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    wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES)
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    wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES)
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    wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES)
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    !wit_shape_is_http(wit) && !wit_shape_is_pubsub(wit) && !wit_shape_is_store(wit)
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
361impl WitContract {
362    /// Substrate-canonical per-`:contratos` caller-Servico scalar
363    /// accessor every consumer that reads the edge's source endpoint
364    /// keys off — returns the author-declared `:contratos :de`
365    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
366    /// own [`String`] storage.
367    ///
368    /// The `:contratos :de` slot names the caller-side member Servico
369    /// on a typed inter-Servico edge (validated by
370    /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
371    /// Aplicacao declares — a stray `:de` that doesn't name a member is
372    /// [`AplicacaoError::ContratoMemberMissing`], not a silent
373    /// caller-attachment miss at cluster-apply time). Peer of the
374    /// sibling [`WitContract::destination`] accessor on the same
375    /// per-`:contratos` entry — the pair `( source(), destination() )`
376    /// jointly names the typed edge every renderer that fans on the
377    /// caller-callee identity keys off (the
378    /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)`
379    /// grouping, the [`AplicacaoSpec::detect_sync_cycles`] adjacency
380    /// map, the per-edge dedup key, the per-edge membership-lookup
381    /// diagnostic).
382    ///
383    /// Prior to this lift the `.de` byte-string was accessed inline at
384    /// four caixa-core sites (the two validate-side membership lookups
385    /// at `!names.contains(c.de.as_str())`, the per-edge dedup-key
386    /// tuple's caller-arm at
387    /// `(c.de.as_str(), c.para.as_str(), c.wit.as_str(), ...)`, the
388    /// `detect_sync_cycles` adjacency `adj.entry(c.de.as_str())`) and
389    /// one caixa-mesh site (the per-`(:de, :para)` CNP grouping's
390    /// caller-arm at `groups.entry((c.de.as_str(), c.para.as_str()))`)
391    /// — five open-coded `.de.as_str()` field-accesses that expressed
392    /// no compile-time link back to the typed slot. A future extension
393    /// of the `:contratos :de` axis to a richer author surface (a
394    /// multi-caller weighted-fan-in overlay per MESH-COMPOSITION §III.2
395    /// canary flow, a per-cluster caller-alias table the operator pins
396    /// through a future `:placement`-scoped slot, the M4
397    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
398    /// admission-webhook that promotes the scalar to a caller-set
399    /// projection) would have had to be threaded through every
400    /// open-coded copy in lockstep or one consumer would silently
401    /// disagree with the peers on which caller Servico a given edge
402    /// resolves to. Lifting the resolution rule to a typed method on
403    /// the substrate primitive means every downstream caller-facing
404    /// consumer reaches for one typed dispatch — the resolver's
405    /// accept-set migrates as a unit on any future axis addition.
406    ///
407    /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
408    /// (6db982c) accessor on the analogous per-ingress-Servico scalar
409    /// axis — same "one typed dispatch on the substrate primitive,
410    /// thin projections at each consumer" discipline extended onto the
411    /// per-`:contratos` caller-Servico byte-string axis.
412    ///
413    /// Declared `pub const fn` — the body composes exclusively through
414    /// the `pub const fn` [`String::as_str`] projection (const-stable
415    /// since Rust 1.87, well within the workspace MSRV), so every
416    /// downstream `const`-context consumer of the per-`:contratos`
417    /// caller-Servico byte-string reaches through the same substrate-
418    /// primitive dispatch at const-eval time as at runtime. Peer of
419    /// the sibling `pub const fn` [`Self::destination`] /
420    /// [`Self::world_ref`] scalar accessors on the same
421    /// per-`:contratos` byte-string trio (the family closure the
422    /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
423    /// locks load-bearing), and mirror on the method-surface of the
424    /// sibling free-function [`wit_shape_matches`] +
425    /// [`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
426    /// [`wit_shape_is_store`] / [`wit_shape_is_capability`] `const`-
427    /// eval-surface pass (d46420c) on the raw `&str → bool` WIT-shape
428    /// dispatch family.
429    #[must_use]
430    pub const fn source(&self) -> &str {
431        self.de.as_str()
432    }
433
434    /// Substrate-canonical per-`:contratos` callee-Servico scalar
435    /// accessor every consumer that reads the edge's destination
436    /// endpoint keys off — returns the author-declared
437    /// `:contratos :para` byte-string verbatim as a `&str`, borrowed
438    /// from the typed slot's own [`String`] storage.
439    ///
440    /// The `:contratos :para` slot names the callee-side member Servico
441    /// on a typed inter-Servico edge (validated by
442    /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
443    /// Aplicacao declares — a stray `:para` that doesn't name a member
444    /// is [`AplicacaoError::ContratoMemberMissing`], not a silent
445    /// callee-attachment miss at cluster-apply time). Callee-side twin
446    /// of the sibling [`WitContract::source`] accessor — the pair
447    /// jointly names the typed edge every renderer that fans on the
448    /// caller-callee identity keys off, and this accessor is also the
449    /// per-`(:de, :para)` L4 port resolver's canonical destination arg:
450    /// under today's typed surface [`AplicacaoSpec::port_for_destination`]
451    /// composes with `destination()` at every emit site that projects a
452    /// per-edge destination Servico's L4 listener port.
453    ///
454    /// Prior to this lift the `.para` byte-string was accessed inline
455    /// at five sites — four caixa-core (the validate-side membership
456    /// lookup at `!names.contains(c.para.as_str())`, the per-edge
457    /// dedup-key tuple's callee-arm, the `detect_sync_cycles`
458    /// adjacency `.insert(c.para.as_str())`, the CNP grouping's
459    /// callee-arm) and one caixa-mesh (the per-`(:de, :para)` CNP L4
460    /// port resolver's destination arg `spec.port_for_destination(&c.para)`)
461    /// — with no compile-time link back to the typed slot. A future
462    /// extension of the `:contratos :para` axis to a richer author
463    /// surface (a multi-callee weighted-fan-out overlay for canary /
464    /// blue-green routing on typed edges, a per-cluster callee-alias
465    /// table the operator pins through a future `:placement`-scoped
466    /// slot, the M4 CR materializer's per-CR admission-webhook that
467    /// promotes the scalar to a callee-set projection) would have had
468    /// to be threaded through every open-coded copy in lockstep or one
469    /// consumer would silently disagree on which callee Servico a given
470    /// edge resolves to (a per-CNP `endpointSelector` that names a
471    /// different destination than its L4 port resolver reads for, a
472    /// dedup-key that treats `(cart, catalog-v2)` and `(cart, catalog)`
473    /// as distinct while the adjacency map collapses them, or vice
474    /// versa). Lifting to a typed method on the substrate primitive
475    /// means every downstream callee-facing consumer reaches for one
476    /// typed dispatch.
477    ///
478    /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
479    /// (6db982c) accessor — both name the "destination-Servico
480    /// byte-string" concept on their respective mesh-slot atoms (per-
481    /// ingress apex vs. per-typed-edge callee), and both extend the
482    /// substrate-primitive-owns-the-resolver discipline onto the
483    /// per-slot destination-Servico scalar axis. Composes with
484    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) at every
485    /// emit-side per-edge L4 port reader — the composition
486    /// `spec.port_for_destination(c.destination())` pins the CNP per-
487    /// `(:de, :para)` L4 port axis to the same typed dispatch the peer
488    /// `HTTPRoute` `backendRefs[0].port` axis reaches through with
489    /// `spec.port_for_destination(entrada.destination())`.
490    ///
491    /// Declared `pub const fn` — sibling in `const`-eval posture to the
492    /// peer `pub const fn` [`Self::source`] / [`Self::world_ref`]
493    /// per-`:contratos` byte-string scalar accessors, all three
494    /// projecting through the `pub const fn` [`String::as_str`]
495    /// (const-stable since Rust 1.87). See [`Self::source`] for the
496    /// family-closure rationale.
497    #[must_use]
498    pub const fn destination(&self) -> &str {
499        self.para.as_str()
500    }
501
502    /// Substrate-canonical per-`:contratos` WIT-world-reference scalar
503    /// accessor every consumer that reads the edge's WIT world
504    /// discriminator keys off — returns the author-declared
505    /// `:contratos :wit` byte-string verbatim as a `&str`, borrowed from
506    /// the typed slot's own [`String`] storage.
507    ///
508    /// The `:contratos :wit` slot names the WIT world the typed edge
509    /// carries (e.g. `"wasi:http/proxy"`, `"nats:pub-sub"`,
510    /// `"wasi:keyvalue/store"`); validated by [`WitContract::target`] to
511    /// be a well-shaped WIT world reference via
512    /// [`crate::render::is_wit_world_ref`] and by
513    /// [`AplicacaoSpec::validate`] to be non-empty via the narrower
514    /// [`AplicacaoError::EmptyWit`] variant. Peer of the sibling
515    /// [`WitContract::source`] / [`WitContract::destination`] accessors
516    /// on the same per-`:contratos` entry — the triple
517    /// `( source(), destination(), world_ref() )` jointly names the
518    /// typed edge every renderer that fans on the caller-callee-shape
519    /// identity keys off (the per-edge dedup key at
520    /// [`AplicacaoSpec::validate`]'s duplicate-`:contratos` gate, the
521    /// per-`(:de, :para)` CNP grouping's shape-arm classifier at
522    /// [`caixa_mesh::cilium_network_policies`], the
523    /// [`WitContract::is_http`] / [`is_pubsub`][WitContract::is_pubsub]
524    /// / [`is_store`][WitContract::is_store] shape-dispatch predicates,
525    /// the [`feira app graph`][fag] per-edge printer's WIT-shape label).
526    ///
527    /// Prior to this lift the `.wit` byte-string was accessed inline at
528    /// five sites — three caixa-core (the `WitContract::is_*` shape-
529    /// dispatch predicates' `&self.wit` arg, the validate-side empty
530    /// check at `if c.wit.is_empty()`, the per-edge dedup-key tuple's
531    /// shape arm at `c.wit.as_str()`) and one caixa-feira (the app-graph
532    /// printer's `{}` format-slot at `c.wit`) — five open-coded
533    /// `.wit` field-accesses that expressed no compile-time link back to
534    /// the typed slot. A future extension of the `:contratos :wit` axis
535    /// to a richer author surface (an M4 promotion from `String` to a
536    /// typed WIT-world enum once the WIT registry stabilizes in tatara-
537    /// lisp per this struct's own `:wit` field docstring, a per-cluster
538    /// WIT-alias table the operator pins through a future
539    /// `:placement`-scoped slot, a canonicalization pass that lowercases
540    /// `wasi:*` prefixes) would have had to be threaded through every
541    /// open-coded copy in lockstep or one consumer would silently
542    /// disagree with the peers on which WIT shape a given edge resolves
543    /// to (a per-CNP L7 emission that read `wasi:http/proxy` while the
544    /// dedup key read the pre-canonicalized `WASI:HTTP/proxy`, an
545    /// empty-check that missed a whitespace-only string a peer accessor
546    /// stripped, or vice versa). Lifting to a typed method on the
547    /// substrate primitive means every downstream WIT-shape-facing
548    /// consumer reaches for one typed dispatch — the resolver's
549    /// accept-set migrates as a unit on any future axis addition.
550    ///
551    /// Sibling of the peer per-`:contratos` [`WitContract::source`] /
552    /// [`WitContract::destination`] (7f0fd43), per-`:entrada`
553    /// [`Entrada::hostname`] / [`Entrada::destination`] (11f3dfe /
554    /// 6db982c), per-`:membros` [`Membro::nome`] /
555    /// [`Membro::versao_requirement`] (4a32abf / a40b0e3) accessors on
556    /// the mesh-slot-atom scalar-value axes — same "one typed dispatch
557    /// on the substrate primitive, thin projections at each consumer"
558    /// discipline extended onto the last unlifted per-`:contratos`
559    /// scalar (the WIT-world-reference arm).
560    ///
561    /// [fag]: caixa-feira/src/cmd/app.rs
562    ///
563    /// Declared `pub const fn` — sibling in `const`-eval posture to the
564    /// peer `pub const fn` [`Self::source`] / [`Self::destination`]
565    /// per-`:contratos` byte-string scalar accessors on the trio, and
566    /// the load-bearing enabler for the paired `pub const fn`
567    /// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] /
568    /// [`Self::is_capability`] WIT-shape-predicate family (each
569    /// composes as `wit_shape_is_<arm>(self.world_ref())` and inherits
570    /// the `const`-eval posture by construction once this accessor
571    /// carries it). See [`Self::source`] for the family-closure
572    /// rationale and the paired
573    /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
574    /// for the load-bearing witness.
575    #[must_use]
576    pub const fn world_ref(&self) -> &str {
577        self.wit.as_str()
578    }
579
580    /// Substrate-canonical per-`:contratos` `:endpoint` HTTP-shaped
581    /// payload-target scalar accessor every consumer that reads the
582    /// edge's L7 HTTP request path payload keys off — returns the
583    /// author-declared `:contratos :endpoint` byte-string verbatim as
584    /// an `Option<&str>`, borrowed from the typed slot's own
585    /// `Option<String>` storage; `None` when the slot is absent (the
586    /// canonical shape of a non-HTTP-`:wit`-world edge — pub-sub
587    /// `nats:*`/`kafka:*` carries `:subject` instead, key/value
588    /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
589    /// [`WitTarget::Capability`] edge carries none of the three).
590    ///
591    /// The `:contratos :endpoint` slot carries the HTTP request path
592    /// payload (Cilium L7 `path:` + Gateway API v1 `PathPrefix` grammar
593    /// — same shape required of `:entrada :paths`, gated by the shared
594    /// [`crate::render::is_gateway_api_http_path`] predicate) that
595    /// [`WitContract::target`] projects onto the [`WitTarget::Http`]
596    /// arm's `endpoint: &'a str` payload when the edge's `:wit` world
597    /// matches the [`WIT_HTTP_SHAPE_PREFIXES`] accept-set. Every
598    /// downstream consumer that reads the payload keys off this scalar
599    /// (the [`WitContract::target`] Http-arm payload extraction that
600    /// materializes [`WitTarget::Http { endpoint }`] under the paired
601    /// [`WitTarget::HTTP_FIELD_NAME`] label, the
602    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
603    /// key's endpoint arm that pins the payload as part of the six-tuple
604    /// dedup key alongside the sibling `:subject`/`:slot` arms, the
605    /// future M4 per-edge WIT registry resolver's HTTP-arm materializer,
606    /// the future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
607    /// per-edge L7 admission webhook, the future caixa-mesh L7 CNP
608    /// emission path that lands the payload verbatim as a Cilium L7
609    /// `path:` rule).
610    ///
611    /// Prior to this lift the `.endpoint` field was accessed inline at
612    /// two production sites in `caixa-core/src/aplicacao.rs` — the
613    /// [`WitContract::target`] payload-shape dispatch's `let endpoint =
614    /// self.endpoint.as_deref();` binding at the top of the method, and
615    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
616    /// tuple's `c.endpoint.as_deref()` HTTP-arm slot — two open-coded
617    /// field-accesses that expressed no compile-time link back to the
618    /// typed slot. A future extension of the `:contratos :endpoint`
619    /// axis to a richer author surface (an M4 promotion from
620    /// `Option<String>` to a typed HTTP path-template enum once the
621    /// WIT registry stabilizes path-parameter shapes in tatara-lisp per
622    /// this struct's own `:wit` field docstring, a per-cluster endpoint-
623    /// alias table the operator pins through a future `:placement`-
624    /// scoped slot, a canonicalization pass that percent-encodes non-
625    /// ASCII path segments, a per-CR fully-qualified rewrite the M4 CR
626    /// materializer applies per-tenant) would have had to be threaded
627    /// through both open-coded copies in lockstep or the two consumers
628    /// would silently disagree on which HTTP path a given edge resolves
629    /// to — the [`WitContract::target`] payload-extraction reading
630    /// `"/lookup"` while the [`AplicacaoSpec::validate`] dedup key read
631    /// the operator-resolved `"/tenant-a/lookup"` would silently split
632    /// the [`WitTarget::Http`]-arm rendered payload from the actual
633    /// dedup-key uniqueness axis, a two-consumer split at the validator
634    /// far from the source `caixa.lisp` with no field naming the
635    /// payload-drift root cause. Lifting the resolution rule to a typed
636    /// method on the substrate primitive means every downstream
637    /// HTTP-payload-facing consumer of the Aplicacao's per-`:contratos`
638    /// L7-payload surface reaches for exactly one typed dispatch — the
639    /// resolver's accept-set migrates as a unit on any future axis
640    /// addition.
641    ///
642    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
643    /// (7cd2a28) / [`Placement::affinity`] (74ec2d3) `Option<&str>`
644    /// accessors on the M3 mesh-slot family — same "one typed dispatch
645    /// on the substrate primitive, thin projections at each consumer"
646    /// discipline extended onto the per-`:contratos` HTTP-shaped
647    /// payload-carrier `Option<String>` optional-scalar axis. First
648    /// `Option<&str>`-return accessor on the per-`:contratos` mesh-slot
649    /// atom — opens the "optional per-slot payload-carrier scalar"
650    /// projection pattern the sibling per-`:contratos` `:subject` /
651    /// `:slot` future lifts fold on, matching the closed
652    /// per-`:contratos` scalar-value accessor family
653    /// ([`WitContract::source`] / [`WitContract::destination`] /
654    /// [`WitContract::world_ref`]) already lifted onto the mandatory-
655    /// scalar `String` axes. Named `endpoint()` to match the storage
656    /// field's name and the paired [`WitTarget::HTTP_FIELD_NAME`]
657    /// author-facing label const; the accessor's identity name maps
658    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
659    /// docstring already carries.
660    #[must_use]
661    pub const fn endpoint(&self) -> Option<&str> {
662        match &self.endpoint {
663            Some(s) => Some(s.as_str()),
664            None => None,
665        }
666    }
667
668    /// Substrate-canonical per-`:contratos` `:subject` pub-sub-shaped
669    /// payload-target scalar accessor every consumer that reads the
670    /// edge's NATS / Kafka publish subject payload keys off — returns
671    /// the author-declared `:contratos :subject` byte-string verbatim
672    /// as an `Option<&str>`, borrowed from the typed slot's own
673    /// `Option<String>` storage; `None` when the slot is absent (the
674    /// canonical shape of a non-pub-sub-`:wit`-world edge — HTTP
675    /// `wasi:http/*`/`http:*` carries `:endpoint` instead, key/value
676    /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
677    /// [`WitTarget::Capability`] edge carries none of the three).
678    ///
679    /// The `:contratos :subject` slot carries the NATS / Kafka publish
680    /// subject payload (the [`WIT_PUBSUB_SHAPE_PREFIXES`] dispatch arm's
681    /// per-edge target selector — `orders.paid`, `events.>`, whatever
682    /// subject namespace the author names on the pub-sub edge) that
683    /// [`WitContract::target`] projects onto the [`WitTarget::PubSub`]
684    /// arm's `subject: &'a str` payload when the edge's `:wit` world
685    /// matches the [`WIT_PUBSUB_SHAPE_PREFIXES`] accept-set. Every
686    /// downstream consumer that reads the payload keys off this scalar
687    /// (the [`WitContract::target`] PubSub-arm payload extraction that
688    /// materializes [`WitTarget::PubSub { subject }`] under the paired
689    /// [`WitTarget::PUBSUB_FIELD_NAME`] label, the
690    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
691    /// key's subject arm that pins the payload as part of the six-tuple
692    /// dedup key alongside the sibling `:endpoint`/`:slot` arms, the
693    /// future M4 per-edge WIT registry resolver's pub-sub-arm
694    /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
695    /// materializer's per-edge NATS admission webhook, the future
696    /// caixa-mesh L4 CNP emission path that lands the payload verbatim
697    /// as a NATS subject the operator pins per-CR).
698    ///
699    /// Prior to this lift the `.subject` field was accessed inline at
700    /// two production sites in `caixa-core/src/aplicacao.rs` — the
701    /// [`WitContract::target`] payload-shape dispatch's `let subject =
702    /// self.subject.as_deref();` binding at the top of the method, and
703    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
704    /// tuple's `c.subject.as_deref()` pub-sub-arm slot — two open-coded
705    /// field-accesses that expressed no compile-time link back to the
706    /// typed slot. A future extension of the `:contratos :subject` axis
707    /// to a richer author surface (an M4 promotion from `Option<String>`
708    /// to a typed NATS-subject-template enum once the WIT registry
709    /// stabilizes wildcard / hierarchy shapes in tatara-lisp per this
710    /// struct's own `:wit` field docstring, a per-cluster subject-alias
711    /// table the operator pins through a future `:placement`-scoped
712    /// slot, a canonicalization pass that lowercases / dedupes wildcard
713    /// segments, a per-CR fully-qualified rewrite the M4 CR materializer
714    /// applies per-tenant) would have had to be threaded through both
715    /// open-coded copies in lockstep or the two consumers would silently
716    /// disagree on which NATS subject a given edge resolves to — the
717    /// [`WitContract::target`] payload-extraction reading `"orders.paid"`
718    /// while the [`AplicacaoSpec::validate`] dedup key read the operator-
719    /// resolved `"tenant-a.orders.paid"` would silently split the
720    /// [`WitTarget::PubSub`]-arm rendered payload from the actual dedup-
721    /// key uniqueness axis, a two-consumer split at the validator far
722    /// from the source `caixa.lisp` with no field naming the payload-
723    /// drift root cause. Lifting the resolution rule to a typed method
724    /// on the substrate primitive means every downstream pub-sub-payload-
725    /// facing consumer of the Aplicacao's per-`:contratos` L4-payload
726    /// surface reaches for exactly one typed dispatch — the resolver's
727    /// accept-set migrates as a unit on any future axis addition.
728    ///
729    /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
730    /// (7020470) `Option<&str>` accessor on the M3 mesh-slot payload-
731    /// carrier axis — second `Option<&str>`-return accessor on the
732    /// per-`:contratos` mesh-slot atom, extending the "optional per-slot
733    /// payload-carrier scalar" projection pattern the [`WitContract::endpoint`]
734    /// HTTP-arm lift opened onto the pub-sub arm; leaves the [`WitContract::slot`]
735    /// key/value-store arm as the last unlifted per-`:contratos`
736    /// `Option<String>` axis. Named `subject()` to match the storage
737    /// field's name and the paired [`WitTarget::PUBSUB_FIELD_NAME`]
738    /// author-facing label const; the accessor's identity name maps
739    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
740    /// docstring already carries.
741    #[must_use]
742    pub const fn subject(&self) -> Option<&str> {
743        match &self.subject {
744            Some(s) => Some(s.as_str()),
745            None => None,
746        }
747    }
748
749    /// Substrate-canonical per-`:contratos` `:slot` key/value-store-
750    /// shaped payload-target scalar accessor every consumer that reads
751    /// the edge's `wasi:keyvalue/*` / `kv:*` key-template payload keys
752    /// off — returns the author-declared `:contratos :slot` byte-string
753    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
754    /// own `Option<String>` storage; `None` when the slot is absent
755    /// (the canonical shape of a non-store-`:wit`-world edge — HTTP
756    /// `wasi:http/*`/`http:*` carries `:endpoint` instead, pub-sub
757    /// `nats:*`/`kafka:*` carries `:subject` instead, and a plain
758    /// [`WitTarget::Capability`] edge carries none of the three).
759    ///
760    /// The `:contratos :slot` slot carries the key/value store
761    /// key-template payload (the [`WIT_STORE_SHAPE_PREFIXES`] dispatch
762    /// arm's per-edge target selector — `carts/{cart_id}`,
763    /// `sessions/{tenant}/{sid}`, whatever key-template the author
764    /// names on the store edge) that [`WitContract::target`] projects
765    /// onto the [`WitTarget::Store`] arm's `slot: &'a str` payload when
766    /// the edge's `:wit` world matches the [`WIT_STORE_SHAPE_PREFIXES`]
767    /// accept-set. Every downstream consumer that reads the payload
768    /// keys off this scalar (the [`WitContract::target`] Store-arm
769    /// payload extraction that materializes [`WitTarget::Store { slot }`]
770    /// under the paired [`WitTarget::STORE_FIELD_NAME`] label, the
771    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
772    /// key's store arm that pins the payload as part of the six-tuple
773    /// dedup key alongside the sibling `:endpoint`/`:subject` arms,
774    /// the future M4 per-edge WIT registry resolver's store-arm
775    /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
776    /// materializer's per-edge key/value admission webhook, the future
777    /// caixa-mesh L4 CNP emission path that lands the payload verbatim
778    /// as a key-template the operator pins per-CR).
779    ///
780    /// Prior to this lift the `.slot` field was accessed inline at two
781    /// production sites in `caixa-core/src/aplicacao.rs` — the
782    /// [`WitContract::target`] payload-shape dispatch's `let slot =
783    /// self.slot.as_deref();` binding at the top of the method, and
784    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
785    /// tuple's `c.slot.as_deref()` store-arm slot — two open-coded
786    /// field-accesses that expressed no compile-time link back to the
787    /// typed slot. A future extension of the `:contratos :slot` axis
788    /// to a richer author surface (an M4 promotion from `Option<String>`
789    /// to a typed key-template enum once the WIT registry stabilizes
790    /// key-template parameter shapes in tatara-lisp per this struct's
791    /// own `:wit` field docstring, a per-cluster slot-alias table the
792    /// operator pins through a future `:placement`-scoped slot, a
793    /// canonicalization pass that lowercases the bucket prefix, a
794    /// per-CR fully-qualified rewrite the M4 CR materializer applies
795    /// per-tenant) would have had to be threaded through both
796    /// open-coded copies in lockstep or the two consumers would
797    /// silently disagree on which key-template a given edge resolves
798    /// to — the [`WitContract::target`] payload-extraction reading
799    /// `"carts/{cart_id}"` while the [`AplicacaoSpec::validate`] dedup
800    /// key read the operator-resolved `"tenant-a/carts/{cart_id}"`
801    /// would silently split the [`WitTarget::Store`]-arm rendered
802    /// payload from the actual dedup-key uniqueness axis, a
803    /// two-consumer split at the validator far from the source
804    /// `caixa.lisp` with no field naming the payload-drift root cause.
805    /// Lifting the resolution rule to a typed method on the substrate
806    /// primitive means every downstream store-payload-facing consumer
807    /// of the Aplicacao's per-`:contratos` payload surface reaches for
808    /// exactly one typed dispatch — the resolver's accept-set migrates
809    /// as a unit on any future axis addition.
810    ///
811    /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
812    /// (7020470) / [`WitContract::subject`] (90de675) `Option<&str>`
813    /// accessors on the M3 mesh-slot payload-carrier axis — third and
814    /// final `Option<&str>`-return accessor on the per-`:contratos`
815    /// mesh-slot atom, closes the last unlifted per-`:contratos`
816    /// `Option<String>` axis and completes the "optional per-slot
817    /// payload-carrier scalar" projection pattern the peer HTTP /
818    /// pub-sub arms established across the three payload-shape
819    /// dispatch arms. Named `slot()` to match the storage field's
820    /// name and the paired [`WitTarget::STORE_FIELD_NAME`]
821    /// author-facing label const; the accessor's identity name maps
822    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
823    /// docstring already carries.
824    #[must_use]
825    pub const fn slot(&self) -> Option<&str> {
826        match &self.slot {
827            Some(s) => Some(s.as_str()),
828            None => None,
829        }
830    }
831
832    /// Substrate-canonical per-`:contratos` `(caller, callee)` owned-form
833    /// caller-callee-pair accessor every consumer that constructs an
834    /// [`AplicacaoError`] variant carrying the per-edge `(de, para)`
835    /// caller-callee pair keys off — returns the author-declared
836    /// `:contratos :de` / `:contratos :para` byte-strings verbatim as an
837    /// owned `(String, String)` tuple, projected through the lifted
838    /// [`WitContract::source`] / [`WitContract::destination`] scalar
839    /// accessors so any future rebrand on the caller-arm / callee-arm
840    /// projection axis (an M4 per-cluster caller-alias table the
841    /// operator pins through a future `:placement`-scoped slot, a
842    /// namespace-qualified rewrite the M4 CR materializer applies per-CR,
843    /// a per-`:membros` alias overlay from the future `:membros
844    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
845    /// acknowledges) reaches every diagnostic-construction site by
846    /// construction.
847    ///
848    /// The `(de, para)` pair is the "typed-edge caller-callee identity in
849    /// owned form" primitive every per-`:contratos` diagnostic variant on
850    /// [`AplicacaoError`] carries alongside its payload-shape arm — the
851    /// nine variants [`AplicacaoError::EmptyWit`],
852    /// [`AplicacaoError::ContratoEndpointEmpty`],
853    /// [`AplicacaoError::ContratoEndpointNotAbsolute`],
854    /// [`AplicacaoError::ContratoEndpointInvalid`],
855    /// [`AplicacaoError::ContratoSubjectEmpty`],
856    /// [`AplicacaoError::ContratoSubjectInvalid`],
857    /// [`AplicacaoError::ContratoSlotEmpty`],
858    /// [`AplicacaoError::ContratoSlotInvalid`], and
859    /// [`AplicacaoError::ContratoDuplicate`] each carry a `de: String,
860    /// para: String` field pair the constructor site reads verbatim off
861    /// the [`WitContract`] the diagnostic points at, so a diagnostic
862    /// whose `de:` and `para:` labels silently drift off the source
863    /// caller/callee — a per-cluster caller-alias rewrite that landed on
864    /// one variant's inline `de: c.de.clone()` field access but not on
865    /// its sibling variant's, an accidental swap of the `de:` and `para:`
866    /// arms in a copy-paste of the constructor block — would emit a
867    /// build-time error whose "which caixa is at fault" question the
868    /// operator answers wrongly, far from the source `caixa.lisp`.
869    ///
870    /// Prior to this lift the `(self.de.clone(), self.para.clone())`
871    /// pair was inlined at seven [`WitContract::target`] error-
872    /// construction sites (the [`AplicacaoError::ContratoEndpointEmpty`]
873    /// / [`AplicacaoError::ContratoEndpointNotAbsolute`] /
874    /// [`AplicacaoError::ContratoEndpointInvalid`] HTTP-arm variants,
875    /// the [`AplicacaoError::ContratoSubjectEmpty`] /
876    /// [`AplicacaoError::ContratoSubjectInvalid`] pub-sub-arm variants,
877    /// the [`AplicacaoError::ContratoSlotEmpty`] /
878    /// [`AplicacaoError::ContratoSlotInvalid`] store-arm variants) and
879    /// two [`AplicacaoSpec::validate`] error-construction sites (the
880    /// [`AplicacaoError::EmptyWit`] empty-`:wit` gate, the
881    /// [`AplicacaoError::ContratoDuplicate`] duplicate-`:contratos`
882    /// insert-first-seen closure) — nine open-coded `.de.clone() +
883    /// .para.clone()` pairs that expressed no compile-time contract that
884    /// the caller-arm and callee-arm arms of the same diagnostic
885    /// construction reach for the same [`WitContract`] instance or that
886    /// the `de:` and `para:` label pair binds to the fields the author
887    /// declared. Any future rebrand on the axis — an M4 per-cluster
888    /// caller/callee-alias rewrite the operator pins through a future
889    /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
890    /// per-CR fully-qualified namespace prefix the M4
891    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
892    /// per-tenant, a canonicalization pass that lowercases the caller +
893    /// callee identifiers post-parse — would have had to be threaded
894    /// through every open-coded copy in lockstep or one variant's
895    /// diagnostic would silently name a different caller/callee pair
896    /// than its peer, silently degrading the "which caixa is at fault"
897    /// self-locating signal every operator-facing typed diagnostic
898    /// exists to carry. Lifting the pair to a typed method on the
899    /// substrate primitive means every downstream diagnostic-construction
900    /// site reaches for exactly one typed dispatch — the resolver's
901    /// projection migrates as a unit on any future axis addition.
902    ///
903    /// Peer of the sibling per-`:contratos` scalar accessor family
904    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43)
905    /// / [`WitContract::world_ref`] (6226bf4) on the mesh-slot-atom
906    /// scalar-value axes — first composite-projection accessor on the
907    /// per-`:contratos` mesh-slot atom, folds the two open-coded owned-
908    /// form `.clone()` field-accesses that pair the sibling
909    /// caller/callee accessors' `&str`-return borrowed-form outputs onto
910    /// one typed dispatch. Named `edge_pair()` to reflect the identity
911    /// name of the projected tuple (the typed-edge caller-callee pair,
912    /// distinct from the sibling triple-projection
913    /// [`WitContract::edge_triple`] accessor that folds the local `edge`
914    /// closure in [`WitContract::target`] + the paired
915    /// [`AplicacaoError::ContratoDuplicate`] diagnostic constructor
916    /// site's `(de, para, wit)` triple onto one typed dispatch).
917    #[must_use]
918    pub fn edge_pair(&self) -> (String, String) {
919        (self.source().to_string(), self.destination().to_string())
920    }
921
922    /// Owned form of the `(:contratos :de, :contratos :para, :contratos
923    /// :wit)` triple every per-edge diagnostic constructor that names
924    /// all three axes threads verbatim into its `de:` / `para:` /
925    /// `wit:` fields — the [`WitTarget::target`] dispatch's wrong-target
926    /// / missing-target / invalid-wit / capability-with-payload arms
927    /// (eight sites all shape `let (de, para, wit) = edge();
928    /// AplicacaoError::Contrato* { de, para, wit, .. }` before this
929    /// accessor landed) and the sibling
930    /// [`AplicacaoError::ContratoDuplicate`] duplicate-gate diagnostic
931    /// constructor (which paired `edge_pair()` for the `(de, para)`
932    /// prefix with a raw `c.wit.clone()` for the `wit:` tail — a mixed
933    /// typed-dispatch + raw-field-access shape the sibling accessor
934    /// family already flagged as a drift risk). Nine total call sites
935    /// collapse onto this helper.
936    ///
937    /// Lifted with the same one-source-of-truth discipline
938    /// [`WitContract::edge_pair`] carries on the paired
939    /// caller-callee-only axis: the returned tuple's `.0` / `.1` / `.2`
940    /// arms compose through the lifted [`WitContract::source`] /
941    /// [`WitContract::destination`] / [`WitContract::world_ref`]
942    /// scalar accessors byte-for-byte (pinned by the paired
943    /// [`tests::wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`]
944    /// composition-pin), so any future rebrand on the per-`:contratos`
945    /// caller / callee / world-ref axis (an M4 per-cluster
946    /// caller/callee-alias rewrite the operator pins through a future
947    /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
948    /// per-CR fully-qualified namespace prefix the M4
949    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
950    /// per-tenant, an M4-typed-caller-enum `Display` re-canonicalization
951    /// on `source()` / `destination()`, a per-CR canonicalization pass
952    /// that lowercases the WIT world ref post-parse) migrates as a
953    /// single caixa-core edit rather than a coordinated rewrite of
954    /// nine open-coded triple-constructors.
955    ///
956    /// Peer of the sibling per-`:contratos` composite-projection
957    /// [`WitContract::edge_pair`] accessor on the mesh-slot-atom
958    /// composite-value axes — closes the last unlifted owned-form
959    /// composite-tuple axis on the per-`:contratos` diagnostic-
960    /// construction surface. Named `edge_triple()` to reflect the
961    /// identity name of the projected tuple (the typed-edge
962    /// caller-callee-wit triple, sibling to the caller-callee-only
963    /// pair `edge_pair()` returns).
964    #[must_use]
965    pub fn edge_triple(&self) -> (String, String, String) {
966        (
967            self.source().to_string(),
968            self.destination().to_string(),
969            self.world_ref().to_string(),
970        )
971    }
972
973    /// Borrowed [`ContratoIdentity`] six-tuple every consumer that
974    /// dedups typed edges keys off — routes through the lifted
975    /// [`WitContract::source`] / [`WitContract::destination`] /
976    /// [`WitContract::world_ref`] / [`WitContract::endpoint`] /
977    /// [`WitContract::subject`] / [`WitContract::slot`] scalar
978    /// accessors so the tuple's six arms and the [`ContratoIdentity`]
979    /// type alias's six axes migrate as a unit on any future axis
980    /// addition (adding a seventh field to [`WitContract`] is one
981    /// [`ContratoIdentity`] alias edit + one accessor addition + one
982    /// arm here, not a coordinated rewrite of every open-coded
983    /// six-tuple builder that dedups on the identity axis).
984    ///
985    /// Sibling of [`WitContract::edge_pair`] /
986    /// [`WitContract::edge_triple`] on the composite-projection axis:
987    /// the pair projects the caller-callee axes, the triple extends it
988    /// with the world-ref, this method extends it with the three
989    /// payload-carrier axes. Every projection returns the same six
990    /// scalar accessors' outputs; the three methods differ only in
991    /// which arms they surface.
992    ///
993    /// Declared `pub const fn` — every callee is itself `pub const fn`
994    /// ([`Self::source`] / [`Self::destination`] / [`Self::world_ref`]
995    /// project through `pub const fn` [`String::as_str`], const-stable
996    /// since Rust 1.87; [`Self::endpoint`] / [`Self::subject`] /
997    /// [`Self::slot`] project through the same `String::as_str` under a
998    /// `match &self.<field> { Some(s) => Some(s.as_str()), None => None }`
999    /// arm — the sibling `Option<String> → Option<&str>` shape 0650f64
1000    /// closed the const-eval surface on) and tuple construction from
1001    /// borrowed-reference / `Option`-of-borrowed-reference arms is
1002    /// itself trivially const. The `ContratoIdentity<'_>` alias
1003    /// resolves to a `(&str, &str, &str, Option<&str>, Option<&str>,
1004    /// Option<&str>)` tuple whose every arm is `Copy` — no destructor,
1005    /// no heap allocation, no non-const call folded through the tuple's
1006    /// construction. Sibling in `const`-eval posture to the peer
1007    /// `pub const fn` [`WitContract::is_http`] / [`Self::is_pubsub`] /
1008    /// [`Self::is_store`] / [`Self::is_capability`] WIT-shape-predicate
1009    /// composite-projection family the sibling
1010    /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
1011    /// already anchors — this extends the same `const`-eval-surface
1012    /// posture onto the peer six-arm composite-projection axis where
1013    /// the projection surfaces the full identity tuple rather than a
1014    /// per-`(:de, :para, :wit)`-triple boolean shape probe. Pinned load-
1015    /// bearing by
1016    /// [`wit_contract_identity_projection_accessor_is_const_fn`] below
1017    /// (a future accidental downgrade fires E0015 at the wrapper at
1018    /// caixa-core build time).
1019    #[must_use]
1020    pub const fn identity(&self) -> ContratoIdentity<'_> {
1021        (
1022            self.source(),
1023            self.destination(),
1024            self.world_ref(),
1025            self.endpoint(),
1026            self.subject(),
1027            self.slot(),
1028        )
1029    }
1030
1031    /// True when this contract targets an HTTP-shaped WIT world.
1032    ///
1033    /// Declared `pub const fn` — routes through the paired `pub const
1034    /// fn` [`Self::world_ref`] scalar accessor and the substrate's
1035    /// `pub const fn` free-function classifier [`wit_shape_is_http`]
1036    /// (d46420c). Sibling in `const`-eval posture to the peer
1037    /// `pub const fn` [`Self::is_pubsub`] / [`Self::is_store`] /
1038    /// [`Self::is_capability`] WIT-shape-predicate family; the closed
1039    /// 4-arm partition on the raw `:contratos :wit` axis now carries
1040    /// the same `const`-eval-surface posture as the free-function
1041    /// classifier family it composes through. Pinned load-bearing by
1042    /// the [`wit_contract_pre_projection_accessor_family_is_const_fn`]
1043    /// test (a future accidental downgrade to non-`const` fires E0015
1044    /// at the corresponding `<arm>_via_const_fn` wrapper at caixa-core
1045    /// build time).
1046    #[must_use]
1047    pub const fn is_http(&self) -> bool {
1048        wit_shape_is_http(self.world_ref())
1049    }
1050
1051    /// True when this contract targets a pub-sub-shaped WIT world.
1052    ///
1053    /// Declared `pub const fn` — sibling in `const`-eval posture to
1054    /// the peer `pub const fn` [`Self::is_http`] / [`Self::is_store`] /
1055    /// [`Self::is_capability`] WIT-shape-predicate family. See
1056    /// [`Self::is_http`] for the family-closure rationale.
1057    #[must_use]
1058    pub const fn is_pubsub(&self) -> bool {
1059        wit_shape_is_pubsub(self.world_ref())
1060    }
1061
1062    /// True when this contract targets a key/value-shaped WIT world.
1063    ///
1064    /// Declared `pub const fn` — sibling in `const`-eval posture to
1065    /// the peer `pub const fn` [`Self::is_http`] / [`Self::is_pubsub`] /
1066    /// [`Self::is_capability`] WIT-shape-predicate family. See
1067    /// [`Self::is_http`] for the family-closure rationale.
1068    #[must_use]
1069    pub const fn is_store(&self) -> bool {
1070        wit_shape_is_store(self.world_ref())
1071    }
1072
1073    /// True when this contract targets *none* of the three known payload-
1074    /// shape WIT worlds — the fourth (payload-less) arm of the WIT-shape
1075    /// partition [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
1076    /// open on the [`WitContract`] surface. Returns the exact-inverse
1077    /// disjunction of the peer trio — `true` when none of the three
1078    /// prefix-set predicates matches the raw `:contratos :wit` value; the
1079    /// author-declared WIT world is a pure typed capability edge with no
1080    /// payload selector (the shape [`WitContract::target`] projects onto
1081    /// the payload-less [`WitTarget::Capability`] arm, MESH-COMPOSITION
1082    /// §II.3 — the fourth typed [`WitTarget`] arm the substrate admits).
1083    ///
1084    /// The `:contratos :wit` shape-space is closed at four arms
1085    /// ([`WIT_HTTP_SHAPE_PREFIXES`] / [`WIT_PUBSUB_SHAPE_PREFIXES`] /
1086    /// [`WIT_STORE_SHAPE_PREFIXES`] on the payload-carrying arms;
1087    /// everything else on the payload-less capability arm), and every
1088    /// downstream consumer that must filter contratos by shape-class
1089    /// keys off the four sibling predicates (the [`WitContract::target`]
1090    /// dispatch's implicit `else` after the three payload-shape arm
1091    /// checks at aplicacao.rs:959–1129 that admits [`WitTarget::Capability`],
1092    /// every future substrate-side capability-shape-only emitter — the
1093    /// M4 per-Aplicacao WIT-registry capability-import materializer, the
1094    /// future `feira app graph --capability` per-Aplicacao capability-
1095    /// column filter, the future per-cluster capability-scope reconciler
1096    /// that skips L4/L7 emission for payload-less edges since Cilium
1097    /// can't introspect WASI capability calls, the future
1098    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission webhook's per-
1099    /// shape shape-count histogram). Every such consumer reaches for one
1100    /// typed dispatch on the substrate primitive so the "which arm
1101    /// carries the capability-only shape?" answer lives at one caixa-core
1102    /// edit rather than open-coded across per-consumer
1103    /// `!c.is_http() && !c.is_pubsub() && !c.is_store()` triplet
1104    /// negations, each of which would silently drop a future fourth
1105    /// payload-arm addition without a compile-time signal at the
1106    /// consumer site.
1107    ///
1108    /// Prior to this lift the "not one of the three known payload
1109    /// shapes" classification sat inline at [`WitContract::target`]'s
1110    /// implicit `else`-branch (aplicacao.rs:1131 — the payload-less
1111    /// [`WitTarget::Capability`] admission arm after the three `if
1112    /// self.is_http() { … } if self.is_pubsub() { … } if self.is_store()
1113    /// { … }` guards) with no named accessor for downstream consumers
1114    /// to reach through. A future substrate-side capability-only
1115    /// filter or a future capability-scope reconciler would have had to
1116    /// re-inline the same triplet negation at every emit site with no
1117    /// compile-time link back to the sibling trio, and a future arm
1118    /// addition (a hypothetical fourth payload-shape prefix set — a
1119    /// `wasi:sockets/*` transport-layer shape or an `oci:*` capability-
1120    /// import carrier per the sibling [`wit_shape_matches`] docstring's
1121    /// trajectory bullet) would land the new predicate on the payload-
1122    /// carrying trio and silently misclassify the new shape as
1123    /// capability at every triplet-negation consumer site, propagating
1124    /// the drift far from the caixa-core prefix-set commit.
1125    ///
1126    /// Fourth arm on the [`WitContract`] WIT-shape-predicate family —
1127    /// closes the {[`Self::is_http`], [`Self::is_pubsub`], [`Self::is_store`]}
1128    /// trio into a 4-way partition witness on the raw `:contratos :wit`
1129    /// axis, mirroring the paired post-projection [`WitTarget`]
1130    /// `gen_platform::IsVariant`-derived 4-way predicate set
1131    /// ([`WitTarget::is_http`] / [`WitTarget::is_pubsub`] /
1132    /// [`WitTarget::is_store`] / [`WitTarget::is_capability`]) on the
1133    /// typed-view surface (7f6aa98 `IsVariant` derive lift on the peer
1134    /// arm-set). The two typed axes — pre-projection on the raw
1135    /// `:contratos :wit` string, post-projection on the validated typed
1136    /// view — now carry a matched 4-arm predicate discipline: every
1137    /// arm on the closed [`WitTarget`] set has a peer pre-projection
1138    /// predicate on the [`WitContract`] surface, and any future
1139    /// [`WitTarget`] variant addition (an M4 `Rest` / `Grpc` split of
1140    /// [`WitTarget::Http`] once the WIT registry stabilizes gRPC-shaped
1141    /// worlds per [`WitTarget`]'s own docstring at aplicacao.rs:1341-1343,
1142    /// a `Queue`-shaped peer of [`WitTarget::Store`]) reaches this
1143    /// pre-projection axis through a matching peer prefix-set + peer
1144    /// predicate lift by construction — the compile-time exhaustiveness
1145    /// on [`WitTarget::payload_pair`]'s single dispatch already enforces
1146    /// the post-projection accessor family stays in sync, and the sibling
1147    /// [`tests::wit_contract_is_capability_partitions_the_wit_shape_space`]
1148    /// partition-witness pin locks the pre-projection classification in
1149    /// load-bearing so a peer prefix-set addition that widened one arm's
1150    /// accept-set without shrinking the [`Self::is_capability`] accept-set
1151    /// surfaces as a test failure at caixa-core build time rather than a
1152    /// silent per-consumer split at renderer emit time.
1153    ///
1154    /// Composes byte-for-byte through the lifted peer trio
1155    /// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] so
1156    /// any future rebrand of any prefix-set const flows through this
1157    /// method by construction without a coordinated per-consumer rewrite
1158    /// (pinned by the sibling
1159    /// [`tests::wit_contract_is_capability_composes_through_shape_predicate_negation`]
1160    /// composition-witness).
1161    ///
1162    /// Note: purely syntactic classification on the `:wit` prefix-set —
1163    /// unlike [`Self::target`], which additionally rejects value-shape-
1164    /// invalid `:wit` strings (uppercase, hyphen-for-colon typo, empty
1165    /// package) via [`crate::render::is_wit_world_ref`] and payload-
1166    /// shape mismatches. A [`WitContract`] whose `:wit` is empty or
1167    /// structurally malformed returns `true` from `is_capability()` (the
1168    /// prefix set matches nothing), and the surrounding
1169    /// [`AplicacaoSpec::validate`] / [`WitContract::target`] gate cascade
1170    /// is where the [`AplicacaoError::EmptyWit`] /
1171    /// [`AplicacaoError::ContratoWitInvalid`] diagnostic surfaces — this
1172    /// predicate is the classifier, not the validator.
1173    ///
1174    /// Declared `pub const fn` — closes the WIT-shape-predicate
1175    /// family's `const`-eval-surface pass at the fourth (payload-less)
1176    /// arm; peer of the sibling `pub const fn` [`Self::is_http`] /
1177    /// [`Self::is_pubsub`] / [`Self::is_store`] payload-arm predicates.
1178    /// See [`Self::is_http`] for the family-closure rationale.
1179    #[must_use]
1180    pub const fn is_capability(&self) -> bool {
1181        wit_shape_is_capability(self.world_ref())
1182    }
1183
1184    /// True when this contract's caller equals its callee — a
1185    /// structurally degenerate typed edge that no `:contratos` entry can
1186    /// legitimately carry (MESH-COMPOSITION §III.1 — "Servico A calls
1187    /// Servico B" is an *inter*-Servico contract between two distinct
1188    /// graph nodes). A Servico contracting with itself resolves to an
1189    /// in-process call the wasm-engine never routes through the mesh at
1190    /// all, so no rendered `CiliumNetworkPolicy` / `HTTPRoute` /
1191    /// per-edge policy can express the intended shape — the pub-sub
1192    /// path silently rendered a self-allow rule that is a no-op (intra-
1193    /// pod traffic bypasses the mesh entirely), and the synchronous
1194    /// paths surfaced as a misleading `ContratoCycle` whose path was
1195    /// `["cart", "cart"]` — framing a self-edge as a multi-node
1196    /// deadlock. Every downstream consumer that must reject the shape
1197    /// (the [`AplicacaoSpec::validate`] per-`:contratos` self-loop
1198    /// gate at caixa-core/src/aplicacao.rs:5559, every future
1199    /// per-`:contratos`-edge policy resolver on the M4 CR materializer
1200    /// axis, every future adjacency-graph builder that must skip self-
1201    /// edges rather than fold them into an incidental cycle) now keys
1202    /// off exactly one typed dispatch on the substrate primitive, so
1203    /// any future rebrand on the axis (an M4-typed-caller enum whose
1204    /// identity comparison rule the accessor could route through, an
1205    /// operator-side per-cluster caller/callee-alias table the
1206    /// materializer resolves per-CR before the equality probe, a
1207    /// promotion of the pointwise `==` to a set-membership check once
1208    /// SimpleOneForOne-shaped dynamic replicas come into typed scope
1209    /// so a per-replica self-edge is rejected under the same predicate)
1210    /// migrates as a single caixa-core edit rather than a coordinated
1211    /// rewrite of every downstream self-edge consumer. Composes
1212    /// byte-for-byte through the lifted [`Self::source`] /
1213    /// [`Self::destination`] scalar accessors — the accessor pair every
1214    /// per-`:contratos` scalar-value axis already routes through — so
1215    /// any future rebrand of the underlying `:de` / `:para` storage
1216    /// (a lift from `String` to a typed `ServicoName(String)` newtype,
1217    /// a per-Aplicacao interning arena the M4 CR materializer authors,
1218    /// a `smol_str::SmolStr` inline-buffer swap) flows through the
1219    /// same one body without a coordinated per-consumer rewrite.
1220    ///
1221    /// Sibling in shape to the peer per-`:contratos` shape-predicate
1222    /// family [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
1223    /// on the `:wit` world-ref axis — extended onto the per-edge
1224    /// endpoint-equality axis: `is_http` / `is_pubsub` / `is_store`
1225    /// partition the WIT-shape-space; `is_self_loop` partitions the
1226    /// caller-callee identity-space. Named `is_self_loop()` to reflect
1227    /// the graph-theoretic identity of the shape (a loop from a graph
1228    /// node to itself, distinct from the sibling multi-node
1229    /// `ContratoCycle` shape [`Self::detect_sync_cycles`] rejects) and
1230    /// to match the [`AplicacaoError::ContratoSelfLoop`] diagnostic
1231    /// variant already carrying the term.
1232    ///
1233    /// Declared `pub const fn` — closes the last unlifted per-`:contratos`
1234    /// shape-predicate on the substrate's `const`-eval surface. The peer
1235    /// per-`:contratos` shape-predicate family [`Self::is_http`] /
1236    /// [`Self::is_pubsub`] / [`Self::is_store`] / [`Self::is_capability`]
1237    /// (d46420c / 84c2325 / 279823b) already carries the `pub const fn`
1238    /// posture on the WIT-world-ref classifier axis; this lift extends it
1239    /// onto the peer caller-callee identity-space predicate. The body
1240    /// projects the `:de` / `:para` `String` storage through the sibling
1241    /// `pub const fn` [`Self::source`] / [`Self::destination`] scalar
1242    /// accessors, then compares the resulting `&str` byte-slices under a
1243    /// manual `while`-loop through `str::as_bytes` (`pub const fn`,
1244    /// const-stable since Rust 1.39), primitive-`usize` `!=` on
1245    /// [`<[u8]>::len`], and const-stable slice indexing (since Rust 1.79)
1246    /// — every operation `const`-eval-callable on stable Rust, no
1247    /// iterator methods, no `PartialEq for str` trait dispatch (which
1248    /// remains non-`const` on stable). Mirrors the peer `pub const fn`
1249    /// [`wit_shape_matches`] combinator's manual byte-level `starts_with`
1250    /// loop verbatim on the paired-slice-equality shape. Every downstream
1251    /// substrate-side `const`-context consumer of the per-`:contratos`
1252    /// self-edge partition (a future `const _: () = assert!(…)` module-
1253    /// scope invariant pin over a per-fixture typed [`WitContract`] once
1254    /// the type's carriers admit `const`-context construction, a future
1255    /// M4 admission-webhook `const fn` self-edge resolver, any `const fn`
1256    /// composer that fans on the identity-space partition at compile
1257    /// time) reaches through the same typed dispatch on the substrate
1258    /// primitive at const-eval time as at runtime. Pinned by
1259    /// [`tests::wit_contract_is_self_loop_predicate_is_const_fn`] which
1260    /// witnesses the `const`-eval posture via a `const fn` wrapper so any
1261    /// future accidental downgrade to non-`const` trips at caixa-core
1262    /// build time with E0015 (`cannot call non-const method`), strictly
1263    /// stronger than a runtime `assert!`.
1264    #[must_use]
1265    pub const fn is_self_loop(&self) -> bool {
1266        // Compose through the paired `pub const fn` [`Self::source`] /
1267        // [`Self::destination`] scalar accessors so any future rebrand of
1268        // the underlying `:de` / `:para` storage (a lift from `String` to
1269        // a typed `ServicoName(String)` newtype, a per-Aplicacao interning
1270        // arena the M4 CR materializer authors, a `smol_str::SmolStr`
1271        // inline-buffer swap) flows through the same one body without a
1272        // coordinated per-consumer rewrite. Peer of the sibling
1273        // [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] /
1274        // [`Self::is_capability`] shape-predicate family — each of which
1275        // composes through the paired [`Self::world_ref`] scalar accessor
1276        // onto the peer `pub const fn` [`wit_shape_is_http`] /
1277        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
1278        // [`wit_shape_is_capability`] free-function classifier — the same
1279        // "typed dispatch composes with typed dispatch, not raw field
1280        // access" discipline extended onto the caller-callee identity-
1281        // space partition. Pinned by
1282        // [`tests::wit_contract_is_self_loop_routes_through_source_destination_accessors`]
1283        // above.
1284        let a = self.source().as_bytes();
1285        let b = self.destination().as_bytes();
1286        if a.len() != b.len() {
1287            return false;
1288        }
1289        // Manual byte-level equality loop — mirrors the peer
1290        // [`wit_shape_matches`] combinator's manual `starts_with` loop
1291        // verbatim on the paired-slice-equality shape. `PartialEq for
1292        // str` remains non-`const` on stable Rust 1.94 (the `Pattern`
1293        // trait dispatch it routes through is not `const`), so a naive
1294        // `self.source() == self.destination()` body would trip on
1295        // `const`-eval-callability; the byte-slice loop dispatches
1296        // through primitive-`u8` `!=`, primitive-`usize` comparison, and
1297        // const-stable slice indexing (since Rust 1.79) — every
1298        // operation `const`-eval-callable on stable.
1299        let mut i = 0;
1300        while i < a.len() {
1301            if a[i] != b[i] {
1302                return false;
1303            }
1304            i += 1;
1305        }
1306        true
1307    }
1308
1309    /// Reject a `:contratos` entry whose `:de` or `:para` names a
1310    /// caixa the `:membros` graph does not contain — the substrate-
1311    /// primitive per-edge graph-membership gate every consumer of the
1312    /// typed inter-Servico edge's endpoint-resolution axis reaches
1313    /// through one dispatch.
1314    ///
1315    /// A `:contratos` entry is a typed directed edge between two
1316    /// declared members (MESH-COMPOSITION §III.1 — "the typed edges
1317    /// address graph nodes, so a reference to a node the graph does
1318    /// not contain is a build error"). Both endpoints must resolve
1319    /// against the same [`AplicacaoSpec::membro_names`] oracle: the
1320    /// paired [`AplicacaoError::ContratoMemberMissing`] diagnostic
1321    /// framing does not distinguish `:de` from `:para` (both arms
1322    /// carry the offending `caixa` name verbatim without a
1323    /// slot-discriminator field, unlike the sibling per-arm shape
1324    /// gate [`validate_contrato_caixa`] whose paired
1325    /// [`AplicacaoError::ContratoCaixaEmpty`] / `ContratoCaixaInvalid`
1326    /// variants each carry a `slot: &'static str` tag). So the two
1327    /// arms are byte-identical modulo the accessor projection they
1328    /// key off, and folding them into one per-edge dispatch preserves
1329    /// every existing diagnostic-fired output byte-for-byte while
1330    /// closing the last inline duplication the substrate-primitive
1331    /// per-edge gate family carried inside
1332    /// [`AplicacaoSpec::validate_contratos`].
1333    ///
1334    /// Routes through the paired [`Self::source`] / [`Self::destination`]
1335    /// scalar accessors so every future rebrand of the underlying
1336    /// `:de` / `:para` storage (a lift from `String` to a typed
1337    /// `ServicoName(String)` newtype, a per-Aplicacao interning arena
1338    /// the M4 CR materializer authors, a per-cluster caller-alias
1339    /// table the operator pins through a future `:placement`-scoped
1340    /// slot, an M4 promotion from `String` to a typed edge-endpoint
1341    /// enum) flows through the same body without a coordinated
1342    /// per-consumer rewrite. Peer of the sibling per-edge substrate
1343    /// primitives already lifted on the same `impl WitContract`
1344    /// surface ([`Self::is_self_loop`] on the identity-space arm,
1345    /// [`Self::target`] on the payload-shape ↔ target-consistency
1346    /// arm, [`Self::identity`] on the dedup-key arm) — this run
1347    /// extends the shape to the last per-edge axis
1348    /// [`AplicacaoSpec::validate_contratos`] carried as an inline
1349    /// twin-arm cascade.
1350    ///
1351    /// Every future consumer that wants to re-check *one* edge's
1352    /// graph-membership reaches through one call: the M4
1353    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
1354    /// admission-webhook re-checking `:contratos` after a
1355    /// per-`(:de, :para)` edge patch without re-walking the whole
1356    /// `:contratos` list, the per-`:contratos`-edge `:politicas`
1357    /// override MESH-COMPOSITION §III.2 #3 acknowledges — which
1358    /// resolves an effective per-edge [`MeshPolicy`] and must
1359    /// re-check the edge's endpoints against the same membership
1360    /// oracle before it can key a per-edge override off the endpoint
1361    /// tuple. Pre-lift each such consumer was structurally forced to
1362    /// either re-inline the twin `if !names.contains(...)` cascade
1363    /// (the duplication the PRIME DIRECTIVE names as a bug) or call
1364    /// [`AplicacaoSpec::validate_contratos`] and pay a whole-list
1365    /// walk to re-check one edge. Post-lift each reaches the axis
1366    /// through one dispatch on the substrate primitive.
1367    ///
1368    /// `:de` runs before `:para` per the canonical edge-direction
1369    /// order the sibling per-arm shape gate
1370    /// [`validate_contrato_caixa`] arm ordering, the self-loop
1371    /// diagnostic string, and every peer arm ordering in
1372    /// [`AplicacaoSpec::validate_contratos`] already use — a
1373    /// well-shaped-but-phantom `:de` fires before a well-shaped-but-
1374    /// phantom `:para`, preserving byte-equal ordering with the
1375    /// pre-lift inline cascade.
1376    fn require_endpoints_in(
1377        &self,
1378        names: &std::collections::HashSet<&str>,
1379    ) -> Result<(), AplicacaoError> {
1380        if !names.contains(self.source()) {
1381            return Err(AplicacaoError::contrato_member_missing(self.source()));
1382        }
1383        if !names.contains(self.destination()) {
1384            return Err(AplicacaoError::contrato_member_missing(self.destination()));
1385        }
1386        Ok(())
1387    }
1388
1389    /// Typed view of the contract's payload target. Enforces that the
1390    /// `:wit` shape and the carried `:endpoint`/`:subject`/`:slot`
1391    /// fields agree, and that each carried value is itself
1392    /// value-shape valid:
1393    ///
1394    ///   - HTTP world (`wasi:http/*`, `http:*`) ⇒ exactly `:endpoint`,
1395    ///     non-empty, leading-`/` (Cilium L7 `path` + Gateway API
1396    ///     `PathPrefix` invariant — same shape required of `:entrada
1397    ///     :paths`)
1398    ///   - `PubSub` world (`nats:*`, `kafka:*`) ⇒ exactly `:subject`,
1399    ///     non-empty (NATS / Kafka publish without a subject is a
1400    ///     no-op subscribe, never the author's intent)
1401    ///   - Store world (`wasi:keyvalue/*`, `kv:*`) ⇒ exactly `:slot`,
1402    ///     non-empty (an empty slot template addresses the bucket
1403    ///     root, defeating the per-key isolation the slot exists for)
1404    ///   - Anything else ⇒ none of the three; the contract is a pure
1405    ///     typed capability edge with no payload selector.
1406    ///
1407    /// Translates the Apollo Federation discipline ("conflicts are
1408    /// errors at compile time, not warnings at runtime";
1409    /// MESH-COMPOSITION §II.3) onto pleme-io's typed Aplicacao surface:
1410    /// a contract whose WIT shape disagrees with its target field, or
1411    /// whose target field carries a value-shape-invalid string, is a
1412    /// build error — not a silent renderer drop. The returned
1413    /// [`WitTarget`] view's `&str` payload is therefore guaranteed
1414    /// non-empty (and absolute, for `Http`); every downstream consumer
1415    /// (caixa-mesh's L7 emission, the M3 Gateway/HTTPRoute renderer,
1416    /// the M4 per-edge policy resolver) can rely on that without
1417    /// re-checking.
1418    pub fn target(&self) -> Result<WitTarget<'_>, AplicacaoError> {
1419        // Route the HTTP-shaped payload-target extraction through the
1420        // lifted [`WitContract::endpoint`] accessor rather than the raw
1421        // `self.endpoint.as_deref()` field access — the two production
1422        // consumers of the per-`:contratos :endpoint` HTTP-shaped
1423        // payload-carrier scalar (this method's Http-arm payload
1424        // extraction, the [`AplicacaoSpec::validate`] duplicate-
1425        // `:contratos` [`ContratoIdentity`] dedup-key HTTP arm) now key
1426        // off exactly one typed dispatch on the substrate primitive, so
1427        // any future rebrand on the axis (an M4 per-cluster endpoint-
1428        // alias rewrite, a per-CR fully-qualified path prefix the M4
1429        // materializer applies per-tenant, an M4 promotion from
1430        // `Option<String>` to a typed HTTP path-template enum) migrates
1431        // as a single caixa-core edit rather than a coordinated rewrite
1432        // of the two call sites — peer of the sibling M3 per-`:placement`
1433        // [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
1434        // (74ec2d3) `Option<&str>` typed-dispatch discipline extended
1435        // onto the per-`:contratos` HTTP-shaped payload-carrier axis.
1436        let endpoint = self.endpoint();
1437        let subject = self.subject();
1438        // Route the store-arm payload-carrier scalar through the
1439        // lifted [`WitContract::slot`] accessor rather than the raw
1440        // `self.slot.as_deref()` field access — the two production
1441        // consumers of the per-`:contratos :slot` key/value-store-
1442        // shaped payload-carrier scalar (this method's Store-arm
1443        // payload extraction, the [`AplicacaoSpec::validate`]
1444        // duplicate-`:contratos` [`ContratoIdentity`] dedup-key store
1445        // arm) now key off exactly one typed dispatch on the substrate
1446        // primitive. Closes the last unlifted per-`:contratos`
1447        // `Option<String>` axis, completing the payload-carrier
1448        // accessor family peer of the sibling per-`:contratos`
1449        // [`WitContract::endpoint`] (7020470) / [`WitContract::subject`]
1450        // (90de675) lifts across the HTTP / pub-sub arms.
1451        let slot = self.slot();
1452        // Route the local `(de, para, wit)` triple-projection closure
1453        // through the lifted [`WitContract::edge_triple`] typed accessor
1454        // rather than re-inlining `(self.de.clone(), self.para.clone(),
1455        // self.wit.clone())` — the eight [`AplicacaoError::Contrato*`]
1456        // triple-carrying diagnostic constructors below (wrong-target /
1457        // missing-target on all three payload arms + capability-with-
1458        // payload + invalid-wit) now key off exactly one typed dispatch
1459        // on the substrate-primitive composite projection, sibling to
1460        // the peer [`WitContract::edge_pair`]-routed
1461        // [`AplicacaoError::Empty*`]/`ContratoEndpointEmpty`/
1462        // `ContratoSubjectEmpty`/`ContratoSlotEmpty` pair-carrying
1463        // diagnostic constructors on the same per-`:contratos`
1464        // diagnostic-construction surface.
1465        let edge = || self.edge_triple();
1466
1467        // The `:wit` value drives every downstream dispatch — the
1468        // is_http/is_pubsub/is_store prefix matchers below, the
1469        // caixa-mesh L7-vs-L4 emission, the cycle-detector's pub-sub
1470        // exclusion. Until this gate landed `target()` accepted any
1471        // non-empty string and silently demoted unrecognized shapes to
1472        // a capability-only edge (`:wit "WASI:HTTP/proxy"` — uppercase
1473        // typo, `:wit "wasi-http/proxy"` — hyphen-instead-of-colon typo,
1474        // `:wit "wasi:http proxy"` — whitespace, `:wit "wasi:"` — empty
1475        // package, the paste-from-binary footgun a multi-line blob
1476        // accidentally landing in the slot, the un-percent-encoded
1477        // non-ASCII byte) — the canonical "I thought I had L7 HTTP
1478        // routing, got L4-only" footgun. Empty is still pre-checked at
1479        // the [`AplicacaoSpec::validate`] call site via the narrower
1480        // [`AplicacaoError::EmptyWit`] variant (and fires first at the
1481        // validate layer); the value-shape gate here picks up the
1482        // structurally-invalid non-empty cases the empty check misses,
1483        // and remains correct under direct `target()` calls outside
1484        // validate (the predicate's defensive empty arm returns a
1485        // parser-shaped reason rather than silently falling through to
1486        // the Capability arm). Same trajectory as c4213a4 (WitContract
1487        // endpoint/subject/slot value-shape gates lifted into
1488        // `target()`) on the peer payload axes.
1489        //
1490        // Routed through the lifted [`WitContract::world_ref`] accessor
1491        // rather than the raw `&self.wit` field access — the two
1492        // production consumers of the per-`:contratos :wit` world-ref
1493        // byte-string on the value-shape axis (this method's invalid-
1494        // wit gate, the [`AplicacaoSpec::validate`] duplicate-
1495        // `:contratos` [`ContratoIdentity`] dedup-key world-ref arm via
1496        // [`WitContract::identity`]) now key off exactly one typed
1497        // dispatch on the substrate primitive, so any future rebrand on
1498        // the axis (an M4 promotion from `String` to a typed WIT
1499        // world-ref enum once the WIT registry stabilizes in
1500        // tatara-lisp, a per-CR canonicalization pass that lowercases
1501        // the WIT world ref post-parse, a promoted `smol_str::SmolStr`
1502        // inline-buffer swap on the storage arm) migrates as a single
1503        // caixa-core edit rather than a coordinated rewrite of the two
1504        // call sites — sibling of the peer [`WitContract::endpoint`] /
1505        // [`WitContract::subject`] / [`WitContract::slot`] accessor-
1506        // routed payload-carrier extractions above on the same
1507        // [`WitContract::target`] body, completing the per-`:contratos`
1508        // scalar-accessor-routing pass at the last unlifted raw-field-
1509        // access site inside `impl WitContract`. Same "typed dispatch
1510        // composes with typed dispatch, not with raw field access"
1511        // discipline the sibling [`WitContract::edge_pair`] /
1512        // [`WitContract::edge_triple`] / [`WitContract::identity`]
1513        // composite-projection accessors and the
1514        // [`WitContract::is_self_loop`] identity-space predicate
1515        // already route through. Pinned by
1516        // [`tests::wit_contract_target_wit_shape_gate_routes_through_world_ref_accessor`].
1517        if let Err(reason) = crate::render::is_wit_world_ref(self.world_ref()) {
1518            return Err(AplicacaoError::contrato_wit_invalid(
1519                self.edge_pair(),
1520                self.world_ref(),
1521                reason,
1522            ));
1523        }
1524
1525        if self.is_http() {
1526            if subject.is_some() || slot.is_some() {
1527                return Err(AplicacaoError::contrato_wrong_target(
1528                    edge(),
1529                    WitTarget::HTTP_FIELD_NAME,
1530                ));
1531            }
1532            let ep = endpoint.ok_or_else(|| {
1533                AplicacaoError::contrato_missing_target(edge(), WitTarget::HTTP_FIELD_NAME)
1534            })?;
1535            if ep.is_empty() {
1536                return Err(AplicacaoError::contrato_endpoint_empty(self.edge_pair()));
1537            }
1538            if !ep.starts_with('/') {
1539                return Err(AplicacaoError::contrato_endpoint_not_absolute(
1540                    self.edge_pair(),
1541                    ep,
1542                ));
1543            }
1544            // The `:endpoint` lands verbatim as a Cilium L7 `path:` rule
1545            // (caixa-mesh/src/lib.rs:311) and shares the K8s Gateway
1546            // API v1 HTTPPathMatch.value admission grammar with the
1547            // sibling `:entrada :paths` axis. Until this gate landed
1548            // `target()` only refused the empty string + the missing-
1549            // leading-`/` form; a structurally invalid endpoint
1550            // (`"/charge?token=X"` — query in path slot, `"/foo bar"` —
1551            // un-percent-encoded whitespace, `"/api/café"` — non-ASCII,
1552            // `"/api//bar"` — consecutive slash, `"/api/../etc"` —
1553            // path-traversal segment, the >1024-byte slug) silently
1554            // passed validate and the failure surfaced at apply time
1555            // as a Cilium policy rejection / silent traffic drop, far
1556            // from the source caixa.lisp. Same Gateway API HTTPPathMatch
1557            // grammar `:entrada :paths` already gates (55410e4), now
1558            // shared with `:contratos :endpoint` through the lifted
1559            // `crate::render::is_gateway_api_http_path` predicate.
1560            if let Err(reason) = crate::render::is_gateway_api_http_path(ep) {
1561                return Err(AplicacaoError::contrato_endpoint_invalid(
1562                    self.edge_pair(),
1563                    ep,
1564                    reason,
1565                ));
1566            }
1567            return Ok(WitTarget::Http { endpoint: ep });
1568        }
1569        if self.is_pubsub() {
1570            if endpoint.is_some() || slot.is_some() {
1571                return Err(AplicacaoError::contrato_wrong_target(
1572                    edge(),
1573                    WitTarget::PUBSUB_FIELD_NAME,
1574                ));
1575            }
1576            let s = subject.ok_or_else(|| {
1577                AplicacaoError::contrato_missing_target(edge(), WitTarget::PUBSUB_FIELD_NAME)
1578            })?;
1579            if s.is_empty() {
1580                return Err(AplicacaoError::contrato_subject_empty(self.edge_pair()));
1581            }
1582            // The `:subject` lands at runtime as the NATS subject the
1583            // producer publishes to and the consumer subscribes from.
1584            // Until this gate landed `target()` only refused the
1585            // empty string; a structurally invalid subject
1586            // (`"foo..bar"` — empty token between separators,
1587            // `"foo.>.bar"` — non-trailing `>` wildcard the NATS
1588            // server's subject parser rejects, `"foo bar"` —
1589            // un-percent-encoded whitespace, `"foo.café"` —
1590            // un-percent-encoded non-ASCII, `".foo"` / `"foo."` —
1591            // empty leading/trailing tokens, the >256-byte
1592            // paste-from-binary slug) silently passed validate and
1593            // the failure surfaced at runtime as a NATS server-side
1594            // `-ERR 'Invalid Subject'` on publish / subscribe, or as
1595            // a silent message drop, far from the source caixa.lisp.
1596            // Same Gateway API HTTPPathMatch / WIT-IDL grammar
1597            // trajectory `:contratos :endpoint` (4f0390b) and
1598            // `:contratos :wit` (6226bf4) already gate, now shared
1599            // with `:contratos :subject` through the lifted
1600            // `crate::render::is_nats_subject` predicate.
1601            if let Err(reason) = crate::render::is_nats_subject(s) {
1602                return Err(AplicacaoError::contrato_subject_invalid(
1603                    self.edge_pair(),
1604                    s,
1605                    reason,
1606                ));
1607            }
1608            return Ok(WitTarget::PubSub { subject: s });
1609        }
1610        if self.is_store() {
1611            if endpoint.is_some() || subject.is_some() {
1612                return Err(AplicacaoError::contrato_wrong_target(
1613                    edge(),
1614                    WitTarget::STORE_FIELD_NAME,
1615                ));
1616            }
1617            let sl = slot.ok_or_else(|| {
1618                AplicacaoError::contrato_missing_target(edge(), WitTarget::STORE_FIELD_NAME)
1619            })?;
1620            if sl.is_empty() {
1621                return Err(AplicacaoError::contrato_slot_empty(self.edge_pair()));
1622            }
1623            // Value-shape gate on the third (and last) typed payload
1624            // axis the `WitContract::target` dispatch carries — the
1625            // peer of [`crate::render::is_gateway_api_http_path`] for
1626            // `:endpoint` (4f0390b) and [`crate::render::is_nats_subject`]
1627            // for `:subject` (63e18a0). Until this gate landed
1628            // `target()` only refused the empty string; a structurally
1629            // invalid slot (`"check out/$order"` — un-percent-encoded
1630            // whitespace whose runtime behavior varies unpredictably
1631            // across kv backends, `"checkout/\x01order"` — control
1632            // character that Redis admits but corrupts on next read
1633            // and DynamoDB rejects outright, `"chéckout/$order"` —
1634            // un-percent-encoded non-ASCII byte each backend re-encodes
1635            // differently, `"checkout\n/$order"` — embedded newline,
1636            // the 513-byte paste-from-binary slug) silently passed
1637            // validate and surfaced at runtime as a per-backend kv
1638            // write rejection (DynamoDB / etcd) or as a silent
1639            // next-read corruption (Redis-via-RESP3), far from the
1640            // source caixa.lisp with no field naming which `:contratos`
1641            // edge carried the typo. The lifted predicate makes the
1642            // kv-backend intersection-floor a substrate-level
1643            // invariant at validate time, not a runtime "this passed
1644            // validate but the kv backend rejected on first write"
1645            // surprise — closes the typed payload-axis value-shape
1646            // trajectory across all three legs of the four
1647            // [`WitTarget`] arms (HTTP / PubSub / Store / Capability)
1648            // that caixa-mesh + the future kv emitters land in.
1649            if let Err(reason) = crate::render::is_wasi_keyvalue_slot(sl) {
1650                return Err(AplicacaoError::contrato_slot_invalid(
1651                    self.edge_pair(),
1652                    sl,
1653                    reason,
1654                ));
1655            }
1656            return Ok(WitTarget::Store { slot: sl });
1657        }
1658
1659        // Unrecognized WIT world — must not carry any payload target.
1660        if endpoint.is_some() || subject.is_some() || slot.is_some() {
1661            return Err(AplicacaoError::contrato_wrong_target(
1662                edge(),
1663                WitTarget::CAPABILITY_EXPECTED,
1664            ));
1665        }
1666        Ok(WitTarget::Capability)
1667    }
1668
1669    /// Substrate-canonical post-validation projection of the typed
1670    /// [`WitTarget`] view — the panic-on-failure shorthand every renderer
1671    /// downstream of an [`AplicacaoSpec`] that has already crossed the
1672    /// [`AplicacaoSpec::validate`] gate (typically via a caixa-mesh
1673    /// [`typed_view`]-shaped entry point that composes `validate` into
1674    /// the projection) reaches through when it needs the typed
1675    /// [`WitTarget`] and knows the containing [`AplicacaoSpec::validate`]
1676    /// has already admitted the `(:wit, :endpoint/:subject/:slot)` shape
1677    /// coherence for every `:contratos` entry. The peer accessor to the
1678    /// [`Self::target`] `Result`-returning validator on the same
1679    /// per-`:contratos` typed-projection axis — [`Self::target`] is the
1680    /// pre-validation validator that computes the projection *and* raises
1681    /// the [`AplicacaoError::Contrato*`] diagnostic cascade on any
1682    /// (`:wit`, payload) mismatch; this method is the post-validation
1683    /// projection every downstream consumer reaches through once the
1684    /// pre-validation gate has succeeded.
1685    ///
1686    /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
1687    ///
1688    /// Prior to this lift the "call `.target()` then `.expect(…)` with
1689    /// the same message" pattern sat inline at two production sites with
1690    /// no compile-time link between them: the
1691    /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)` CNP
1692    /// L7 introspection branch at `caixa-mesh/src/lib.rs:2825`
1693    /// (`c.target().expect("validated by typed_view").http_endpoint()`)
1694    /// and the [`caixa_feira::cmd::app`] `feira app graph` per-`:contratos`
1695    /// payload-column printer at `caixa-feira/src/cmd/app.rs:110`
1696    /// (`c.target().expect("validated by typed_view").graph_label()`),
1697    /// each open-coding the same `.target().expect("validated by
1698    /// typed_view")` pair with the message spelled twice. A future
1699    /// vocabulary shift on the panic-message axis (a tightening from
1700    /// `"validated by typed_view"` to `"validated by AplicacaoSpec::
1701    /// validate"` as the substrate's validator entry-point vocabulary
1702    /// sharpens, a per-consumer disambiguation, an M4 promotion of the
1703    /// panic to a `debug_assert` under a `--release` build profile) would
1704    /// have had to be threaded through both open-coded call sites in
1705    /// lockstep or one consumer would silently disagree with the peer on
1706    /// which invariant the panic message names. Same "same shape written
1707    /// verbatim ≥ 2 times becomes a typed helper" duplication-budget
1708    /// discipline the sibling [`Self::edge_pair`] /
1709    /// [`Self::edge_triple`] / [`Self::identity`] composite-projection
1710    /// lifts already establish on the paired composite-projection axis;
1711    /// this lift extends it onto the post-validation typed-view axis.
1712    ///
1713    /// Every future downstream consumer of the projected typed view
1714    /// (the future M4 per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao`
1715    /// CR materializer's per-edge admission webhook, the future
1716    /// Envoy-side per-typed-arm `local_rate_limit.descriptor_entries`
1717    /// bucket-key resolver, the future per-`:contratos`-edge mTLS overlay
1718    /// resolver, the future `feira app graph --l7` / `--pubsub` /
1719    /// `--kv` per-shape column emitters) reaches through this one typed
1720    /// dispatch on the substrate primitive rather than an open-coded
1721    /// per-consumer `.target().expect(…)` pair with the message
1722    /// re-inlined. The invariant the accessor's panic path pins — "this
1723    /// call is only reachable after [`AplicacaoSpec::validate`] has
1724    /// succeeded on the containing spec" — is the substrate's answer to
1725    /// give exactly once, at the primitive, not once per consumer.
1726    ///
1727    /// # Panics
1728    ///
1729    /// Panics with [`Self::PROJECTED_INVARIANT_MSG`] if [`Self::target`]
1730    /// would return an `Err` — i.e. if this contract's
1731    /// (`:wit`, `:endpoint`/`:subject`/`:slot`) shape has not been
1732    /// crossed by the [`AplicacaoSpec::validate`] gate cascade. Call
1733    /// this accessor only from a code path that has already reached the
1734    /// containing [`AplicacaoSpec`] through a validating entry-point
1735    /// (caixa-mesh's [`typed_view`], caixa-feira's `feira app graph`'s
1736    /// [`typed_view`] compose, the future M4 CR admission webhook's
1737    /// per-CR validate). Use [`Self::target`] instead on any pre-
1738    /// validation code path.
1739    ///
1740    /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
1741    #[must_use]
1742    pub fn target_projected(&self) -> WitTarget<'_> {
1743        self.target().expect(Self::PROJECTED_INVARIANT_MSG)
1744    }
1745
1746    /// Canonical panic message the [`Self::target_projected`]
1747    /// post-validation projection accessor threads through when the
1748    /// caller has violated the "call only after [`AplicacaoSpec::validate`]
1749    /// has succeeded" precondition. Lifted as a `pub const` on the
1750    /// [`WitContract`] surface so the byte-string lives in one place
1751    /// across the substrate — the [`Self::target_projected`] method
1752    /// body, the two prior production call sites' comments now naming
1753    /// the const, and every future consumer that must format-match the
1754    /// panic-message shape (a future test suite that asserts the panic-
1755    /// message byte-string across a fuzzed invalid-contract corpus,
1756    /// a future custom-panic hook in `caixa-operator` that surfaces the
1757    /// message with per-`:contratos` telemetry, the future admission
1758    /// webhook's per-CR validate-error report) reaches through the same
1759    /// canonical `&'static str`. A future rebrand on the panic-message
1760    /// axis (a tightening from `"validated by typed_view"` to `"validated
1761    /// by AplicacaoSpec::validate"` as the substrate's validator
1762    /// entry-point vocabulary sharpens once caixa-core grows a
1763    /// `Caixa::validated_aplicacao_view` companion to caixa-mesh's
1764    /// [`typed_view`]) lands at one caixa-core edit rather than a
1765    /// coordinated per-consumer sweep — same "one canonical declaration
1766    /// per axis, next to the accessor that reads it" discipline the peer
1767    /// [`WitTarget::CAPABILITY_LABEL`] / [`WitTarget::CAPABILITY_EXPECTED`]
1768    /// / [`WitTarget::CAPABILITY_GRAPH_LABEL`] payload-less-arm scalar-
1769    /// const family already establishes on the paired per-consumer-axis
1770    /// diagnostic-scalar surface.
1771    pub const PROJECTED_INVARIANT_MSG: &'static str = "validated by typed_view";
1772}
1773
1774/// Borrowed identity key for the typed-graph duplicate-`:contratos`
1775/// gate (see [`AplicacaoSpec::validate`]): every field that
1776/// distinguishes one contract from another, in declaration order
1777/// (`(de, para, wit, endpoint, subject, slot)`). Two [`WitContract`]s
1778/// with equal [`ContratoIdentity`]s are the same typed edge declared
1779/// twice — the graph-edge analogue of duplicate `:membros` /
1780/// `:placement :clusters` / `:entrada :paths` entries. Lifted as a
1781/// type alias so the duplicate-gate's `HashSet<…>` type doesn't trip
1782/// clippy's `type_complexity` lint (and so a future axis added to
1783/// `WitContract` is one alias edit, not a coordinated rewrite of
1784/// every set instantiation).
1785pub type ContratoIdentity<'a> = (
1786    &'a str,
1787    &'a str,
1788    &'a str,
1789    Option<&'a str>,
1790    Option<&'a str>,
1791    Option<&'a str>,
1792);
1793
1794/// Typed view of a [`WitContract`]'s payload target. Each variant
1795/// carries the field its WIT shape requires; constructing a `Http`
1796/// view without an endpoint is impossible by the type system.
1797///
1798/// Renderers (caixa-mesh L7 rules, feira app graph) match on this
1799/// instead of probing `Option<String>` fields one by one — the
1800/// "which payload field is set?" question is answered once, at
1801/// validation time.
1802#[derive(Debug, Clone, Copy, PartialEq, Eq, gen_platform::IsVariant)]
1803pub enum WitTarget<'a> {
1804    /// HTTP-shaped WIT world. Carries the configured request path.
1805    Http { endpoint: &'a str },
1806    /// Pub-sub-shaped WIT world. Carries the event-stream subject.
1807    ///
1808    /// The `IsVariant` derive would auto-name the predicate `is_pub_sub`
1809    /// (`discriminant_to_snake("PubSub") == "pub_sub"`); the explicit
1810    /// `#[is_variant(name = "pubsub")]` override keeps the emitted
1811    /// method name byte-identical to the sibling
1812    /// [`WitContract::is_pubsub`] predicate (the paired shape-side
1813    /// arm-discriminator that routes through
1814    /// [`wit_shape_is_pubsub`] on the wit-world-ref scalar rather than
1815    /// through `matches!` on the variant), so the two arm-discriminator
1816    /// axes — target-side variant-arm and shape-side ref-prefix — reach
1817    /// every downstream consumer through the same `is_pubsub()` name.
1818    #[is_variant(name = "pubsub")]
1819    PubSub { subject: &'a str },
1820    /// Key-value-shaped WIT world. Carries the slot template.
1821    Store { slot: &'a str },
1822    /// A typed capability edge with no payload selector — the WIT
1823    /// world stands on its own (rare; reserved for plain capability
1824    /// imports or M4-and-later WIT worlds we haven't shaped yet).
1825    Capability,
1826}
1827
1828impl<'a> WitTarget<'a> {
1829    /// Canonical author-facing `:contratos` payload field name for the
1830    /// HTTP-shaped arm — the `expected: &'static str` scalar the
1831    /// [`AplicacaoError::ContratoMissingTarget`] /
1832    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1833    /// through, the `:endpoint "…"` keyword the [`WitTarget::label`]
1834    /// duplicate-edge diagnostic emits, and the `endpoint=…` prefix
1835    /// the `feira app graph` verb prints. Peer of
1836    /// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
1837    /// on the payload-field-name axis; declared as a peer const next
1838    /// to the [`WitTarget::Http`] variant so a future rename on the
1839    /// author-surface `(defcaixa … :contratos ((:de … :para … :wit …
1840    /// :endpoint …)))` field lands in exactly one place, not scattered
1841    /// across the [`WitContract::target`] gate's six `expected:`
1842    /// literals, the label template, and every downstream consumer
1843    /// that prints a per-arm prefix. Same trajectory as the peer
1844    /// [`WitTarget::label`] lift (174e96a): a single source of truth
1845    /// for the arm's shape, next to the variant declaration.
1846    pub const HTTP_FIELD_NAME: &'static str = "endpoint";
1847    /// Canonical author-facing `:contratos` payload field name for the
1848    /// pub-sub-shaped arm. Peer of [`WitTarget::HTTP_FIELD_NAME`] /
1849    /// [`WitTarget::STORE_FIELD_NAME`] on the payload-field-name axis;
1850    /// see [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1851    pub const PUBSUB_FIELD_NAME: &'static str = "subject";
1852    /// Canonical author-facing `:contratos` payload field name for the
1853    /// key/value-store-shaped arm. Peer of
1854    /// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`]
1855    /// on the payload-field-name axis; see
1856    /// [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1857    pub const STORE_FIELD_NAME: &'static str = "slot";
1858
1859    /// Canonical stable human-readable label the payload-less
1860    /// [`WitTarget::Capability`] arm renders as under [`Self::label`] —
1861    /// the byte-string every consumer that formats a payload-less
1862    /// typed capability edge as text lands on (the
1863    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` diagnostic
1864    /// naming which identical edge was declared twice, the future
1865    /// `feira app graph` verb's per-arm prefix, the future M4 per-edge
1866    /// policy resolver's audit view, the operator's mesh-graph audit).
1867    /// Peer of the payload-arm [`Self::HTTP_FIELD_NAME`] /
1868    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`]
1869    /// author-facing label-scalar consts — the same
1870    /// "one canonical declaration per arm, next to the variant, so a
1871    /// future rename lands in one place" discipline extended to the
1872    /// payload-less arm. Until this lift landed the byte-string sat
1873    /// twice — once inline in [`Self::label`]'s [`WitTarget::Capability`]
1874    /// match arm, once in the pin test asserting the label's
1875    /// [`WitTarget::Capability`] output — with no compile-time link
1876    /// between the two: a rebrand on either side (an operator-facing
1877    /// vocabulary shift, a per-consumer disambiguation like
1878    /// `"(capability — no payload; typed edge only)"`) would silently
1879    /// desynchronize until a downstream consumer surfaced the drift at
1880    /// runtime.
1881    pub const CAPABILITY_LABEL: &'static str = "(capability — no payload)";
1882
1883    /// Canonical `expected:` scalar the
1884    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1885    /// through for the payload-less [`WitTarget::Capability`] arm — the
1886    /// byte-string authors read as "this WIT world's shape is not one
1887    /// of {`HTTP`, `PubSub`, `Store`}, so it must not carry
1888    /// `:endpoint` / `:subject` / `:slot`". Peer of the payload-arm
1889    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1890    /// [`Self::STORE_FIELD_NAME`] consts on the
1891    /// `ContratoWrongTarget::expected` axis — the fourth arm of the
1892    /// same "which payload field name goes in the diagnostic" dispatch
1893    /// the three payload-arm consts cover, extended to the payload-less
1894    /// arm. Until this lift landed the byte-string sat twice — once
1895    /// inline in the [`Self::target`] Capability-arm rejection at the
1896    /// production dispatch, once in the pin test asserting the
1897    /// diagnostic's `expected:` scalar carries `"none"` verbatim — with
1898    /// no compile-time link between the two: a rebrand on either side
1899    /// (an author-facing vocabulary shift to `"capability"` /
1900    /// `"(none)"` / `"no-payload"` as the WIT registry's shape
1901    /// vocabulary sharpens, a per-consumer disambiguation as M4 splits
1902    /// [`WitTarget::Capability`] into per-shape peers) would silently
1903    /// desynchronize until a downstream consumer surfaced the drift at
1904    /// runtime. Same "one canonical declaration per arm, next to the
1905    /// variant, so a future rename lands in one place" discipline the
1906    /// peer [`Self::CAPABILITY_LABEL`] lift (7ed03a3-era) already
1907    /// established for the payload-less arm's human-readable label
1908    /// axis; this lift extends it onto the peer diagnostic-scalar axis
1909    /// so both halves of the "how does the Capability arm surface at
1910    /// its two consumer axes (human-readable label, wrong-target
1911    /// diagnostic)" pipeline route through peer consts declared next
1912    /// to the variant.
1913    ///
1914    /// Pairwise-distinctness against the three payload-arm scalars
1915    /// ([`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1916    /// [`Self::STORE_FIELD_NAME`]) is pinned by the sibling
1917    /// `wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`
1918    /// test — the 4-way closure of the 3-way
1919    /// `wit_target_field_names_are_pairwise_distinct` sibling pin onto
1920    /// the `ContratoWrongTarget::expected` axis, matching the peer
1921    /// `m3_placement_estrategia_consts_are_pairwise_distinct` closed-set
1922    /// scalar-value distinctness discipline the sibling M3 typed-enum
1923    /// discriminator axis already carries.
1924    pub const CAPABILITY_EXPECTED: &'static str = "none";
1925
1926    /// Canonical `feira app graph` per-`:contratos`-edge payload-column
1927    /// byte-string the payload-less [`WitTarget::Capability`] arm renders
1928    /// as under [`Self::graph_label`] — the sibling
1929    /// [`WitTarget::CAPABILITY_LABEL`] scalar on the peer graph-verb
1930    /// payload-column axis (the graph verb spells payload-less as
1931    /// `(capability-only)`, distinct from the duplicate-`:contratos`
1932    /// diagnostic's `(capability — no payload)` on the human-readable
1933    /// [`Self::label`] axis). Peer of [`Self::CAPABILITY_LABEL`] /
1934    /// [`Self::CAPABILITY_EXPECTED`] on the payload-less-arm scalar-const
1935    /// family — extends the "one canonical declaration per arm, next to
1936    /// the variant, so a future rename lands in one place" discipline
1937    /// onto the third payload-less-arm consumer axis (`feira app graph`
1938    /// payload column, joining the [`Self::label`] duplicate-`:contratos`
1939    /// diagnostic axis and the [`Self::target`] wrong-target diagnostic
1940    /// axis).
1941    ///
1942    /// Until this lift landed the byte-string sat inline in
1943    /// [`caixa-feira`]'s `cmd::app::GraphArgs::run` per-`:contratos` payload-
1944    /// column match at `caixa-feira/src/cmd/app.rs:111` as a raw
1945    /// `"(capability-only)".to_string()` literal, with no compile-time link
1946    /// back to the [`WitTarget::Capability`] variant declaration nor to
1947    /// the sibling [`Self::CAPABILITY_LABEL`] / [`Self::CAPABILITY_EXPECTED`]
1948    /// peer consts already carrying the "one canonical declaration per
1949    /// payload-less-arm consumer axis" discipline. A rebrand on either
1950    /// side (the graph verb's operator-facing vocabulary tightening from
1951    /// `"(capability-only)"` to `"capability"` / `"(capability edge)"` as
1952    /// the WIT registry vocabulary sharpens, an M4 split of
1953    /// [`Self::Capability`] into per-shape peers) would silently
1954    /// desynchronize the graph-verb byte-string from the paired
1955    /// per-arm-adjacent const and land two spellings of the same axis in
1956    /// two spots.
1957    pub const CAPABILITY_GRAPH_LABEL: &'static str = "(capability-only)";
1958
1959    /// The `(author-facing field name, payload)` pair this typed target
1960    /// arm carries — `Some((HTTP_FIELD_NAME, endpoint))` for
1961    /// [`Self::Http`], `Some((PUBSUB_FIELD_NAME, subject))` for
1962    /// [`Self::PubSub`], `Some((STORE_FIELD_NAME, slot))` for
1963    /// [`Self::Store`], `None` for the payload-less
1964    /// [`Self::Capability`] arm.
1965    ///
1966    /// Lifted as the single 4-arm dispatch that both [`Self::label`]
1967    /// (formats `":{field} {payload:?}"` on `Some`, falls to
1968    /// [`Self::CAPABILITY_LABEL`] on `None`) and [`Self::field_name`]
1969    /// (returns the first component) route through, so a future
1970    /// [`WitTarget`] variant addition — the M4-and-later per-edge WIT
1971    /// registry may split [`Self::Http`] into `Rest` / `Grpc` peers,
1972    /// or extend [`Self::Store`] with a `Queue`-shaped peer — becomes
1973    /// exactly one new match-arm here (a compile-time exhaustiveness
1974    /// error otherwise), not a coordinated three-way rewrite of the
1975    /// prior [`Self::label`] template + [`Self::field_name`] dispatch
1976    /// + every downstream consumer that reaches for the pair.
1977    ///
1978    /// Until this lift landed the three payload arms sat in
1979    /// [`Self::label`] as three near-identical `format!(":{} {…:?}", …)`
1980    /// invocations (one per variant, each hand-quoting the paired
1981    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1982    /// [`Self::STORE_FIELD_NAME`] const) — the canonical
1983    /// "same shape, written N times" duplication THEORY.md §I.3.5
1984    /// ("Generation first, composition second, hand-authoring last;
1985    /// the duplication budget is zero") promotes to a build-time
1986    /// concern, with each per-arm site paired to its own const with no
1987    /// compile-time link between the format template and the arm's
1988    /// payload extraction.
1989    #[must_use]
1990    pub const fn payload_pair(&self) -> Option<(&'static str, &'a str)> {
1991        match *self {
1992            WitTarget::Http { endpoint } => Some((Self::HTTP_FIELD_NAME, endpoint)),
1993            WitTarget::PubSub { subject } => Some((Self::PUBSUB_FIELD_NAME, subject)),
1994            WitTarget::Store { slot } => Some((Self::STORE_FIELD_NAME, slot)),
1995            WitTarget::Capability => None,
1996        }
1997    }
1998
1999    /// The canonical author-facing `:contratos` payload field name
2000    /// this typed target arm carries (`Http` → `Some("endpoint")`,
2001    /// `PubSub` → `Some("subject")`, `Store` → `Some("slot")`), or
2002    /// `None` for the payload-less `Capability` arm.
2003    ///
2004    /// Routes through [`Self::payload_pair`] — the single 4-arm
2005    /// dispatch [`Self::label`] also reads — so a future variant
2006    /// addition is one match-arm edit at [`Self::payload_pair`], not a
2007    /// per-consumer rewrite. Same "exhaustive-match at one canonical
2008    /// dispatch, thin projections at each consumer" trajectory the
2009    /// peer [`PlacementStrategy::as_str`] / [`std::fmt::Display`]
2010    /// pair (0a2f653) landed on the sibling M3 typed-enum axis.
2011    #[must_use]
2012    pub const fn field_name(&self) -> Option<&'static str> {
2013        match self.payload_pair() {
2014            Some((f, _)) => Some(f),
2015            None => None,
2016        }
2017    }
2018
2019    /// The underlying scalar the payload-carrying arm carries — the
2020    /// per-arm request path ([`Self::Http`] `:endpoint`), event-stream
2021    /// subject ([`Self::PubSub`] `:subject`), or slot template
2022    /// ([`Self::Store`] `:slot`), borrowed from the typed slot's own
2023    /// `&'a str` storage — or `None` on the payload-less
2024    /// [`Self::Capability`] arm.
2025    ///
2026    /// Thin projection onto the single 4-arm [`Self::payload_pair`]
2027    /// dispatch (`self.payload_pair().map(|(_, p)| p)` in `const fn`
2028    /// form) — peer of [`Self::field_name`] (`.payload_pair().0`) on
2029    /// the paired sub-selector axis. Both per-half accessors read from
2030    /// one authoritative match, so a future [`WitTarget`] variant
2031    /// addition (`Rest`/`Grpc` split of [`Self::Http`], `Queue`-shaped
2032    /// peer of [`Self::Store`]) lands at exactly one caixa-core edit
2033    /// on [`Self::payload_pair`] and both per-half projections + every
2034    /// downstream consumer picks the new arm up by construction — no
2035    /// coordinated N-way rewrite across the paired accessor dispatches,
2036    /// the [`Self::label`] / [`Self::graph_label`] format templates,
2037    /// and every future WIT-registry-shaped consumer.
2038    ///
2039    /// Peer of the sibling [`caixa-flux`][caixa-flux-crate]
2040    /// `GitRefSpec::ref_value` projection on the `FluxCD` source-
2041    /// controller `spec.ref.<field>` axis — same "one paired dispatch,
2042    /// both per-half projections as thin readers, every downstream
2043    /// consumer through the same match" discipline extended onto the
2044    /// M3 `:contratos` payload-arm axis. Closes the discipline-parity
2045    /// gap between the two paired-dispatch surfaces: the peer
2046    /// [`Self::payload_pair`] + [`Self::field_name`] pair carried only
2047    /// the first-component projection until this lift; the second-
2048    /// component sibling now sits alongside so both halves reach every
2049    /// future consumer through the same substrate-primitive dispatch.
2050    ///
2051    /// [caixa-flux-crate]: https://docs.rs/caixa-flux/latest/caixa_flux/enum.GitRefSpec.html#method.ref_value
2052    #[must_use]
2053    pub const fn payload(&self) -> Option<&'a str> {
2054        match self.payload_pair() {
2055            Some((_, p)) => Some(p),
2056            None => None,
2057        }
2058    }
2059
2060    /// Substrate-canonical per-arm HTTP-endpoint scalar accessor every
2061    /// consumer that fans on the L7-HTTP-shaped payload keys off —
2062    /// returns the [`Self::Http`]-arm's author-declared request path
2063    /// verbatim as an `Option<&'a str>`, `Some(endpoint)` when the
2064    /// projected target is [`Self::Http { endpoint }`], `None` on the
2065    /// three sibling arms ([`Self::PubSub`] / [`Self::Store`] /
2066    /// [`Self::Capability`], each of which carries no HTTP endpoint by
2067    /// definition).
2068    ///
2069    /// The [`Self::Http`] arm carries the Cilium L7 `HTTPNetworkPolicy`
2070    /// `path:` rule payload every substrate-side L7-introspecting
2071    /// per-`(:de, :para)` `CiliumNetworkPolicy` emitter reads (today: the
2072    /// [`caixa_mesh::cilium_network_policies`] per-edge `toPorts[].rules
2073    /// .http[0].path` scalar the HTTP-shape-only L7 rule builder emits
2074    /// on the L7 introspection branch; every peer WIT shape stays
2075    /// L4-only because Cilium can't introspect NATS / key-value / plain
2076    /// capability edges), and every future L7-introspecting consumer
2077    /// of the projected target's HTTP endpoint (the future M4
2078    /// per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao` CR
2079    /// materializer's per-edge L7 admission-webhook overlay, the
2080    /// future Envoy-side `local_rate_limit.descriptor_entries` per-HTTP-
2081    /// path bucket-key resolver, the future per-`:contratos`-edge
2082    /// mTLS-required overlay's HTTP-shape scope filter, the future
2083    /// `feira app graph --l7` per-Aplicacao HTTP-path column) reaches
2084    /// through the same typed dispatch.
2085    ///
2086    /// Prior to this lift the sole production consumer of the projected-
2087    /// target HTTP endpoint — the [`caixa_mesh::cilium_network_policies`]
2088    /// per-edge L7 introspection branch at `caixa-mesh/src/lib.rs:2759`
2089    /// (`if let WitTarget::Http { endpoint } = c.target().expect(…) {
2090    /// http_rule.insert_string(CILIUM_KEY_PATH, endpoint.to_string()); …
2091    /// }`) — reached the payload through a raw per-arm `if let` pattern-
2092    /// match that expressed no compile-time link back to the substrate
2093    /// primitive's typed dispatch, sibling to the [`WitContract`] pre-
2094    /// projection [`WitContract::endpoint`] (7020470) `Option<&str>`
2095    /// scalar accessor on the peer per-`:contratos` raw-field axis but
2096    /// with no post-projection peer on the typed-view surface. A future
2097    /// [`WitTarget`] variant addition that splits [`Self::Http`] into
2098    /// peers (a `Rest`/`Grpc` split once the WIT registry stabilizes
2099    /// gRPC-shaped worlds per this enum's own docstring at
2100    /// aplicacao.rs:1341-1343 — with a `Rest`-arm `endpoint: &'a str`
2101    /// payload alongside a `Grpc`-arm `service_method: &'a str` payload)
2102    /// would have had to be threaded through the caixa-mesh L7 emit
2103    /// branch's raw `if let` in lockstep — either coalescing the two
2104    /// L7-HTTP-family arms under a shared `path:` emit, or splitting the
2105    /// emit path per-arm — with no substrate-primitive dispatch making
2106    /// the "which arms count as L7-HTTP-shaped for path-emission
2107    /// purposes" question the substrate's answer to give. Lifting the
2108    /// resolution to a typed method on the substrate primitive means
2109    /// every downstream L7-HTTP-facing consumer of the Aplicacao's
2110    /// projected-target HTTP endpoint reaches for exactly one typed
2111    /// dispatch — the resolver's accept-set migrates as a unit on any
2112    /// future arm-family widening, and the caixa-mesh L7 emit branch
2113    /// reads through the same substrate primitive.
2114    ///
2115    /// Peer of the sibling pre-projection [`WitContract::endpoint`]
2116    /// (7020470) `Option<&str>` scalar accessor on the raw
2117    /// `:contratos :endpoint` field-access axis — same "one typed
2118    /// dispatch on the substrate primitive, thin projections at each
2119    /// consumer" discipline extended onto the peer post-projection typed-
2120    /// view surface (the [`WitContract::endpoint`] pre-projection
2121    /// accessor returns `Some` for any author-declared `:endpoint`
2122    /// value regardless of the paired `:wit` world's HTTP-shape
2123    /// classification — the raw slot before validation crosses it —
2124    /// while this post-projection [`Self::http_endpoint`] accessor
2125    /// returns `Some` iff the target has been projected onto the
2126    /// [`Self::Http`] arm, i.e. only after the [`WitContract::target`]
2127    /// gate has admitted the `(:wit, :endpoint/:subject/:slot)` shape
2128    /// coherence; the two accessors close the pre-projection /
2129    /// post-projection pair on the HTTP-endpoint axis). Sibling of the
2130    /// unified pan-arm [`Self::payload`] (`Option<&'a str>` for any of
2131    /// the three payload-carrying arms) — extends the per-arm
2132    /// projection family onto the [`Self::Http`] specialization axis
2133    /// that the pan-arm accessor's shape blends into a single arm-
2134    /// agnostic view; paired with [`Self::pubsub_subject`] /
2135    /// [`Self::store_slot`] on the sibling per-arm axes so every
2136    /// per-payload-arm shape carries a named post-projection accessor
2137    /// on the same shape as `http_endpoint`, closing the per-arm-shape
2138    /// accept-set the substrate primitive owns.
2139    #[must_use]
2140    pub const fn http_endpoint(&self) -> Option<&'a str> {
2141        match *self {
2142            WitTarget::Http { endpoint } => Some(endpoint),
2143            WitTarget::PubSub { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
2144        }
2145    }
2146
2147    /// Substrate-canonical per-arm pub-sub-subject scalar accessor every
2148    /// consumer that fans on the pub-sub-shaped payload keys off —
2149    /// returns the [`Self::PubSub`]-arm's author-declared event-stream
2150    /// subject verbatim as an `Option<&'a str>`, `Some(subject)` when
2151    /// the projected target is [`Self::PubSub { subject }`], `None` on
2152    /// the three sibling arms ([`Self::Http`] / [`Self::Store`] /
2153    /// [`Self::Capability`], each of which carries no NATS-shaped
2154    /// subject by definition).
2155    ///
2156    /// The [`Self::PubSub`] arm carries the NATS-server-accepted subject
2157    /// the future substrate-side pub-sub-introspecting per-`(:de, :para)`
2158    /// consumer keys off (the M4 per-Aplicacao NATS `Stream` / `Consumer`
2159    /// CR materializer's `spec.subjects[]` projection, the future
2160    /// Envoy-side per-subject `local_rate_limit.descriptor_entries`
2161    /// bucket-key resolver, the future `feira app graph --pubsub`
2162    /// per-Aplicacao subject column, any future substrate-lifted
2163    /// pub-sub-shape emitter that reads a projected `WitTarget` in the
2164    /// same shape [`caixa_mesh::cilium_network_policies`] reads the
2165    /// HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today). Every
2166    /// future pub-sub-shape consumer reaches for the same typed
2167    /// dispatch this accessor exposes so the "which arm carries the
2168    /// subject scalar?" answer lives at one caixa-core edit rather
2169    /// than open-coded across per-consumer `if let WitTarget::PubSub
2170    /// { subject } = c.target()…` pattern-matches.
2171    ///
2172    /// Peer of the sibling [`Self::http_endpoint`] (5d6dc92 trajectory)
2173    /// per-arm HTTP-endpoint accessor on the peer per-arm axis and of
2174    /// the pre-projection [`WitContract::subject`] scalar accessor on
2175    /// the raw `:contratos :subject` field-access axis — same "one
2176    /// typed dispatch on the substrate primitive, thin projections at
2177    /// each consumer" discipline extended onto the per-arm pub-sub
2178    /// post-projection axis. The pre-projection accessor returns
2179    /// `Some` for any author-declared `:subject` value regardless of
2180    /// the paired `:wit` world's pub-sub-shape classification (the raw
2181    /// slot before validation crosses it); this post-projection
2182    /// accessor returns `Some` iff the target has been projected onto
2183    /// the [`Self::PubSub`] arm, i.e. only after the
2184    /// [`WitContract::target`] gate has admitted the
2185    /// `(:wit, :endpoint/:subject/:slot)` shape coherence — closing
2186    /// the pre-/post-projection pair on the pub-sub-subject axis to
2187    /// match the pair the [`WitContract::endpoint`] +
2188    /// [`Self::http_endpoint`] surfaces already close on the peer
2189    /// HTTP-endpoint axis.
2190    ///
2191    /// Sibling of the unified pan-arm [`Self::payload`]
2192    /// (`Option<&'a str>` for any of the three payload-carrying arms) —
2193    /// extends the per-arm projection family onto the [`Self::PubSub`]
2194    /// specialization axis that the pan-arm accessor's shape blends
2195    /// into a single arm-agnostic view; the pair
2196    /// (`pubsub_subject`, `store_slot`) closes the trio
2197    /// (`http_endpoint`, `pubsub_subject`, `store_slot`) so every
2198    /// payload arm now carries its own per-arm-shape post-projection
2199    /// accessor.
2200    #[must_use]
2201    pub const fn pubsub_subject(&self) -> Option<&'a str> {
2202        match *self {
2203            WitTarget::PubSub { subject } => Some(subject),
2204            WitTarget::Http { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
2205        }
2206    }
2207
2208    /// Substrate-canonical per-arm key/value-store-slot scalar accessor
2209    /// every consumer that fans on the store-shaped payload keys off —
2210    /// returns the [`Self::Store`]-arm's author-declared slot template
2211    /// verbatim as an `Option<&'a str>`, `Some(slot)` when the
2212    /// projected target is [`Self::Store { slot }`], `None` on the
2213    /// three sibling arms ([`Self::Http`] / [`Self::PubSub`] /
2214    /// [`Self::Capability`], each of which carries no
2215    /// key/value-store slot by definition).
2216    ///
2217    /// The [`Self::Store`] arm carries the WASI-key/value-accepted slot
2218    /// template (validated by [`crate::render::is_wasi_keyvalue_slot`])
2219    /// every future substrate-side store-introspecting per-`(:de,
2220    /// :para)` consumer keys off (the M4 per-Aplicacao WASI-key/value
2221    /// namespace / prefix reconciler's per-slot projection, the future
2222    /// per-store-backend routing overlay's slot-shape gate, the future
2223    /// `feira app graph --store` per-Aplicacao slot column, any future
2224    /// substrate-lifted store-shape emitter that reads a projected
2225    /// `WitTarget` in the same shape [`caixa_mesh::cilium_network_policies`]
2226    /// reads the HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today).
2227    /// Every future store-shape consumer reaches for the same typed
2228    /// dispatch this accessor exposes so the "which arm carries the
2229    /// slot scalar?" answer lives at one caixa-core edit rather than
2230    /// open-coded across per-consumer
2231    /// `if let WitTarget::Store { slot } = c.target()…`
2232    /// pattern-matches.
2233    ///
2234    /// Peer of the sibling [`Self::http_endpoint`] +
2235    /// [`Self::pubsub_subject`] per-arm accessors on the peer per-arm
2236    /// axes and of the pre-projection [`WitContract::slot`] scalar
2237    /// accessor on the raw `:contratos :slot` field-access axis — same
2238    /// "one typed dispatch on the substrate primitive, thin projections
2239    /// at each consumer" discipline extended onto the per-arm store
2240    /// post-projection axis. Closes the pre-/post-projection pair on
2241    /// the store-slot axis to match the pairs the
2242    /// [`WitContract::endpoint`] + [`Self::http_endpoint`] and
2243    /// [`WitContract::subject`] + [`Self::pubsub_subject`] surfaces
2244    /// already close on the peer HTTP-endpoint and pub-sub-subject
2245    /// axes; the substrate-side pre-/post-projection accessor family
2246    /// now spans all three payload arms as a matched trio, so any
2247    /// future arm-shape widening (a `Rest`/`Grpc` split of
2248    /// [`Self::Http`], a `Queue`-shaped peer of [`Self::Store`]) that
2249    /// lands one accessor without threading through the sibling
2250    /// pre-projection or the peer per-arm post-projection surfaces a
2251    /// compile-time exhaustiveness error at the substrate primitive,
2252    /// not a silent per-consumer split at renderer emit time.
2253    ///
2254    /// Sibling of the unified pan-arm [`Self::payload`]
2255    /// (`Option<&'a str>` for any of the three payload-carrying arms) —
2256    /// closes the per-arm projection family onto the [`Self::Store`]
2257    /// specialization axis that the pan-arm accessor's shape blends
2258    /// into a single arm-agnostic view. The trio
2259    /// (`http_endpoint`, `pubsub_subject`, `store_slot`) partitions the
2260    /// pan-arm accept-set on every payload-carrying arm: exactly one
2261    /// per-arm accessor returns `Some(payload)` and the two peers
2262    /// return `None`, and every payload-less [`Self::Capability`]
2263    /// input returns `None` on all three — the partition the sibling
2264    /// `wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`
2265    /// pin locks in load-bearing.
2266    #[must_use]
2267    pub const fn store_slot(&self) -> Option<&'a str> {
2268        match *self {
2269            WitTarget::Store { slot } => Some(slot),
2270            WitTarget::Http { .. } | WitTarget::PubSub { .. } | WitTarget::Capability => None,
2271        }
2272    }
2273
2274    /// Render this typed target as a stable human-readable label
2275    /// (`:endpoint "/charge"`, `:subject "events.x"`,
2276    /// `:slot "checkout/$order"`, or `(capability — no payload)` when
2277    /// the WIT world is a pure capability edge).
2278    ///
2279    /// Used by the [`AplicacaoSpec::validate`] duplicate-`:contratos`
2280    /// gate so the diagnostic names *which* identical edge was
2281    /// declared twice (not just which `(de, para, wit)` triple).
2282    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
2283    /// on the payload-carrying arms (`Some((field, payload)) →
2284    /// format!(":{field} {payload:?}")`) and through the lifted
2285    /// [`Self::CAPABILITY_LABEL`] const on the payload-less
2286    /// [`Self::Capability`] arm — so a future variant addition (the
2287    /// M4-and-later per-edge WIT registry may split [`Self::Http`]
2288    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
2289    /// `Queue`-shaped peer) becomes a single new match-arm on
2290    /// [`Self::payload_pair`] rather than a rewrite of this template
2291    /// (and every downstream consumer that reaches for the label
2292    /// shape: the per-edge policy resolver in M4, the `feira app
2293    /// graph` view, the operator's mesh-graph audit). Until this
2294    /// lift landed the three payload arms carried three near-identical
2295    /// per-arm `format!(":{} {…:?}", …)` invocations, and the
2296    /// [`Self::Capability`] arm carried the payload-less byte-string
2297    /// twice (once inline here, once in the pin test) — closing the
2298    /// duplication trajectory the peer [`Self::HTTP_FIELD_NAME`] /
2299    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`] (174e96a
2300    /// / 4a1e490) peer-const lifts already established for the
2301    /// payload-carrying arms.
2302    #[must_use]
2303    pub fn label(&self) -> String {
2304        match self.payload_pair() {
2305            Some((field, payload)) => format!(":{field} {payload:?}"),
2306            None => Self::CAPABILITY_LABEL.to_string(),
2307        }
2308    }
2309
2310    /// Render this typed target as the `feira app graph` per-`:contratos`
2311    /// payload-column byte-string (`endpoint=/charge`, `subject=events.x`,
2312    /// `slot=checkout/$order`, or [`Self::CAPABILITY_GRAPH_LABEL`] on the
2313    /// payload-less arm).
2314    ///
2315    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
2316    /// on the payload-carrying arms (`Some((field, payload)) →
2317    /// format!("{field}={payload}")`) and through the lifted
2318    /// [`Self::CAPABILITY_GRAPH_LABEL`] const on the payload-less
2319    /// [`Self::Capability`] arm — so a future variant addition
2320    /// (the M4-and-later per-edge WIT registry may split [`Self::Http`]
2321    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
2322    /// `Queue`-shaped peer) becomes one match-arm edit at
2323    /// [`Self::payload_pair`], propagating through this graph-verb
2324    /// projection at zero call-site cost, sibling to the peer
2325    /// [`Self::label`] duplicate-`:contratos` diagnostic emission on the
2326    /// same 4-arm dispatch.
2327    ///
2328    /// Until this lift landed the [`caixa-feira`]
2329    /// `cmd::app::GraphArgs::run` per-`:contratos` payload column
2330    /// (`caixa-feira/src/cmd/app.rs:101-112`) hand-rolled the same 4-arm
2331    /// dispatch inline, re-projecting `HTTP_FIELD_NAME` /
2332    /// `PUBSUB_FIELD_NAME` / `STORE_FIELD_NAME` under a per-arm
2333    /// `format!("{}={endpoint}", ...)` template and hard-coding
2334    /// `"(capability-only)"` as a fifth payload-less scalar with no link
2335    /// back to the paired [`WitTarget::Capability`] variant declaration.
2336    /// A future variant addition would have had to be threaded through
2337    /// both [`Self::label`] (via [`Self::payload_pair`]) *and* the graph
2338    /// verb's inline match in lockstep or the two projections would
2339    /// silently disagree on the arm-set the graph verb prints — the
2340    /// duplicate-`:contratos` diagnostic reading one shape while the
2341    /// graph verb's payload column silently dropped the new arm to
2342    /// `(capability-only)`. Lifting the graph-verb projection onto the
2343    /// same substrate-primitive [`Self::payload_pair`] dispatch closes
2344    /// the axis: both projections migrate as a unit.
2345    ///
2346    /// The `field=payload` (no colon prefix, `=` separator, no `Debug`
2347    /// quoting) shape is graph-verb-canonical — distinct from the
2348    /// sibling [`Self::label`] `":{field} {payload:?}"` shape the
2349    /// duplicate-`:contratos` diagnostic seeds (see
2350    /// [`Self::CAPABILITY_LABEL`] vs. [`Self::CAPABILITY_GRAPH_LABEL`]
2351    /// on the payload-less axis for the paired distinction).
2352    #[must_use]
2353    pub fn graph_label(&self) -> String {
2354        match self.payload_pair() {
2355            Some((field, payload)) => format!("{field}={payload}"),
2356            None => Self::CAPABILITY_GRAPH_LABEL.to_string(),
2357        }
2358    }
2359}
2360
2361/// [`std::fmt::Display`] routed through [`WitTarget::label`], so the
2362/// pretty-printed byte-string every consumer that formats a typed
2363/// payload target as user-facing text lands on (the
2364/// [`AplicacaoError::ContratoDuplicate`] diagnostic's `target:` carry
2365/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds via
2366/// [`WitTarget::label`] at aplicacao.rs:5491, the future `feira app
2367/// graph` per-`:contratos`-edge payload column that reaches the graph
2368/// verb through `format!("{target}")`, the future M4 per-edge policy
2369/// resolver's per-edge audit-log line, the operator's mesh-graph
2370/// per-edge inspection view) reaches for the same lifted
2371/// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`] /
2372/// [`WitTarget::STORE_FIELD_NAME`] / [`WitTarget::CAPABILITY_LABEL`]
2373/// const set the [`WitTarget::payload_pair`] 4-arm dispatch already
2374/// routes through — extending the three-path-convergence
2375/// (`Debug` for structural inspection, `Display` for user-facing text,
2376/// per-arm typed accessor for the canonical byte-string) discipline the
2377/// sibling M3 [`PlacementStrategy`] and M2 [`crate::supervisor::RestartStrategy`]
2378/// / [`crate::supervisor::RestartPolicy`] OTP-shape typed enums carry
2379/// onto the fourth (and only remaining) typed-shape-discriminator axis
2380/// on the caixa surface.
2381///
2382/// Pre-lift the two paths were structurally independent — every consumer
2383/// reaching for a payload byte-string past the [`WitTarget::label`]
2384/// helper had to pick between three paths ([`WitTarget::label`],
2385/// `format!("{v:?}")` on the `Debug` derive, hand-rolled per-arm
2386/// formatting through the [`WitTarget::HTTP_FIELD_NAME`] /
2387/// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`] /
2388/// [`WitTarget::CAPABILITY_LABEL`] const set), and a future consumer
2389/// that reached for `format!("{target}")` — the canonical shape every
2390/// user-facing pretty-print site on the sibling typed-enum axes already
2391/// uses — would silently land on the `Debug` derive's structural output
2392/// (`Http { endpoint: "/charge" }` — Rust struct-literal syntax) rather
2393/// than the `label()` helper's stable byte-string (`:endpoint
2394/// "/charge"` — the author-facing `:contratos` keyword form) the
2395/// substrate-side duplicate-`:contratos` gate at aplicacao.rs:5491
2396/// already threads through. The two spellings would diverge silently in
2397/// every downstream diagnostic / graph / audit line reached through
2398/// `format!` rather than through the `label()` helper. Routing
2399/// [`std::fmt::Display`] through [`WitTarget::label`] closes the third
2400/// path: every `format!("{v}")` call reaches the same
2401/// [`WitTarget::payload_pair`]-shaped byte-string the `label()` helper
2402/// and the duplicate-`:contratos` gate already route through, so a
2403/// future variant addition (the M4-and-later per-edge WIT registry may
2404/// split [`WitTarget::Http`] into `Rest` / `Grpc` peers, or extend
2405/// [`WitTarget::Store`] with a `Queue`-shaped peer) reaches every
2406/// consumer at exactly one place — the [`WitTarget::payload_pair`]
2407/// match — rather than fanning out through hand-rolled per-arm
2408/// [`std::fmt::Display`] arms.
2409///
2410/// The dispatcher-catalog identity remains unaffected — [`WitTarget`]
2411/// is the typed view returned by [`WitContract::target`], not a
2412/// closed-set discriminator enum with a gen-platform Discriminant
2413/// registration, so the `Debug` derive's structural output (which every
2414/// `{v:?}` consumer still reaches) stays distinct from the `Display`
2415/// helper's stable pretty-printed byte-string. `Debug` reveals variant
2416/// shape for structural inspection; `Display` (via `label`) reveals the
2417/// stable author-facing payload projection.
2418///
2419/// Pin tests
2420/// [`tests::wit_target_display_routes_through_label_helper`] and
2421/// [`tests::wit_target_display_matches_duplicate_contratos_diagnostic_carrier`]
2422/// assert the two paths agree byte-for-byte on every variant, so a
2423/// future variant addition or `label()` reimplementation that hand-rolls
2424/// the arms instead of delegating to [`WitTarget::payload_pair`] is a
2425/// build error visible at caixa-core test time, not a silent
2426/// per-consumer dispatch miss at diagnostic / audit / graph time.
2427impl std::fmt::Display for WitTarget<'_> {
2428    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2429        f.write_str(&self.label())
2430    }
2431}
2432
2433// ── one Aplicacao member ─────────────────────────────────────────────
2434
2435/// A Servico participating in the Aplicacao. Same shape as
2436/// `crate::supervisor::ChildSpec` but without a restart policy —
2437/// supervision is per-Servico (each member has its own
2438/// `:supervisor`), the Aplicacao orchestrates *placement*.
2439#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2440#[serde(rename_all = "camelCase")]
2441pub struct Membro {
2442    /// Member caixa's `:nome`. Resolves through the same dep
2443    /// resolution path as `crate::dep::Dep`.
2444    pub caixa: String,
2445
2446    /// Semver constraint.
2447    pub versao: String,
2448}
2449
2450impl Membro {
2451    /// Substrate-canonical per-`:membros` member-caixa `:nome` scalar
2452    /// accessor every consumer that reads the member's Servico identity
2453    /// keys off — returns the author-declared `:membros :caixa`
2454    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
2455    /// own [`String`] storage.
2456    ///
2457    /// The `:membros :caixa` slot carries the caixa `:nome` of a Servico
2458    /// participating in the Aplicacao — validated by
2459    /// [`AplicacaoSpec::validate`] to be a non-empty DNS-1123 label
2460    /// (via [`validate_membro_caixa`]), unique across the Aplicacao's
2461    /// `:membros` list, distinct from the Aplicacao's own `:nome` (via
2462    /// [`validate_no_self_membership`]) — and every downstream consumer
2463    /// that fans on the member's identity keys off this scalar (the
2464    /// [`AplicacaoSpec::validate`] `:contratos`/`:entrada` member-set
2465    /// lookup, the per-`:membros` duplicate gate's dedup key, the
2466    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency map's node
2467    /// identity, the self-membership gate, the
2468    /// [`caixa_mesh::fleet_programs`] per-member programs.yaml entry
2469    /// `name:` axis, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
2470    /// CR materializer's per-member resolver).
2471    ///
2472    /// Prior to this lift the `.caixa` byte-string was read inline at
2473    /// five caixa-core sites (the [`AplicacaoSpec::validate`] member-name
2474    /// set collector at
2475    /// `self.membros.iter().map(|m| m.caixa.as_str())`, the
2476    /// [`validate_membros`] validation-side member-caixa gate at
2477    /// `validate_membro_caixa(&m.caixa)`, the [`validate_membros`]
2478    /// per-member duplicate-gate dedup key at
2479    /// `insert_first_seen(&mut seen, m.caixa.as_str(), …)`, the
2480    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency-map seed at
2481    /// `adj.entry(m.caixa.as_str()).or_default()`, and the
2482    /// [`validate_no_self_membership`] self-loop gate at
2483    /// `m.caixa == parent_nome`) — five open-coded field-accesses that
2484    /// expressed no compile-time link back to the typed slot. Every
2485    /// caixa-mesh `metadata.name` derived from a `:membros :caixa`
2486    /// value flows through the [`caixa_mesh::fleet_programs`] per-entry
2487    /// `name:` axis, so a future extension of the `:membros :caixa`
2488    /// axis to a richer author surface — a per-cluster alias table the
2489    /// operator pins through a future `:placement`-scoped slot, a
2490    /// namespace-qualified rewrite the M4 CR materializer applies
2491    /// per-CR, a per-member overlay from the future `:membros
2492    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
2493    /// acknowledges — would have had to be threaded through every
2494    /// open-coded copy in lockstep or one consumer would silently
2495    /// disagree with the peers on which caixa a given member resolves
2496    /// to. A member-set lookup that treated the name as `"cart"` while
2497    /// the peer adjacency map treated it as `"tenant-a/cart"` would
2498    /// silently split the `:contratos` membership-lookup diagnostic from
2499    /// the cycle-detector's node identity — a two-consumer split at the
2500    /// validator far from the source `caixa.lisp` with no field naming
2501    /// the identity-drift root cause. Lifting the resolution rule to a
2502    /// typed method on the substrate primitive means every downstream
2503    /// consumer of the Aplicacao's per-`:membros` identity surface
2504    /// reaches for exactly one typed dispatch — the resolver's
2505    /// accept-set migrates as a unit on any future axis addition.
2506    ///
2507    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2508    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2509    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2510    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2511    /// destination-Servico scalar accessors — same "one typed dispatch
2512    /// on the substrate primitive, thin projections at each consumer"
2513    /// discipline extended onto the per-`:membros` member-caixa `:nome`
2514    /// byte-string axis. Named `nome()` to match the tatara-lisp
2515    /// author-surface term the field's docstring already reaches for
2516    /// ("Member caixa's `:nome`") and the peer [`crate::Caixa::nome`] /
2517    /// [`crate::dep::Dep::nome`] field-name discipline the substrate
2518    /// already carries — the accessor's name maps directly onto the
2519    /// canonical caixa-identity vocabulary rather than shadowing the
2520    /// field's storage-side `caixa` label.
2521    #[must_use]
2522    pub const fn nome(&self) -> &str {
2523        self.caixa.as_str()
2524    }
2525
2526    /// Substrate-canonical per-`:membros` member-caixa `:versao` semver-
2527    /// requirement scalar accessor every consumer that reads the
2528    /// member's version pin keys off — returns the author-declared
2529    /// `:membros :versao` byte-string verbatim as a `&str`, borrowed
2530    /// from the typed slot's own [`String`] storage.
2531    ///
2532    /// The `:membros :versao` slot carries the Cargo-shaped semver
2533    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that
2534    /// pins which release of the member-caixa the Aplicacao composes
2535    /// against — the same requirement grammar the peer `:deps :versao`
2536    /// / `:children :versao` axes carry, resolved through the shared
2537    /// [`crate::render::require_valid_versao_requirement`] cascade and
2538    /// the shared [`crate::version::parse_requirement`] parser. Every
2539    /// downstream consumer that fans on the member's version pin keys
2540    /// off this scalar (the [`validate_membros`] per-member requirement
2541    /// gate at `require_valid_versao_requirement(m.versao_requirement(),
2542    /// …)`, the [`feira app graph`] per-member `println!("    - {} {}",
2543    /// m.nome(), m.versao_requirement())` line, every future per-cluster
2544    /// version-lock overlay the operator pins through a future
2545    /// `:placement`-scoped slot, the future
2546    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-member
2547    /// version resolver, the future `feira app deploy` pipeline's
2548    /// per-member lacre BLAKE3-closure lookup).
2549    ///
2550    /// Prior to this lift the `.versao` byte-string was accessed inline
2551    /// at two `&str`-shaped sites — the [`validate_membros`]
2552    /// requirement-gate call `require_valid_versao_requirement(&m.versao,
2553    /// …)` and the `feira app graph` per-member printer's `println!(
2554    /// "    - {} {}", m.caixa, m.versao)` (caixa-feira/src/cmd/app.rs:78
2555    /// prior to this lift) — two open-coded field-accesses that expressed
2556    /// no compile-time link back to the typed slot. A future extension of
2557    /// the `:membros :versao` axis to a richer author surface (a
2558    /// per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
2559    /// flow, a lacre-projected concrete-version rewrite the operator
2560    /// materializes at CR-admission time, a future `:membros :versao-lock`
2561    /// per-cluster override slot) would have had to be threaded through
2562    /// every open-coded copy in lockstep or one consumer would silently
2563    /// disagree with the peers on which release constraint a given
2564    /// member resolves to. Lifting the resolution rule to a typed method
2565    /// on the substrate primitive means every downstream requirement-
2566    /// facing consumer reaches for exactly one typed dispatch — the
2567    /// resolver's accept-set migrates as a unit on any future axis
2568    /// addition.
2569    ///
2570    /// Sibling of the peer per-`:membros` [`Membro::nome`] (4a32abf)
2571    /// member-caixa `:nome` scalar accessor — the pair
2572    /// `(nome(), versao_requirement())` jointly projects the
2573    /// `(caixa, versao)` field pair every renderer that fans on
2574    /// per-member identity + version pin keys off, closing the last
2575    /// unlifted per-`:membros` scalar axis so every downstream
2576    /// per-`:membros` reader now routes through a typed dispatch on the
2577    /// substrate primitive. Named `versao_requirement()` rather than
2578    /// `versao()` because the field's storage-side `.versao` label is
2579    /// already the author-surface term (`:versao`); the accessor's name
2580    /// carries the semantic role — the semver *requirement* string the
2581    /// shared [`crate::version::parse_requirement`] entry-point consumes
2582    /// — so a raw field access and a typed dispatch read differently at
2583    /// every consumer site.
2584    ///
2585    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2586    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2587    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2588    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2589    /// destination-Servico scalar accessors — same "one typed dispatch
2590    /// on the substrate primitive, thin projections at each consumer"
2591    /// discipline extended onto the per-`:membros` member-`:versao`
2592    /// semver-requirement byte-string axis.
2593    #[must_use]
2594    pub const fn versao_requirement(&self) -> &str {
2595        self.versao.as_str()
2596    }
2597}
2598
2599// ── mesh-level policies ──────────────────────────────────────────────
2600
2601/// Mesh policies that apply to every `:contratos` edge unless
2602/// overridden per-edge in M4. V0 is a single global policy block.
2603#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
2604#[serde(rename_all = "camelCase")]
2605pub struct MeshPolicy {
2606    /// Per-call timeout. Authored as a duration string (`"30s"`).
2607    #[serde(
2608        default,
2609        skip_serializing_if = "Option::is_none",
2610        with = "supervisor::duration_codec"
2611    )]
2612    pub timeout: Option<Duration>,
2613
2614    /// Number of retries on transient failure. None = no retries.
2615    #[serde(default, skip_serializing_if = "Option::is_none")]
2616    pub retries: Option<u32>,
2617
2618    /// Circuit breaker config. Trips after N failures within W
2619    /// duration; closes after a cooldown.
2620    #[serde(default, skip_serializing_if = "Option::is_none")]
2621    pub circuit_breaker: Option<CircuitBreaker>,
2622
2623    /// Whether mTLS is required for every contrato. Default: true
2624    /// (sandboxing-by-default; explicit opt-out only).
2625    #[serde(default, skip_serializing_if = "Option::is_none")]
2626    pub mtls_required: Option<bool>,
2627
2628    /// Token-bucket rate limit. Authored as `"100/s"` or
2629    /// `"5000/m"`; stored as `(rate, window)`.
2630    #[serde(
2631        default,
2632        skip_serializing_if = "Option::is_none",
2633        with = "rate_limit_codec"
2634    )]
2635    pub rate_limit: Option<RateLimit>,
2636}
2637
2638impl MeshPolicy {
2639    /// True when no `:politicas` axis carries a value — every field is
2640    /// `None`. The same emptiness contract every other M2/M3 typed
2641    /// surface carries ([`crate::LimitsSpec::is_empty`],
2642    /// [`crate::BehaviorSpec::is_empty`]): renderers that overlay the
2643    /// typed slot onto a cluster artifact key off this predicate to
2644    /// decide "emit the slot" vs "skip the slot entirely", so an
2645    /// authored-but-unset `:politicas (())` round-trips to a rendered
2646    /// artifact that's structurally identical to one that omits the
2647    /// slot. Lifted as a typed predicate (rather than per-renderer
2648    /// inline `politicas.timeout.is_none() && politicas.retries.is_none()
2649    /// && …` chains) so a future axis added to `MeshPolicy` (per-edge
2650    /// :politicas overlay in M4, per-Aplicacao traffic-shaping in M5)
2651    /// is one struct-field edit + one `&& self.<axis>.is_none()` here,
2652    /// not a coordinated rewrite of every consumer that's reaching
2653    /// for the emptiness semantic.
2654    #[must_use]
2655    pub const fn is_empty(&self) -> bool {
2656        self.timeout().is_none()
2657            && self.retries().is_none()
2658            && self.circuit_breaker().is_none()
2659            && self.mtls_required().is_none()
2660            && self.rate_limit().is_none()
2661    }
2662
2663    /// Substrate-canonical cross-axis coherence predicate on the
2664    /// `:politicas` slot: does the `:circuit-breaker :window` rolling
2665    /// failure-observation interval span at least one full
2666    /// `:timeout`-bounded call?
2667    ///
2668    /// The first *cross-axis* invariant on the `:politicas` surface —
2669    /// every prior gate ([`AplicacaoSpec::validate_politicas`]'s four
2670    /// zero-floor + canonical-form + cap brackets) validates one axis
2671    /// in isolation, so a `MeshPolicy` whose axes are each individually
2672    /// well-formed could still name a structurally inert pair. The
2673    /// pair `{ timeout: 30s, circuit_breaker: { window: 10s, .. } }`
2674    /// passes every per-axis bracket (30s ≤ [`POLICY_TIMEOUT_MAX`],
2675    /// 10s ≤ [`POLICY_BREAKER_WINDOW_MAX`], both integer-millisecond,
2676    /// both above the zero floor) and is nonetheless a breaker that
2677    /// cannot trip on the failure mode it exists to catch: a call
2678    /// dispatched at t=0 is declared failed at t=30s, by which point
2679    /// the 10s window open at dispatch has rolled twice over, so no
2680    /// window can ever hold even one timeout-derived failure however
2681    /// high the call volume. Envoy's `outlier_detection.interval`
2682    /// carries the identical relation against the per-route request
2683    /// timeout; Hystrix ships the canonical ratio in its defaults
2684    /// (10s `metrics.rollingStats.timeInMilliseconds` against a 1s
2685    /// `execution.isolation.thread.timeoutInMilliseconds`).
2686    ///
2687    /// Vacuously `true` when either axis is absent — a `:politicas`
2688    /// that names only one of the pair declares no relation for the
2689    /// substrate to hold it to (`:timeout` alone is a per-call deadline
2690    /// with no breaker; `:circuit-breaker` alone is a breaker whose
2691    /// failures arrive from the transport's own error signal rather
2692    /// than from a substrate-imposed deadline, so no dispatch-to-report
2693    /// lag is knowable at author time). This is the same
2694    /// "unset means the cluster default applies, not zero" partition
2695    /// [`MeshPolicy::is_empty`] and every per-axis accessor's `None`
2696    /// arm already carry.
2697    ///
2698    /// Lifted as a typed predicate on the substrate primitive rather
2699    /// than open-coded at the validate gate so every downstream
2700    /// consumer of the pair reaches the invariant through one dispatch:
2701    /// the [`AplicacaoSpec::validate_politicas`] gate below, the future
2702    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2703    /// (MESH-COMPOSITION §III.2 #3) that must emit
2704    /// `outlier_detection.interval` and the per-route `timeout` as one
2705    /// coherent Envoy block, the future M4
2706    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
2707    /// webhook, and the future per-`:contratos`-edge `:politicas`
2708    /// override that same roadmap acknowledges — which resolves an
2709    /// *effective* pair per edge (edge-level `:timeout` against the
2710    /// Aplicacao-level `:window`, or vice versa) and so must re-check
2711    /// the relation on a pair neither axis's declaration site can see
2712    /// whole. Naming the invariant once means that resolver folds this
2713    /// predicate over its resolved pair instead of re-deriving the
2714    /// comparison, exactly as the sibling cross-slot
2715    /// [`PlacementStrategy::is_shard_keyed`] predicate names the
2716    /// `:placement`/`:shard-key` relation for its own consumers.
2717    #[must_use]
2718    pub const fn breaker_window_observes_timeout(&self) -> bool {
2719        match (self.timeout(), self.circuit_breaker()) {
2720            (Some(timeout), Some(cb)) => cb.window().as_nanos() >= timeout.as_nanos(),
2721            _ => true,
2722        }
2723    }
2724
2725    /// Substrate-canonical cross-axis coherence predicate on the
2726    /// `:politicas` slot: can the token-bucket rate declared by
2727    /// `:rate-limit` dispatch enough calls inside `:circuit-breaker
2728    /// :window` to reach `:max-failures`?
2729    ///
2730    /// The second cross-axis invariant on the `:politicas` surface —
2731    /// sibling to [`MeshPolicy::breaker_window_observes_timeout`] on
2732    /// the `(:timeout, :circuit-breaker :window)` pair, extended onto
2733    /// the `(:rate-limit, :circuit-breaker)` pair. Each axis in the
2734    /// pair is validated in isolation by the per-axis brackets in
2735    /// [`AplicacaoSpec::validate_politicas`] (rate zero-floor + cap,
2736    /// max-failures zero-floor + cap, both windows zero-floor +
2737    /// integer-millisecond + cap, rate-limit window canonical-form),
2738    /// so a `MeshPolicy` whose axes are each individually well-formed
2739    /// can still name a structurally inert pair. The pair
2740    /// `{ rate-limit: "1/h", circuit-breaker: (:max-failures 5 :window
2741    /// "10s") }` passes every per-axis bracket and is nonetheless a
2742    /// breaker that cannot trip on the failure mode it exists to
2743    /// catch: the token bucket admits `rate × (cb.window / rl.window)`
2744    /// = `1 × (10s / 3600s)` ≈ 0 calls per rolling breaker window, so
2745    /// no window can accumulate five failures however catastrophically
2746    /// the upstream is failing. Envoy's
2747    /// `outlier_detection.consecutive_5xx` paired against
2748    /// `local_rate_limit.token_bucket.max_tokens` /
2749    /// `fill_interval` carries the identical relation; every
2750    /// production playbook that pairs the two axes (Envoy, Istio, AWS
2751    /// App Mesh, Kong) recommends sizing the rate at or above the
2752    /// breaker's minimum-request-volume threshold for exactly this
2753    /// reason.
2754    ///
2755    /// The typed test is the integer inequality
2756    /// `rate × cb.window.as_nanos() >= max_failures × rl.window.as_nanos()`
2757    /// (rearranged from `rate × cb.window / rl.window >= max_failures`
2758    /// so no floating-point division mediates the comparison and so
2759    /// the sub-second `rl.window` arms — `"n/s"` = 1s — are treated
2760    /// exactly). Both multiplicands are `saturating_mul`'d into
2761    /// [`u128`] so a struct-literal `MeshPolicy` whose per-axis fields
2762    /// have not yet passed [`AplicacaoSpec::validate_politicas`]
2763    /// (e.g. `rate: u32::MAX, cb_window: Duration::MAX`) does not
2764    /// panic the predicate; a saturated pair collapses to the
2765    /// "vacuously coherent" branch the peer per-axis brackets reject
2766    /// via their own zero-floor / cap arms first.
2767    ///
2768    /// Vacuously `true` when either axis is absent — a `:politicas`
2769    /// that names only one of the pair declares no relation for the
2770    /// substrate to hold it to (`:rate-limit` alone is a per-edge
2771    /// token-bucket declaration with no failure counter to starve;
2772    /// `:circuit-breaker` alone is a rolling-window failure counter
2773    /// whose call rate is unconstrained by the substrate, so no
2774    /// bucket-derived upper bound on calls-per-window is knowable at
2775    /// author time). Same "unset means the cluster default applies,
2776    /// not zero" partition [`MeshPolicy::is_empty`] and the sibling
2777    /// [`MeshPolicy::breaker_window_observes_timeout`] predicate
2778    /// carry.
2779    ///
2780    /// Lifted as a typed predicate on the substrate primitive rather
2781    /// than open-coded at the validate gate so every downstream
2782    /// consumer of the pair reaches the invariant through one
2783    /// dispatch: the [`AplicacaoSpec::validate_politicas`] gate
2784    /// below, the future `CiliumClusterwideEnvoyConfig`
2785    /// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) that
2786    /// must emit `local_rate_limit.token_bucket.{max_tokens,
2787    /// fill_interval}` alongside `outlier_detection.consecutive_5xx`
2788    /// / `outlier_detection.interval` as one coherent Envoy block,
2789    /// the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
2790    /// materializer's admission webhook, and the future
2791    /// per-`:contratos`-edge `:politicas` override the same roadmap
2792    /// acknowledges — which resolves an *effective* pair per edge
2793    /// (edge-level `:rate-limit` against the Aplicacao-level
2794    /// `:circuit-breaker`, or vice versa) and so must re-check the
2795    /// relation on a pair neither axis's declaration site can see
2796    /// whole. Naming the invariant once means that resolver folds
2797    /// this predicate over its resolved pair instead of re-deriving
2798    /// the comparison, exactly as the sibling cross-axis
2799    /// [`MeshPolicy::breaker_window_observes_timeout`] predicate
2800    /// names the `(:timeout, :window)` relation for its own consumers.
2801    #[must_use]
2802    pub const fn breaker_can_trip_under_rate_limit(&self) -> bool {
2803        match (self.rate_limit(), self.circuit_breaker()) {
2804            (Some(rl), Some(cb)) => {
2805                let calls_per_cb_window =
2806                    (rl.rate() as u128).saturating_mul(cb.window().as_nanos());
2807                let trip_threshold_per_cb_window =
2808                    (cb.max_failures() as u128).saturating_mul(rl.window().as_nanos());
2809                calls_per_cb_window >= trip_threshold_per_cb_window
2810            }
2811            _ => true,
2812        }
2813    }
2814
2815    /// Substrate-canonical cross-axis coherence predicate on the
2816    /// `:politicas` slot: can one client's declared `:retries` all
2817    /// complete before `:circuit-breaker :max-failures` trips the
2818    /// breaker mid-retry?
2819    ///
2820    /// The third cross-axis invariant on the `:politicas` surface —
2821    /// sibling to [`MeshPolicy::breaker_window_observes_timeout`] on
2822    /// the `(:timeout, :circuit-breaker :window)` pair and
2823    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] on the
2824    /// `(:rate-limit, :circuit-breaker)` pair, extended onto the
2825    /// `(:retries, :circuit-breaker :max-failures)` pair. Each axis in
2826    /// the pair is validated in isolation by the per-axis brackets in
2827    /// [`AplicacaoSpec::validate_politicas`] (retries zero-floor + cap,
2828    /// max-failures zero-floor + cap), so a `MeshPolicy` whose axes
2829    /// are each individually well-formed can still name a
2830    /// structurally-inert retry policy. The pair
2831    /// `{ :retries 3, :circuit-breaker (:max-failures 3 :window "1s") }`
2832    /// passes every per-axis bracket and is nonetheless a retry
2833    /// policy the substrate cannot honor: one client's initial attempt
2834    /// plus three retries is four attempts, but the breaker trips on
2835    /// the third failure — the fourth attempt (the last declared
2836    /// retry) is blocked by the open breaker, so the substrate
2837    /// declared four attempts and structurally allows three.
2838    ///
2839    /// The typed test is the integer inequality
2840    /// `cb.max_failures() > retries` — the retries count is the
2841    /// *number of retry attempts beyond the initial* (Envoy's
2842    /// `retry_policy.num_retries` semantics), so a client makes at
2843    /// most `retries + 1` attempts per client call, each of which may
2844    /// fail. For the breaker to *admit* the retry policy through
2845    /// completion, its trip threshold must not be reached by one
2846    /// client's failures alone: `retries + 1 <= max_failures`,
2847    /// equivalently `retries < max_failures`, equivalently
2848    /// `max_failures > retries`. The boundary case
2849    /// `max_failures == retries + 1` accepts (the R+1th failure — the
2850    /// last retry — trips the breaker exactly as it completes; retries
2851    /// are fully executed). The strict-below case
2852    /// `max_failures <= retries` rejects (the breaker trips before
2853    /// retries exhaust, silently truncating the declared retry policy
2854    /// mid-run — the same declared-but-structurally-inert footgun the
2855    /// sibling per-axis cap arms close on the single-axis surfaces).
2856    ///
2857    /// Vacuously `true` when either axis is absent — a `:politicas`
2858    /// that names only one of the pair declares no relation for the
2859    /// substrate to hold it to (`:retries` alone is a client-retry
2860    /// policy with no failure counter to trip; `:circuit-breaker`
2861    /// alone is a failure counter whose per-client attempt count is
2862    /// unconstrained by the substrate, so no per-client saturation
2863    /// bound on failures-per-client-call is knowable at author time).
2864    /// Same "unset means the cluster default applies, not zero"
2865    /// partition [`MeshPolicy::is_empty`] and the sibling
2866    /// [`MeshPolicy::breaker_window_observes_timeout`] /
2867    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
2868    /// carry.
2869    ///
2870    /// Lifted as a typed predicate on the substrate primitive rather
2871    /// than open-coded at the validate gate so every downstream
2872    /// consumer of the pair reaches the invariant through one
2873    /// dispatch: the [`AplicacaoSpec::validate_politicas`] gate
2874    /// below, the future `CiliumClusterwideEnvoyConfig`
2875    /// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) that
2876    /// must emit `retry_policy.num_retries` alongside
2877    /// `outlier_detection.consecutive_5xx` as one coherent Envoy
2878    /// block, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
2879    /// materializer's admission webhook, and the future
2880    /// per-`:contratos`-edge `:politicas` override the same roadmap
2881    /// acknowledges — which resolves an *effective* pair per edge
2882    /// (edge-level `:retries` against the Aplicacao-level
2883    /// `:circuit-breaker`, or vice versa) and so must re-check the
2884    /// relation on a pair neither axis's declaration site can see
2885    /// whole. Naming the invariant once means that resolver folds
2886    /// this predicate over its resolved pair instead of re-deriving
2887    /// the comparison, exactly as the sibling cross-axis
2888    /// [`MeshPolicy::breaker_window_observes_timeout`] and
2889    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
2890    /// name the `(:timeout, :window)` and `(:rate-limit,
2891    /// :circuit-breaker)` relations for their own consumers.
2892    #[must_use]
2893    pub const fn retries_fit_under_breaker_trip_threshold(&self) -> bool {
2894        match (self.retries(), self.circuit_breaker()) {
2895            (Some(retries), Some(cb)) => cb.max_failures() > retries,
2896            _ => true,
2897        }
2898    }
2899
2900    /// Substrate-canonical cross-axis coherence predicate on the
2901    /// `:politicas` slot: does the `:rate-limit` token-bucket capacity
2902    /// admit one client's full `:retries + 1` attempt burst inside a
2903    /// single refill window?
2904    ///
2905    /// The fourth cross-axis invariant on the `:politicas` surface,
2906    /// completing the triangle of pairs the three sibling gates carve
2907    /// out — sibling to [`MeshPolicy::breaker_window_observes_timeout`]
2908    /// on the `(:timeout, :circuit-breaker :window)` pair,
2909    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] on the
2910    /// `(:rate-limit, :circuit-breaker)` pair, and
2911    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`] on the
2912    /// `(:retries, :circuit-breaker :max-failures)` pair, extended onto
2913    /// the `(:retries, :rate-limit)` pair — the last cross-axis relation
2914    /// among the three scalar `:politicas` axes (`:retries`,
2915    /// `:rate-limit`, `:circuit-breaker`) whose axis-triple defines the
2916    /// coherence surface every production overlay (Envoy, Istio,
2917    /// resilience4j, AWS App Mesh) resolves as one block. Each axis in
2918    /// the pair is validated in isolation by the per-axis brackets in
2919    /// [`AplicacaoSpec::validate_politicas`] (retries zero-floor + cap,
2920    /// rate zero-floor + cap, window canonical-form), so a `MeshPolicy`
2921    /// whose axes are each individually well-formed can still name a
2922    /// structurally-truncated retry policy the rate limiter refuses to
2923    /// admit. The pair `{ :retries 5, :rate-limit "3/s" }` passes every
2924    /// per-axis bracket and is nonetheless a retry policy the substrate
2925    /// cannot honor: one client's initial attempt plus five retries is
2926    /// six attempts, but the token bucket admits at most three tokens
2927    /// per one-second refill window, so the fourth attempt onward is
2928    /// blocked by the rate limiter itself — the substrate declared six
2929    /// attempts and structurally allows three. Envoy's
2930    /// `local_rate_limit.token_bucket.max_tokens` paired against
2931    /// `retry_policy.num_retries` carries the identical relation; every
2932    /// production playbook that pairs the two axes recommends sizing
2933    /// the bucket capacity above any single client's retry budget so
2934    /// the retry policy is not silently truncated by the same rate
2935    /// limiter it feeds through.
2936    ///
2937    /// The typed test is the integer inequality
2938    /// `rl.rate() >= retries + 1` — the retries count is the *number of
2939    /// retry attempts beyond the initial* (Envoy's
2940    /// `retry_policy.num_retries` semantics), so a client makes at most
2941    /// `retries + 1` attempts per client call, each of which consumes
2942    /// one token from the local rate-limit bucket. For the bucket to
2943    /// *admit* the retry burst without dropping tokens, its capacity
2944    /// must not be reached by one client's attempts alone:
2945    /// `retries + 1 <= rate`, equivalently `rate >= retries + 1`. The
2946    /// boundary case `rate == retries + 1` accepts (the bucket admits
2947    /// exactly one client's full retry sequence per refill window —
2948    /// retries fully executed). The strict-below case `rate <= retries`
2949    /// rejects (the bucket exhausts before retries complete, silently
2950    /// truncating the declared retry policy mid-run — the same
2951    /// declared-but-structurally-inert footgun the sibling per-axis cap
2952    /// arms close on the single-axis surfaces). The equivalent
2953    /// coherent-direction form `rl.rate() > retries` sidesteps the
2954    /// `retries + 1` addition entirely (both `rate` and `retries` are
2955    /// `u32`; the `>` comparison is total on the type with no overflow
2956    /// against past-the-guard struct-literal `retries` values a caller
2957    /// might pass before `validate` runs), matching the peer
2958    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`] direct-
2959    /// `>`-comparison discipline on the sibling
2960    /// `(:retries, :max-failures)` pair.
2961    ///
2962    /// Vacuously `true` when either axis is absent — a `:politicas`
2963    /// that names only one of the pair declares no relation for the
2964    /// substrate to hold it to (`:retries` alone is a client-retry
2965    /// policy with no rate limiter to saturate; `:rate-limit` alone is
2966    /// a token-bucket declaration whose per-client attempt count is
2967    /// unconstrained by the substrate, so no per-client saturation
2968    /// bound on tokens-per-client-call is knowable at author time).
2969    /// Same "unset means the cluster default applies, not zero"
2970    /// partition [`MeshPolicy::is_empty`] and the three sibling
2971    /// cross-axis predicates
2972    /// ([`MeshPolicy::breaker_window_observes_timeout`],
2973    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`],
2974    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]) carry.
2975    ///
2976    /// Lifted as a typed predicate on the substrate primitive rather
2977    /// than open-coded at the validate gate so every downstream
2978    /// consumer of the pair reaches the invariant through one dispatch:
2979    /// the [`AplicacaoSpec::validate_politicas`] gate below, the future
2980    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2981    /// (MESH-COMPOSITION §III.2 #3) that must emit
2982    /// `local_rate_limit.token_bucket.max_tokens` alongside
2983    /// `retry_policy.num_retries` as one coherent Envoy block, the
2984    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
2985    /// admission webhook, and the future per-`:contratos`-edge
2986    /// `:politicas` override the same roadmap acknowledges — which
2987    /// resolves an *effective* pair per edge (edge-level `:retries`
2988    /// against the Aplicacao-level `:rate-limit`, or vice versa) and
2989    /// so must re-check the relation on a pair neither axis's
2990    /// declaration site can see whole. Naming the invariant once means
2991    /// that resolver folds this predicate over its resolved pair
2992    /// instead of re-deriving the comparison, exactly as the three
2993    /// sibling cross-axis predicates name the
2994    /// `(:timeout, :window)` / `(:rate-limit, :circuit-breaker)` /
2995    /// `(:retries, :max-failures)` relations for their own consumers,
2996    /// closing the fourth and last cross-axis relation on the scalar
2997    /// `:politicas` axis-triple.
2998    #[must_use]
2999    pub const fn rate_limit_admits_retry_burst(&self) -> bool {
3000        match (self.retries(), self.rate_limit()) {
3001            (Some(retries), Some(rl)) => rl.rate() > retries,
3002            _ => true,
3003        }
3004    }
3005
3006    /// Substrate-canonical fold over the four cross-axis coherence
3007    /// predicates on the `:politicas` slot — returns the *first*
3008    /// cross-axis violation (as its [`AplicacaoError`] variant) in the
3009    /// canonical "more-foundational-cross-axis first" ordering
3010    /// [`MeshPolicy::breaker_window_observes_timeout`] on
3011    /// `(:timeout, :circuit-breaker :window)` →
3012    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] on
3013    /// `(:rate-limit, :circuit-breaker)` →
3014    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`] on
3015    /// `(:retries, :circuit-breaker :max-failures)` →
3016    /// [`MeshPolicy::rate_limit_admits_retry_burst`] on `(:retries,
3017    /// :rate-limit)`. Returns `None` when every cross-axis relation
3018    /// holds (the vacuous shape [`MeshPolicy::is_empty`] and the fully-
3019    /// coherent shape both land here).
3020    ///
3021    /// The ordering discipline this method encodes was open-coded four
3022    /// times at [`AplicacaoSpec::validate_politicas`] — each cross-axis
3023    /// gate was an `if !<predicate>() { let <a> = self.<axis>().expect(
3024    /// "cross-axis gate fires only when :<axis> is present"); let <b>
3025    /// = self.<axis>().expect(…); return Err(<variant>) }` block whose
3026    /// axis-fetch step depended on the predicate having just returned
3027    /// `false` (structurally guaranteed both paired axes are `Some`,
3028    /// but the compiler cannot see through the predicate body, so
3029    /// every arm re-called the accessor with `.expect(…)` to reach
3030    /// the axis it just tested). Two unsound consequences: (1) the
3031    /// validate gate carried eight `.expect(…)` panic call sites the
3032    /// predicate contract already forbids on every well-typed input
3033    /// but the type system does not enforce; (2) the
3034    /// "which-cross-axis-fires-first-when-two-apply" contract lived
3035    /// twice — once in each predicate's own doc comments and once at
3036    /// the validate call site's four-arm cascade. Lifting the four-arm
3037    /// cascade onto this substrate primitive collapses both
3038    /// duplications: the predicate contract and the axis-fetch step
3039    /// live in the same body (no `.expect(…)` — the pattern match at
3040    /// each arm rebinds the paired axes so their `Some` presence is a
3041    /// compile-time property of the local scope), and the ordering
3042    /// discipline lives once at the top of the primitive rather than
3043    /// scattered across four sibling doc-comment blocks that must
3044    /// stay in lockstep.
3045    ///
3046    /// Every downstream cross-axis consumer (the [`AplicacaoSpec::
3047    /// validate_politicas`] gate below, the future M4 `mesh.pleme.io/
3048    /// v1alpha1/Aplicacao` CR materializer's admission webhook, the
3049    /// per-`:contratos`-edge `:politicas` override MESH-COMPOSITION
3050    /// §III.2 #3 acknowledges — the last of which resolves an
3051    /// *effective* per-edge pair and must emit *the same* diagnostic
3052    /// on the same paired-axis input as `feira build`) reaches through
3053    /// one call rather than re-inlining the four pattern-matches +
3054    /// accessor-fetches + variant-constructions + ordering-cascade.
3055    ///
3056    /// Returns owned copies of every axis carried into the diagnostic:
3057    /// [`Duration`] and [`u32`] are `Copy`, so no `String` allocation
3058    /// occurs on the happy path when no violation fires.
3059    #[must_use]
3060    pub fn first_cross_axis_violation(&self) -> Option<AplicacaoError> {
3061        // Ordering discipline this fold encodes matches the four
3062        // per-arm predicate doc comments' pairwise-ordering contract:
3063        // window-below-timeout wins over every arm that names `:rate-
3064        // limit` or `:retries` (its diagnostic is more self-locating —
3065        // the pair is a per-call-deadline invariant every synchronous
3066        // edge carries whether or not `:rate-limit`/`:retries` is
3067        // declared); the starve arm wins over the two retry arms (its
3068        // diagnostic reasons across the token-bucket-vs-breaker
3069        // relation, an axis the retry arms do not touch); the
3070        // retries-saturate arm wins over the retries-burst arm (its
3071        // diagnostic reasons across the per-client-vs-breaker
3072        // relation, which carries whether or not `:rate-limit` is
3073        // declared). Each arm rebinds the paired axes through the
3074        // pattern match, so the `.expect(…)` panics the four-block
3075        // cascade at `validate_politicas` carried collapse to no-op
3076        // pattern rebindings the compiler statically proves exhaust.
3077        if let (Some(t), Some(cb)) = (self.timeout(), self.circuit_breaker())
3078            && !self.breaker_window_observes_timeout()
3079        {
3080            return Some(AplicacaoError::policy_breaker_window_below_timeout(&cb, t));
3081        }
3082        if let (Some(rl), Some(cb)) = (self.rate_limit(), self.circuit_breaker())
3083            && !self.breaker_can_trip_under_rate_limit()
3084        {
3085            return Some(AplicacaoError::policy_breaker_cannot_trip_under_rate_limit(
3086                &rl, &cb,
3087            ));
3088        }
3089        if let (Some(retries), Some(cb)) = (self.retries(), self.circuit_breaker())
3090            && !self.retries_fit_under_breaker_trip_threshold()
3091        {
3092            return Some(
3093                AplicacaoError::policy_breaker_trips_before_retries_exhausted(retries, &cb),
3094            );
3095        }
3096        if let (Some(retries), Some(rl)) = (self.retries(), self.rate_limit())
3097            && !self.rate_limit_admits_retry_burst()
3098        {
3099            return Some(AplicacaoError::policy_rate_limit_cannot_admit_retry_burst(
3100                retries, &rl,
3101            ));
3102        }
3103        None
3104    }
3105
3106    /// Substrate-canonical compound entry gate over the whole
3107    /// `:politicas` typed slot — folds every per-axis bracket
3108    /// (`:timeout` / `:retries` / `:circuit-breaker :max-failures` /
3109    /// `:circuit-breaker :window` / `:rate-limit` rate / `:rate-limit`
3110    /// window-canonical-form) *and* the compound cross-axis fold
3111    /// [`MeshPolicy::first_cross_axis_violation`] into one call every
3112    /// consumer of a validated [`MeshPolicy`] reaches through.
3113    ///
3114    /// Returns the first violation as its [`AplicacaoError`] variant,
3115    /// or `Ok(())` when every per-axis value lies in its accept-set and
3116    /// every cross-axis relation holds. Per-axis brackets run strictly
3117    /// before the cross-axis fold — the sibling
3118    /// [`AplicacaoSpec::validate_politicas`] gate carried the same
3119    /// ordering discipline for the same reason: a per-axis
3120    /// structurally-invalid value (a `Duration::ZERO` `:window`, an
3121    /// above-cap `:rate-limit` rate) surfaces its own self-locating
3122    /// diagnostic first, ahead of any cross-axis arm that would send
3123    /// the author to reconcile two values one of which is not a
3124    /// meaningful window at all. Within the per-axis phase, arms fire
3125    /// in the same slot-order the peer per-axis brackets carry
3126    /// (`:timeout` → `:retries` → `:circuit-breaker` → `:rate-limit`,
3127    /// each internally ordered zero-floor before canonical-form before
3128    /// cap by [`crate::render::require_positive_bounded_u32`] /
3129    /// [`crate::render::require_positive_canonical_bounded_duration`]);
3130    /// within the cross-axis phase, arms fire in the canonical
3131    /// more-foundational-cross-axis-first ordering
3132    /// [`MeshPolicy::first_cross_axis_violation`] encodes.
3133    ///
3134    /// Lifted as a typed method on the substrate primitive so every
3135    /// downstream consumer of a validated [`MeshPolicy`] reaches the
3136    /// invariant through one dispatch: the
3137    /// [`AplicacaoSpec::validate_politicas`] gate below (whose whole
3138    /// body collapses to `self.politicas().validate()`), the future
3139    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
3140    /// admission webhook, the future per-`:contratos`-edge `:politicas`
3141    /// override MESH-COMPOSITION §III.2 #3 acknowledges — the last of
3142    /// which resolves an *effective* per-edge [`MeshPolicy`] and must
3143    /// emit *the same* diagnostic on the same input as `feira build`.
3144    /// Naming the compound gate once on the substrate primitive means
3145    /// every downstream consumer inherits both the per-axis brackets
3146    /// *and* the cross-axis fold through one call, rather than
3147    /// re-inlining the four-per-axis + one-cross-axis cascade in
3148    /// lockstep with `validate_politicas`.
3149    ///
3150    /// Peer of the per-kind compound entry gates lifted at
3151    /// [`crate::render::require_aplicacao_view`] (7242d45 / 3aefefb),
3152    /// [`crate::render::require_supervisor_view`] (8d8a5c3), and
3153    /// [`crate::render::require_v0_servico_shape`] on the per-Caixa
3154    /// layout axis, and the sibling compound cross-axis fold
3155    /// [`MeshPolicy::first_cross_axis_violation`] on the same
3156    /// `:politicas` axis — extended here onto the per-slot per-axis +
3157    /// cross-axis compound entry gate that folds both surfaces.
3158    pub fn validate(&self) -> Result<(), AplicacaoError> {
3159        if let Some(t) = self.timeout() {
3160            crate::render::require_positive_canonical_bounded_duration(
3161                t,
3162                POLICY_TIMEOUT_MAX,
3163                || AplicacaoError::PolicyTimeoutZero,
3164                AplicacaoError::policy_timeout_not_canonical,
3165                AplicacaoError::policy_timeout_exceeds_cap,
3166            )?;
3167        }
3168        if let Some(r) = self.retries() {
3169            crate::render::require_positive_bounded_u32(
3170                r,
3171                POLICY_RETRIES_MAX,
3172                || AplicacaoError::PolicyRetriesZero,
3173                AplicacaoError::policy_retries_exceeds_cap,
3174            )?;
3175        }
3176        if let Some(cb) = self.circuit_breaker() {
3177            crate::render::require_positive_bounded_u32(
3178                cb.max_failures(),
3179                POLICY_BREAKER_MAX_FAILURES_MAX,
3180                || AplicacaoError::PolicyBreakerZeroFailures,
3181                AplicacaoError::policy_breaker_max_failures_exceeds_cap,
3182            )?;
3183            crate::render::require_positive_canonical_bounded_duration(
3184                cb.window(),
3185                POLICY_BREAKER_WINDOW_MAX,
3186                || AplicacaoError::PolicyBreakerZeroWindow,
3187                AplicacaoError::policy_breaker_window_not_canonical,
3188                AplicacaoError::policy_breaker_window_exceeds_cap,
3189            )?;
3190        }
3191        if let Some(rl) = self.rate_limit() {
3192            crate::render::require_positive_bounded_u32(
3193                rl.rate(),
3194                POLICY_RATE_LIMIT_MAX,
3195                || AplicacaoError::PolicyRateLimitZero,
3196                AplicacaoError::policy_rate_limit_exceeds_cap,
3197            )?;
3198            if rl.canonical_unit().is_none() {
3199                return Err(AplicacaoError::policy_rate_limit_window_not_canonical(
3200                    rl.window(),
3201                ));
3202            }
3203        }
3204        if let Some(err) = self.first_cross_axis_violation() {
3205            return Err(err);
3206        }
3207        Ok(())
3208    }
3209
3210    /// Substrate-canonical per-`:politicas` `:timeout` Gateway-API-mesh
3211    /// per-call-deadline scalar accessor every consumer of the
3212    /// Aplicacao's Gateway API v1.x per-rule request-timeout keys off —
3213    /// returns the author-declared `:politicas :timeout` typed
3214    /// [`Duration`] verbatim as an `Option<Duration>`, copied out of the
3215    /// typed slot's own `Option<Duration>` storage (`Option<Duration>`
3216    /// is `Copy`, so the accessor returns by value; no borrow of
3217    /// `&self` past the call). `None` when the slot is absent (the
3218    /// "cluster default applies — typically the gateway class's
3219    /// implementation-side per-request wall-clock cap" arm caixa-mesh's
3220    /// `timeout_overlay` builder documents at caixa-mesh/src/lib.rs:2911
3221    /// — [`MeshPolicy::is_empty`]'s `timeout.is_none()` arm reads this
3222    /// predicate too, so an authored-but-unset `:politicas (:timeout ())`
3223    /// round-trips to a rendered `HTTPRoute` structurally identical to
3224    /// one that omits the slot).
3225    ///
3226    /// The `:politicas :timeout` slot carries the "no infinite blocking"
3227    /// per-call deadline contract (MESH-COMPOSITION §V CSE invariant) —
3228    /// the typed slot's `Option<Duration>` accept-set (zero-floor
3229    /// rejected through [`AplicacaoError::PolicyTimeoutZero`], canonical-
3230    /// form rejected through [`AplicacaoError::PolicyTimeoutNotCanonical`],
3231    /// upper-bounded by [`POLICY_TIMEOUT_MAX`]) maps onto the Gateway API
3232    /// v1.x `HTTPRoute.spec.rules[].timeouts.request` per-rule request-
3233    /// deadline scalar the caixa-mesh `timeout_overlay` builder writes.
3234    /// Every downstream consumer that reads the per-call cap keys off
3235    /// this scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
3236    /// renderers key off to decide "emit :politicas overlay" vs "skip
3237    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
3238    /// `timeouts.request` builder at caixa-mesh/src/lib.rs:2979 that
3239    /// fans the deadline into every rule via
3240    /// [`crate::render::single_field_overlay`], the future M4 per-
3241    /// Aplicacao Gateway API reconciler materialization pass, the
3242    /// future per-`:contratos`-edge timeout-override overlay the
3243    /// MESH-COMPOSITION §III.2 roadmap acknowledges).
3244    ///
3245    /// Prior to this lift the `.timeout` field was accessed inline at
3246    /// two sites — [`MeshPolicy::is_empty`]'s `self.timeout.is_none()`
3247    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.timeout,
3248    /// …)` call — two open-coded field-accesses that expressed no
3249    /// compile-time link back to the typed slot. A future extension of
3250    /// the `:politicas :timeout` axis to a richer author surface — a
3251    /// per-`:contratos`-edge timeout override the operator pins through
3252    /// a future `:contratos :timeout` slot the MESH-COMPOSITION §III.2
3253    /// roadmap acknowledges, a per-cluster timeout-default overlay the
3254    /// M4 CR materializer resolves per-CR, a split of the single
3255    /// per-call `Duration` into a richer `{request, backendRequest}`
3256    /// pair once the Gateway API's per-rule `timeouts` block grows the
3257    /// upstream-facing backendRequest arm alongside the client-facing
3258    /// request arm — would have had to be threaded through both open-
3259    /// coded copies in lockstep or the emptiness predicate and the
3260    /// caixa-mesh emit path would silently disagree on which per-call
3261    /// deadline a given [`MeshPolicy`] resolves to (a `:politicas` block
3262    /// whose only axis is a `Some :timeout` would satisfy `is_empty()
3263    /// == false` while the renderer's overlay-emit path silently read
3264    /// a drifted other value, or vice versa: an author's `:timeout
3265    /// "30s"` would omit the `HTTPRoute` `timeouts.request` block while
3266    /// the emptiness predicate still classified the policy as non-
3267    /// empty, and every `kubectl -n tatara-system get httproute -o yaml
3268    /// | grep -A2 timeouts` audit would land on a route whose author's
3269    /// typed slot value silently vanished at the renderer layer).
3270    /// Lifting the resolution to a typed method on the substrate
3271    /// primitive means every downstream consumer of the Aplicacao's
3272    /// per-`:politicas` deadline surface reaches for exactly one typed
3273    /// dispatch — the resolver's accept-set migrates as a unit on any
3274    /// future axis addition.
3275    ///
3276    /// Third `Option<Copy-T>`-return accessor on the M3 mesh-slot
3277    /// family (sibling of the peer per-`:politicas`
3278    /// [`MeshPolicy::retries`] bdfb399 `Option<u32>` accessor and the
3279    /// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1
3280    /// `Option<bool>` accessor — same "one typed dispatch on the
3281    /// substrate primitive, thin projections at each consumer"
3282    /// discipline extended onto the peer per-`:politicas` typed-
3283    /// [`Duration`] optional-scalar axis; closes the "optional per-slot
3284    /// numeric-Copy-T scalar" projection pattern the sibling
3285    /// `Option<u32>` / `Option<bool>` lifts opened, since every
3286    /// remaining `MeshPolicy` axis (`circuit_breaker: Option<CircuitBreaker>`,
3287    /// `rate_limit: Option<RateLimit>`) carries a struct payload rather
3288    /// than a scalar). Named `timeout()` to match the storage field's
3289    /// name; the accessor's identity maps onto the canonical MESH-
3290    /// COMPOSITION §III.2 vocabulary the slot's docstring already carries.
3291    #[must_use]
3292    pub const fn timeout(&self) -> Option<Duration> {
3293        self.timeout
3294    }
3295
3296    /// Substrate-canonical per-`:politicas` `:retries` transient-failure-
3297    /// retry-budget scalar accessor every consumer of the Aplicacao's
3298    /// Gateway API v1.x per-rule retry-cap keys off — returns the
3299    /// author-declared `:politicas :retries` typed `u32` verbatim as an
3300    /// `Option<u32>`, copied out of the typed slot's own `Option<u32>`
3301    /// storage (`Option<u32>` is `Copy`, so the accessor returns by
3302    /// value; no borrow of `&self` past the call). `None` when the slot
3303    /// is absent (the "cluster default applies — typically 'no retries
3304    /// beyond a single dispatch attempt'" arm the caixa-mesh
3305    /// `retry_overlay` builder documents at caixa-mesh/src/lib.rs:2985
3306    /// — [`MeshPolicy::is_empty`]'s `retries.is_none()` arm reads
3307    /// this predicate too, so an authored-but-unset `:politicas
3308    /// (:retries ())` round-trips to a rendered `HTTPRoute` structurally
3309    /// identical to one that omits the slot).
3310    ///
3311    /// The `:politicas :retries` slot carries the "transient failure
3312    /// retry cap" contract (MESH-COMPOSITION §III.2 #2) — the typed
3313    /// slot's `Option<u32>` accept-set (lower-bounded by 1 through
3314    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
3315    /// [`POLICY_RETRIES_MAX`]) maps onto the Gateway API v1.x
3316    /// `HTTPRoute.spec.rules[].retry.attempts` per-rule retry-attempt-
3317    /// count scalar the caixa-mesh `retry_overlay` builder writes.
3318    /// Every downstream consumer that reads the retry cap keys off this
3319    /// scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
3320    /// renderers key off to decide "emit :politicas overlay" vs "skip
3321    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
3322    /// `retry.attempts` builder at caixa-mesh/src/lib.rs:3007 that fans
3323    /// the value into every rule via [`crate::render::single_field_overlay`],
3324    /// the future M4 per-Aplicacao Gateway API reconciler
3325    /// materialization pass, the future per-`:contratos`-edge retry-
3326    /// override overlay the MESH-COMPOSITION §III.2 #2 roadmap
3327    /// acknowledges).
3328    ///
3329    /// Prior to this lift the `.retries` field was accessed inline at
3330    /// two sites — [`MeshPolicy::is_empty`]'s `self.retries.is_none()`
3331    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.retries,
3332    /// …)` call — two open-coded field-accesses that expressed no
3333    /// compile-time link back to the typed slot. A future extension of
3334    /// the `:politicas :retries` axis to a richer author surface — a
3335    /// per-`:contratos`-edge retry override the operator pins through a
3336    /// future `:contratos :retries` slot, a per-cluster retry-default
3337    /// overlay the M4 CR materializer resolves per-CR, a promotion of
3338    /// the plain `u32` attempt-count to a richer `{attempts, codes,
3339    /// backoff}` sub-block once the Gateway API grows the peer
3340    /// `retry.codes` / `retry.backoff` axes — would have had to be
3341    /// threaded through both open-coded copies in lockstep or the
3342    /// emptiness predicate and the caixa-mesh emit path would silently
3343    /// disagree on which retry budget a given [`MeshPolicy`] resolves to
3344    /// (a `:politicas` block whose only axis is a `Some :retries` would
3345    /// satisfy `is_empty() == false` while the renderer's overlay-emit
3346    /// path silently read a drifted other value, or vice versa: an
3347    /// author's `:retries 3` would omit the `HTTPRoute` `retry.attempts`
3348    /// block while the emptiness predicate still classified the policy
3349    /// as non-empty). Lifting the resolution to a typed method on the
3350    /// substrate primitive means every downstream consumer of the
3351    /// Aplicacao's per-`:politicas` retry surface reaches for exactly
3352    /// one typed dispatch — the resolver's accept-set migrates as a
3353    /// unit on any future axis addition.
3354    ///
3355    /// Second `Option<Copy-T>`-return accessor on the M3 mesh-slot
3356    /// family (sibling of the peer per-`:politicas`
3357    /// [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` accessor —
3358    /// same "one typed dispatch on the substrate primitive, thin
3359    /// projections at each consumer" discipline extended onto the
3360    /// peer per-`:politicas` typed-`u32` optional-scalar axis; opens
3361    /// the "optional per-slot numeric-Copy-T scalar" projection pattern
3362    /// the sibling per-`:politicas` `:timeout` (Option<Duration>) /
3363    /// per-`CircuitBreaker` `:max-failures` / `:window` future lifts
3364    /// fold on). Named `retries()` to match the storage field's name;
3365    /// the accessor's identity maps onto the canonical MESH-COMPOSITION
3366    /// §III.2 vocabulary the slot's docstring already carries.
3367    #[must_use]
3368    pub const fn retries(&self) -> Option<u32> {
3369        self.retries
3370    }
3371
3372    /// Substrate-canonical per-`:politicas` `:mtls-required` mTLS-
3373    /// enforcement-toggle scalar accessor every consumer of the
3374    /// Aplicacao's Cilium-mesh L4 mutual-authentication policy keys off
3375    /// — returns the author-declared `:politicas :mtls-required` typed
3376    /// bool verbatim as an `Option<bool>`, copied out of the typed
3377    /// slot's own `Option<bool>` storage (`Option<bool>` is `Copy`, so
3378    /// the accessor returns by value; no borrow of `&self` past the
3379    /// call). `None` when the slot is absent (the "cluster default
3380    /// applies — typically 'disabled' cluster-wide" arm the caixa-mesh
3381    /// `mtls_overlay` builder documents at caixa-mesh/src/lib.rs:2540
3382    /// — [`MeshPolicy::is_empty`]'s `mtls_required.is_none()` arm reads
3383    /// this predicate too, so an authored-but-unset `:politicas
3384    /// (:mtls-required ())` round-trips to a rendered
3385    /// `CiliumNetworkPolicy` structurally identical to one that omits
3386    /// the slot).
3387    ///
3388    /// The `:politicas :mtls-required` slot carries the "explicit opt-
3389    /// out only, sandboxing-by-default" mTLS-enforcement toggle
3390    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's three-way
3391    /// `{None, Some(true), Some(false)}` accept-set maps onto the
3392    /// Cilium `authentication.mode` bijection through
3393    /// [`crate::cilium_auth_mode`]: `Some(true) → "required"` (mTLS
3394    /// handshake enforced), `Some(false) → "disabled"` (handshake
3395    /// skipped — the debug-edge opt-out), `None` → omit the block
3396    /// (cluster default applies). Every downstream consumer that
3397    /// reads the toggle keys off this scalar (the
3398    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
3399    /// off to decide "emit :politicas overlay" vs "skip entirely", the
3400    /// caixa-mesh per-`(:de, :para)` CNP `mtls_overlay` builder at
3401    /// caixa-mesh/src/lib.rs:2549 that fans the toggle into every
3402    /// ingress rule via [`crate::render::single_field_overlay`], the
3403    /// future M4 per-Aplicacao Cilium `authentication.mode` reconciler
3404    /// materialization pass, the future per-`:contratos`-edge mTLS
3405    /// override MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3406    ///
3407    /// Prior to this lift the `.mtls_required` field was accessed
3408    /// inline at two sites — [`MeshPolicy::is_empty`]'s
3409    /// `self.mtls_required.is_none()` arm and caixa-mesh's
3410    /// `single_field_overlay(spec.politicas.mtls_required, …)` call —
3411    /// two open-coded field-accesses that expressed no compile-time
3412    /// link back to the typed slot. A future extension of the
3413    /// `:politicas :mtls-required` axis to a richer author surface —
3414    /// a per-`:contratos`-edge mTLS override the operator pins through
3415    /// a future `:contratos :mtls` slot the MESH-COMPOSITION §III.2
3416    /// #3 roadmap acknowledges, a per-cluster mTLS-default overlay the
3417    /// M4 CR materializer resolves per-CR, a three-valued
3418    /// `{None, Some(true), Some(false), Some(Optional)}` promotion
3419    /// once Cilium's `authentication.mode` grows an `"optional"` arm —
3420    /// would have had to be threaded through both open-coded copies in
3421    /// lockstep or the emptiness predicate and the caixa-mesh emit
3422    /// path would silently disagree on which toggle a given
3423    /// [`MeshPolicy`] resolves to (a `:politicas` block whose only
3424    /// axis is a `Some`
3425    /// `:mtls-required` would satisfy `is_empty() == false` while the
3426    /// renderer's overlay-emit path silently read a drifted other
3427    /// value, or vice versa). Lifting the resolution to a typed method
3428    /// on the substrate primitive means every downstream consumer of
3429    /// the Aplicacao's per-`:politicas` mTLS-toggle surface reaches
3430    /// for exactly one typed dispatch — the resolver's accept-set
3431    /// migrates as a unit on any future axis addition.
3432    ///
3433    /// First `Option<Copy-T>`-return accessor on the M3 mesh-slot
3434    /// family (peer of the sibling per-`:placement`
3435    /// [`Placement::shard_key`] 7cd2a28 `Option<&str>` accessor —
3436    /// same "one typed dispatch on the substrate primitive, thin
3437    /// projections at each consumer" discipline extended onto the
3438    /// peer per-`:politicas` typed-bool optional-scalar axis; opens
3439    /// the "optional per-slot Copy-T scalar" projection pattern the
3440    /// sibling per-`:politicas` `:retries` (Option<u32>) /
3441    /// `:timeout` (Option<Duration>) future lifts fold on). Named
3442    /// `mtls_required()` to match the storage field's name; the
3443    /// accessor's identity maps onto the canonical MESH-COMPOSITION
3444    /// §III.2 vocabulary the slot's docstring already carries.
3445    #[must_use]
3446    pub const fn mtls_required(&self) -> Option<bool> {
3447        self.mtls_required
3448    }
3449
3450    /// Substrate-canonical per-`:politicas` `:rate-limit` Envoy-
3451    /// `local_rate_limit`-mesh token-bucket-declaration scalar
3452    /// accessor every consumer of the Aplicacao's per-`:politicas`
3453    /// per-`(rate, window)` rate-limit surface keys off — returns the
3454    /// author-declared `:politicas :rate-limit` typed [`RateLimit`]
3455    /// verbatim as an `Option<RateLimit>`, copied out of the typed
3456    /// slot's own `Option<RateLimit>` storage ([`RateLimit`] is
3457    /// `Copy`, so the accessor returns by value; no borrow of `&self`
3458    /// past the call). `None` when the slot is absent (the "cluster
3459    /// default applies — typically 'no per-Aplicacao rate declaration,
3460    /// gateway-class per-listener default applies'" arm the future
3461    /// caixa-mesh `local_rate_limit_overlay` emitter MESH-COMPOSITION
3462    /// §III.2 #3 names — [`MeshPolicy::is_empty`]'s
3463    /// `rate_limit().is_none()` arm reads this predicate too, so an
3464    /// authored-but-unset `:politicas (:rate-limit ())` round-trips
3465    /// to a rendered `CiliumClusterwideEnvoyConfig` structurally
3466    /// identical to one that omits the slot).
3467    ///
3468    /// The `:politicas :rate-limit` slot carries the "per-Aplicacao
3469    /// token-bucket rate declaration" contract (MESH-COMPOSITION
3470    /// §III.2 #3) — the typed slot's `Option<RateLimit>` accept-set
3471    /// (rate lower-bounded by 1 through
3472    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
3473    /// [`POLICY_RATE_LIMIT_MAX`], window canonically bijected to the
3474    /// three-unit `{"s", "m", "h"}` [`rate_limit_codec`] table through
3475    /// [`is_canonical_rate_limit_window`]) maps onto the Envoy
3476    /// `local_rate_limit.token_bucket.{max_tokens, fill_interval}`
3477    /// bijection the future `CiliumClusterwideEnvoyConfig` per-
3478    /// `:politicas` overlay emits. Every downstream consumer that
3479    /// reads the rate declaration keys off this scalar (the
3480    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
3481    /// off to decide "emit :politicas overlay" vs "skip entirely", the
3482    /// [`AplicacaoSpec::validate_politicas`] per-value-shape gate that
3483    /// brackets `rl.rate` against [`POLICY_RATE_LIMIT_MAX`] and pins
3484    /// `rl.window` against [`is_canonical_rate_limit_window`], the
3485    /// future M4 per-Aplicacao Envoy reconciler materialization pass,
3486    /// the future per-`:contratos`-edge rate-limit override the
3487    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3488    ///
3489    /// Prior to this lift the `.rate_limit` field was accessed inline
3490    /// at two sites — [`MeshPolicy::is_empty`]'s
3491    /// `self.rate_limit.is_none()` arm and the `validate_politicas`
3492    /// gate's `if let Some(rl) = &p.rate_limit` bind — two open-coded
3493    /// field-accesses that expressed no compile-time link back to the
3494    /// typed slot. A future extension of the `:politicas :rate-limit`
3495    /// axis to a richer author surface — a per-`:contratos`-edge
3496    /// rate-limit override the operator pins through a future
3497    /// `:contratos :rate-limit` slot the MESH-COMPOSITION §III.2 #3
3498    /// roadmap acknowledges, a per-cluster rate-limit-default overlay
3499    /// the M4 CR materializer resolves per-CR, a promotion of the
3500    /// plain `(rate, window)` scalar pair to a richer
3501    /// `{rate, window, burst, key}` sub-block once Envoy's
3502    /// `local_rate_limit` grows the peer `burst_size` /
3503    /// `descriptor_key` axes — would have had to be threaded through
3504    /// both open-coded copies in lockstep or the emptiness predicate
3505    /// and the validate gate would silently disagree on which rate
3506    /// declaration a given [`MeshPolicy`] resolves to (a `:politicas`
3507    /// block whose only axis is a `Some :rate-limit` would satisfy
3508    /// `is_empty() == false` while the validate path silently read a
3509    /// drifted other value, or vice versa: an author's
3510    /// `:rate-limit "100/s"` would omit the value-shape gate while the
3511    /// emptiness predicate still classified the policy as non-empty).
3512    /// Lifting the resolution to a typed method on the substrate
3513    /// primitive means every downstream consumer of the Aplicacao's
3514    /// per-`:politicas` rate-limit surface reaches for exactly one
3515    /// typed dispatch — the resolver's accept-set migrates as a unit
3516    /// on any future axis addition.
3517    ///
3518    /// First `Option<Copy-composite-T>`-return accessor on the M3
3519    /// mesh-slot family — closes the last un-lifted per-`:politicas`
3520    /// scalar-value axis. Peer of the sibling per-`:politicas`
3521    /// [`MeshPolicy::timeout`] (7073d0f) / [`MeshPolicy::retries`]
3522    /// (bdfb399) / [`MeshPolicy::mtls_required`] (c0110f1)
3523    /// `Option<Copy-T>` accessors on the primitive-Copy axes — same
3524    /// "one typed dispatch on the substrate primitive, thin
3525    /// projections at each consumer" discipline extended onto the
3526    /// peer per-`:politicas` composite-Copy shape (`RateLimit` is
3527    /// `#[derive(Copy)]`; peer of [`CircuitBreaker`] which lives
3528    /// behind [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
3529    /// sub-accessors rather than a top-level accessor because
3530    /// consumers reach for the axes not the aggregate). Named
3531    /// `rate_limit()` to match the storage field's name; the
3532    /// accessor's identity maps onto the canonical MESH-COMPOSITION
3533    /// §III.2 vocabulary the slot's docstring already carries.
3534    #[must_use]
3535    pub const fn rate_limit(&self) -> Option<RateLimit> {
3536        self.rate_limit
3537    }
3538
3539    /// Substrate-canonical per-`:politicas` `:circuit-breaker`
3540    /// Envoy-`outlier_detection`-mesh consecutive-failure-ejection-
3541    /// declaration scalar accessor every consumer of the Aplicacao's
3542    /// per-`:politicas` breaker declaration keys off — returns the
3543    /// author-declared `:politicas :circuit-breaker` typed
3544    /// [`CircuitBreaker`] verbatim as an `Option<CircuitBreaker>`,
3545    /// copied out of the typed slot's own `Option<CircuitBreaker>`
3546    /// storage ([`CircuitBreaker`] is `Copy`, so the accessor returns
3547    /// by value; no borrow of `&self` past the call). `None` when the
3548    /// slot is absent (the "cluster default applies — typically 'no
3549    /// per-Aplicacao breaker declaration, gateway-class per-listener
3550    /// default applies'" arm the future caixa-mesh
3551    /// `outlier_detection_overlay` emitter MESH-COMPOSITION §III.2 #3
3552    /// names — [`MeshPolicy::is_empty`]'s `circuit_breaker().is_none()`
3553    /// arm reads this predicate too, so an authored-but-unset
3554    /// `:politicas (:circuit-breaker ())` round-trips to a rendered
3555    /// `CiliumClusterwideEnvoyConfig` structurally identical to one
3556    /// that omits the slot).
3557    ///
3558    /// The `:politicas :circuit-breaker` slot carries the
3559    /// "per-Aplicacao consecutive-transient-failure trip declaration"
3560    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
3561    /// `Option<CircuitBreaker>` accept-set (per-`:max-failures`
3562    /// zero-floor rejected through
3563    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
3564    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]; per-`:window` zero-floor
3565    /// rejected through [`AplicacaoError::PolicyBreakerZeroWindow`],
3566    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`],
3567    /// canonical-form pinned through
3568    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`]) maps onto
3569    /// the Envoy `outlier_detection.{consecutive_5xx, interval}`
3570    /// bijection the future `CiliumClusterwideEnvoyConfig`
3571    /// per-`:politicas` overlay emits. Every downstream consumer that
3572    /// reads the breaker declaration keys off this scalar (the
3573    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
3574    /// off to decide "emit :politicas overlay" vs "skip entirely", the
3575    /// [`AplicacaoSpec::validate_politicas`] per-sub-struct-axis gate
3576    /// that brackets `cb.max_failures()` against
3577    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`] and `cb.window()` against
3578    /// [`POLICY_BREAKER_WINDOW_MAX`] via
3579    /// [`crate::render::require_positive_canonical_bounded_duration`],
3580    /// the future M4 per-Aplicacao Envoy reconciler materialization
3581    /// pass, the future per-`:contratos`-edge breaker override the
3582    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3583    ///
3584    /// Prior to this lift the `.circuit_breaker` field was accessed
3585    /// inline at two sites — [`MeshPolicy::is_empty`]'s
3586    /// `self.circuit_breaker.is_none()` arm and the
3587    /// `validate_politicas` gate's `if let Some(cb) = &p.circuit_breaker`
3588    /// bind — two open-coded field-accesses that expressed no
3589    /// compile-time link back to the typed slot. A future extension of
3590    /// the `:politicas :circuit-breaker` axis to a richer author
3591    /// surface — a per-`:contratos`-edge breaker override the operator
3592    /// pins through a future `:contratos :circuit-breaker` slot the
3593    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-cluster
3594    /// breaker-default overlay the M4 CR materializer resolves per-CR,
3595    /// a promotion of the plain `(max_failures, window)` scalar pair to
3596    /// a richer `{max_failures, window, base_ejection_time, max_ejection_percent}`
3597    /// sub-block once Envoy's `outlier_detection` grows the peer
3598    /// ejection-percentage / ejection-time axes — would have had to be
3599    /// threaded through both open-coded copies in lockstep or the
3600    /// emptiness predicate and the validate gate would silently
3601    /// disagree on which breaker declaration a given [`MeshPolicy`]
3602    /// resolves to (a `:politicas` block whose only axis is a
3603    /// `Some :circuit-breaker` would satisfy `is_empty() == false` while
3604    /// the validate path silently read a drifted other value, or vice
3605    /// versa: an author's `(:circuit-breaker (:max-failures 5 :window
3606    /// "60s"))` would omit the value-shape gate while the emptiness
3607    /// predicate still classified the policy as non-empty). Lifting
3608    /// the resolution to a typed method on the substrate primitive
3609    /// means every downstream consumer of the Aplicacao's
3610    /// per-`:politicas` breaker surface reaches for exactly one typed
3611    /// dispatch — the resolver's accept-set migrates as a unit on any
3612    /// future axis addition.
3613    ///
3614    /// Second `Option<Copy-composite-T>`-return accessor on the M3
3615    /// mesh-slot family (sibling of the peer per-`:politicas`
3616    /// [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>` accessor
3617    /// on the same composite-Copy shape, and of the sibling per-
3618    /// `:politicas` [`MeshPolicy::timeout`] 7073d0f
3619    /// `Option<Duration>` / [`MeshPolicy::retries`] bdfb399
3620    /// `Option<u32>` / [`MeshPolicy::mtls_required`] c0110f1
3621    /// `Option<bool>` accessors on the sibling primitive-Copy axes —
3622    /// same "one typed dispatch on the substrate primitive, thin
3623    /// projections at each consumer" discipline extended onto the last
3624    /// unlifted per-`:politicas` scalar-value axis (the composite-Copy
3625    /// `Option<CircuitBreaker>` arm). Named `circuit_breaker()` to
3626    /// match the storage field's name; the accessor's identity maps
3627    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3628    /// docstring already carries. Closes the last unlifted
3629    /// [`MeshPolicy`] accessor axis so every downstream per-`:politicas`
3630    /// reader now routes through a typed dispatch on the substrate
3631    /// primitive.
3632    #[must_use]
3633    pub const fn circuit_breaker(&self) -> Option<CircuitBreaker> {
3634        self.circuit_breaker
3635    }
3636}
3637
3638#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
3639#[serde(rename_all = "camelCase")]
3640pub struct CircuitBreaker {
3641    pub max_failures: u32,
3642    #[serde(with = "supervisor::duration_codec_required")]
3643    pub window: Duration,
3644}
3645
3646impl CircuitBreaker {
3647    /// Substrate-canonical per-`:politicas :circuit-breaker`
3648    /// `:max-failures` Envoy-outlier-detection trip-threshold scalar
3649    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3650    /// breaker trip-count keys off — returns the author-declared
3651    /// `:politicas :circuit-breaker :max-failures` typed `u32` verbatim,
3652    /// copied out of the typed slot's own `u32` storage (`u32` is `Copy`,
3653    /// so the accessor returns by value; no borrow of `&self` past the
3654    /// call). Non-optional (the surrounding `Option<CircuitBreaker>` is
3655    /// the "slot present?" projection at the parent [`MeshPolicy::circuit_breaker`]
3656    /// axis; a `CircuitBreaker` past pattern-match is definitionally
3657    /// present, and its `:max-failures` field carries the trip count as a
3658    /// required-axis scalar).
3659    ///
3660    /// The `:politicas :circuit-breaker :max-failures` axis carries the
3661    /// "consecutive-transient-failure trip threshold" contract
3662    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's `u32` accept-set
3663    /// (zero-floor rejected through
3664    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
3665    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]) maps onto the Envoy
3666    /// `outlier_detection.consecutive_5xx` per-cluster ejection-threshold
3667    /// scalar (equivalently the future `CiliumClusterwideEnvoyConfig`
3668    /// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 acknowledges).
3669    /// Every downstream consumer that reads the trip threshold keys off
3670    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3671    /// cap bracket at caixa-core/src/aplicacao.rs:4022 that gates on the
3672    /// canonical `require_positive_bounded_u32` helper, the future M4
3673    /// per-Aplicacao Envoy config reconciler materialization pass, the
3674    /// future per-`:contratos`-edge breaker-override overlay the
3675    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3676    ///
3677    /// Prior to this lift the `.max_failures` field was accessed inline
3678    /// at one production site — [`AplicacaoSpec::validate_politicas`]'s
3679    /// `require_positive_bounded_u32(cb.max_failures, …)` call — one
3680    /// open-coded field-access that expressed no compile-time link back
3681    /// to the typed sub-struct axis. A future extension of the
3682    /// `:max-failures` axis to a richer author surface — a
3683    /// per-`:contratos`-edge breaker override the operator pins through a
3684    /// future `:contratos :max-failures` slot the MESH-COMPOSITION §III.2
3685    /// #3 roadmap acknowledges, a per-cluster max-failures-default
3686    /// overlay the M4 CR materializer resolves per-CR, a promotion of the
3687    /// plain `u32` trip count to a richer
3688    /// `{consecutive_5xx, consecutive_gateway_failure, consecutive_local_origin_failure}`
3689    /// tuple once Envoy's `outlier_detection` block's peer axes come into
3690    /// scope, a per-Envoy-cluster minimum-request-volume gate before the
3691    /// count arms — would have had to be threaded through every open-
3692    /// coded copy in lockstep or the validate gate and the future M4
3693    /// emit path would silently disagree on which trip threshold a given
3694    /// [`CircuitBreaker`] resolves to (an author's `:max-failures 5`
3695    /// would satisfy validate while the emit path silently read a drifted
3696    /// other value, or vice versa: a validated typed slot would land at
3697    /// the emit boundary as a no-op breaker whose trip threshold is
3698    /// structurally never reached). Lifting the resolution to a typed
3699    /// method on the substrate primitive means every downstream consumer
3700    /// of the Aplicacao's per-`:politicas :circuit-breaker`
3701    /// trip-threshold surface reaches for exactly one typed dispatch —
3702    /// the resolver's accept-set migrates as a unit on any future axis
3703    /// addition.
3704    ///
3705    /// First sub-struct scalar accessor on the M3 mesh-slot family
3706    /// (opens the "per-`CircuitBreaker` / per-`RateLimit` required-axis
3707    /// scalar" projection pattern the sibling `CircuitBreaker::window` /
3708    /// `RateLimit::rate` / `RateLimit::window` future lifts fold on —
3709    /// closes the last unlifted per-`:politicas` scalar-value axis after
3710    /// the c0110f1 / bdfb399 / 7073d0f trajectory closed every scalar-
3711    /// shaped axis on the parent [`MeshPolicy`] optional-slot surface).
3712    /// Same "one typed dispatch on the substrate primitive, thin
3713    /// projections at each consumer" discipline the peer
3714    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
3715    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
3716    /// [`Membro::versao_requirement`] (a40b0e3),
3717    /// [`Entrada::destination`] (6db982c) accessors carry on their
3718    /// respective per-mesh-slot-atom scalar-value axes, extended onto the
3719    /// per-sub-struct required-`u32` axis. Named `max_failures()` to
3720    /// match the storage field's name; the accessor's identity maps onto
3721    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3722    /// docstring already carries.
3723    #[must_use]
3724    pub const fn max_failures(&self) -> u32 {
3725        self.max_failures
3726    }
3727
3728    /// Substrate-canonical per-`:politicas :circuit-breaker` `:window`
3729    /// Envoy-outlier-detection rolling-observation-interval scalar
3730    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3731    /// breaker rolling-window duration keys off — returns the
3732    /// author-declared `:politicas :circuit-breaker :window` typed
3733    /// `Duration` verbatim, copied out of the typed slot's own
3734    /// `Duration` storage (`Duration` is `Copy`, so the accessor returns
3735    /// by value; no borrow of `&self` past the call). Non-optional (the
3736    /// surrounding `Option<CircuitBreaker>` is the "slot present?"
3737    /// projection at the parent [`MeshPolicy::circuit_breaker`] axis; a
3738    /// `CircuitBreaker` past pattern-match is definitionally present,
3739    /// and its `:window` field carries the rolling-observation interval
3740    /// as a required-axis scalar).
3741    ///
3742    /// The `:politicas :circuit-breaker :window` axis carries the
3743    /// "consecutive-transient-failure rolling-observation interval"
3744    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
3745    /// `Duration` accept-set (zero-floor rejected through
3746    /// [`AplicacaoError::PolicyBreakerZeroWindow`], sub-millisecond
3747    /// residue rejected through
3748    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`],
3749    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`]) maps onto the
3750    /// Envoy `outlier_detection.interval` per-cluster
3751    /// ejection-observation-interval scalar (equivalently the future
3752    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3753    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3754    /// consumer that reads the rolling-observation interval keys off
3755    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3756    /// integer-millisecond canonical-form + cap bracket at
3757    /// caixa-core/src/aplicacao.rs:4121 that gates on the canonical
3758    /// [`crate::render::require_positive_canonical_bounded_duration`]
3759    /// helper, the future M4 per-Aplicacao Envoy config reconciler
3760    /// materialization pass, the future per-`:contratos`-edge
3761    /// breaker-override overlay the MESH-COMPOSITION §III.2 #3 roadmap
3762    /// acknowledges).
3763    ///
3764    /// Prior to this lift the `.window` field was accessed inline at
3765    /// one production site — [`AplicacaoSpec::validate_politicas`]'s
3766    /// `require_positive_canonical_bounded_duration(cb.window, …)`
3767    /// call — one open-coded field-access that expressed no compile-
3768    /// time link back to the typed sub-struct axis. A future extension
3769    /// of the `:window` axis to a richer author surface — a
3770    /// per-`:contratos`-edge window override the operator pins through
3771    /// a future `:contratos :window` slot the MESH-COMPOSITION §III.2
3772    /// #3 roadmap acknowledges, a per-cluster window-default overlay
3773    /// the M4 CR materializer resolves per-CR, a promotion of the plain
3774    /// `Duration` observation interval to a richer
3775    /// `{interval, base_ejection_time, max_ejection_percent}` tuple
3776    /// once Envoy's `outlier_detection` block's peer axes come into
3777    /// scope, a per-Envoy-cluster minimum-request-volume gate before
3778    /// the window arms — would have had to be threaded through every
3779    /// open-coded copy in lockstep or the validate gate and the future
3780    /// M4 emit path would silently disagree on which observation
3781    /// interval a given [`CircuitBreaker`] resolves to (an author's
3782    /// `:window "60s"` would satisfy validate while the emit path
3783    /// silently read a drifted other value, or vice versa: a validated
3784    /// typed slot would land at the emit boundary as a breaker whose
3785    /// observation window is structurally so wide that no realistic
3786    /// failure-rate shape can trip it). Lifting the resolution to a
3787    /// typed method on the substrate primitive means every downstream
3788    /// consumer of the Aplicacao's per-`:politicas :circuit-breaker`
3789    /// observation-window surface reaches for exactly one typed
3790    /// dispatch — the resolver's accept-set migrates as a unit on any
3791    /// future axis addition.
3792    ///
3793    /// Second sub-struct scalar accessor on the M3 mesh-slot family —
3794    /// sibling in shape to the just-landed [`CircuitBreaker::max_failures`]
3795    /// (3a74062) required-`u32` accessor on the peer per-`CircuitBreaker`
3796    /// required-axis, extended onto the per-sub-struct required-`Duration`
3797    /// axis; closes the last unlifted per-`CircuitBreaker` scalar-value
3798    /// axis. Same "one typed dispatch on the substrate primitive, thin
3799    /// projections at each consumer" discipline the peer
3800    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
3801    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
3802    /// [`Membro::versao_requirement`] (a40b0e3),
3803    /// [`Entrada::destination`] (6db982c) accessors carry on their
3804    /// respective per-mesh-slot-atom scalar-value axes, extended onto
3805    /// the per-sub-struct required-`Duration` axis. Named `window()` to
3806    /// match the storage field's name; the accessor's identity maps onto
3807    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3808    /// docstring already carries.
3809    #[must_use]
3810    pub const fn window(&self) -> Duration {
3811        self.window
3812    }
3813}
3814
3815#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3816pub struct RateLimit {
3817    /// Requests per window.
3818    pub rate: u32,
3819    /// Window duration.
3820    pub window: Duration,
3821}
3822
3823impl RateLimit {
3824    /// Substrate-canonical per-`:politicas :rate-limit` `:rate`
3825    /// Envoy-local-rate-limit-mesh token-bucket capacity scalar accessor
3826    /// every consumer of the Aplicacao's per-`:contratos`-edge
3827    /// rate-limit-bucket capacity keys off — returns the author-declared
3828    /// `:politicas :rate-limit` typed `u32` verbatim, copied out of the
3829    /// typed slot's own `u32` storage (`u32` is `Copy`, so the accessor
3830    /// returns by value; no borrow of `&self` past the call). Non-optional
3831    /// (the surrounding `Option<RateLimit>` is the "slot present?"
3832    /// projection at the parent [`MeshPolicy::rate_limit`] axis; a
3833    /// `RateLimit` past pattern-match is definitionally present, and its
3834    /// `:rate` field carries the token-bucket capacity as a required-axis
3835    /// scalar).
3836    ///
3837    /// The `:politicas :rate-limit` `:rate` axis carries the
3838    /// "token-bucket capacity" contract (MESH-COMPOSITION §III.2 #3) —
3839    /// the typed slot's `u32` accept-set (zero-floor rejected through
3840    /// [`AplicacaoError::PolicyRateLimitZero`], upper-bounded by
3841    /// [`POLICY_RATE_LIMIT_MAX`]) maps onto the Envoy
3842    /// `local_rate_limit.token_bucket.max_tokens` per-cluster
3843    /// token-bucket-capacity scalar (equivalently the future
3844    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3845    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3846    /// consumer that reads the token-bucket capacity keys off this
3847    /// scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3848    /// cap bracket that gates on the canonical
3849    /// [`crate::render::require_positive_bounded_u32`] helper, the
3850    /// [`rate_limit_codec::render`] `Duration → unit` projection that
3851    /// emits the `<n>/<s|m|h>` author surface, the future M4
3852    /// per-Aplicacao Envoy config reconciler materialization pass, the
3853    /// future per-`:contratos`-edge rate-limit-override overlay the
3854    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3855    ///
3856    /// Prior to this lift the `.rate` field was accessed inline at three
3857    /// production sites — [`AplicacaoSpec::validate_politicas`]'s
3858    /// `require_positive_bounded_u32(rl.rate, …)` call, and the two
3859    /// [`rate_limit_codec::render`] format-arm arms (canonical-window
3860    /// `format!("{}/{unit}", rl.rate)` and non-canonical-window
3861    /// `format!("{}/{}s", rl.rate, …)` fallback). Three open-coded
3862    /// field-accesses that expressed no compile-time link back to the
3863    /// typed sub-struct axis. A future extension of the `:rate` axis
3864    /// to a richer author surface — a per-`:contratos`-edge rate
3865    /// override the operator pins through a future `:contratos :rate`
3866    /// slot the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a
3867    /// per-cluster rate-default overlay the M4 CR materializer resolves
3868    /// per-CR, a promotion of the plain `u32` token capacity to a
3869    /// richer `{max_tokens, tokens_per_fill}` tuple once Envoy's
3870    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
3871    /// axis comes into scope, a per-Envoy-cluster descriptor-key gate
3872    /// before the token arms — would have had to be threaded through
3873    /// every open-coded copy in lockstep or the validate gate, the
3874    /// codec's render path, and the future M4 emit path would silently
3875    /// disagree on which token capacity a given [`RateLimit`] resolves
3876    /// to (an author's `:rate-limit "100/s"` would satisfy validate
3877    /// while the render / emit paths silently read a drifted other
3878    /// value, or vice versa: a validated typed slot would land at the
3879    /// emit boundary as a no-op limiter whose token capacity is
3880    /// structurally so high that no realistic per-edge traffic shape
3881    /// can drain it). Lifting the resolution to a typed method on the
3882    /// substrate primitive means every downstream consumer of the
3883    /// Aplicacao's per-`:politicas :rate-limit` token-capacity surface
3884    /// reaches for exactly one typed dispatch — the resolver's
3885    /// accept-set migrates as a unit on any future axis addition.
3886    ///
3887    /// First sub-struct scalar accessor on the `RateLimit` axis — sibling
3888    /// in shape to the peer per-`CircuitBreaker`
3889    /// [`CircuitBreaker::max_failures`] (3a74062) required-`u32` accessor
3890    /// on the peer per-sub-struct required-axis, extended onto the
3891    /// per-`RateLimit` required-`u32` axis; opens the "per-`RateLimit`
3892    /// required-axis scalar" projection pattern the sibling
3893    /// [`RateLimit::window`] future lift folds on. Same "one typed
3894    /// dispatch on the substrate primitive, thin projections at each
3895    /// consumer" discipline the peer [`WitContract::source`] /
3896    /// [`WitContract::destination`] (7f0fd43), [`WitContract::world_ref`]
3897    /// (0804823), [`Membro::nome`] (4a32abf),
3898    /// [`Membro::versao_requirement`] (a40b0e3),
3899    /// [`Entrada::destination`] (6db982c),
3900    /// [`CircuitBreaker::max_failures`] (3a74062),
3901    /// [`CircuitBreaker::window`] (373957f) accessors carry on their
3902    /// respective per-mesh-slot-atom scalar-value axes. Named `rate()`
3903    /// to match the storage field's name; the accessor's identity maps
3904    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3905    /// docstring already carries.
3906    #[must_use]
3907    pub const fn rate(&self) -> u32 {
3908        self.rate
3909    }
3910
3911    /// Substrate-canonical per-`:politicas :rate-limit` `:window`
3912    /// Envoy-local-rate-limit-mesh token-bucket refill-period scalar
3913    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3914    /// rate-limit-bucket refill period keys off — returns the
3915    /// author-declared `:politicas :rate-limit` typed `Duration`
3916    /// verbatim, copied out of the typed slot's own `Duration` storage
3917    /// (`Duration` is `Copy`, so the accessor returns by value; no
3918    /// borrow of `&self` past the call). Non-optional (the surrounding
3919    /// `Option<RateLimit>` is the "slot present?" projection at the
3920    /// parent [`MeshPolicy::rate_limit`] axis; a `RateLimit` past
3921    /// pattern-match is definitionally present, and its `:window`
3922    /// field carries the token-bucket refill period as a required-axis
3923    /// scalar).
3924    ///
3925    /// The `:politicas :rate-limit` `:window` axis carries the
3926    /// "token-bucket refill period" contract (MESH-COMPOSITION §III.2 #3)
3927    /// — the typed slot's `Duration` accept-set (constrained to the
3928    /// three canonical windows `{1s, 60s, 3600s}` the
3929    /// [`RATE_LIMIT_UNIT_TABLE`] lifts, rejected off-set through
3930    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]) maps
3931    /// onto the Envoy `local_rate_limit.token_bucket.fill_interval`
3932    /// per-cluster token-bucket-refill-period scalar (equivalently the
3933    /// future `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3934    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3935    /// consumer that reads the token-bucket refill period keys off
3936    /// this scalar (the [`AplicacaoSpec::validate_politicas`]
3937    /// canonical-window gate that keys off
3938    /// [`is_canonical_rate_limit_window`], the
3939    /// [`rate_limit_codec::render`] `Duration → unit` projection that
3940    /// emits the `<n>/<s|m|h>` author surface — canonical arm via
3941    /// [`rate_limit_window_unit`] and non-canonical fallback via
3942    /// `.as_secs()`, the future M4 per-Aplicacao Envoy config
3943    /// reconciler materialization pass, the future per-`:contratos`-
3944    /// edge rate-limit-override overlay the MESH-COMPOSITION §III.2 #3
3945    /// roadmap acknowledges).
3946    ///
3947    /// Prior to this lift the `.window` field was accessed inline at
3948    /// three production sites — [`AplicacaoSpec::validate_politicas`]'s
3949    /// `is_canonical_rate_limit_window(rl.window)` shape-gate call
3950    /// plus the sibling [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]
3951    /// error-payload construction on refusal, and the two
3952    /// [`rate_limit_codec::render`] arms
3953    /// (canonical-window `rate_limit_window_unit(rl.window)` dispatch
3954    /// and non-canonical-window `rl.window.as_secs()` fallback). Three
3955    /// open-coded field-accesses that expressed no compile-time link
3956    /// back to the typed sub-struct axis. A future extension of the
3957    /// `:window` axis to a richer author surface — a per-`:contratos`-
3958    /// edge window override the operator pins through a future
3959    /// `:contratos :window` slot the MESH-COMPOSITION §III.2 #3 roadmap
3960    /// acknowledges, a per-cluster window-default overlay the M4 CR
3961    /// materializer resolves per-CR, a promotion of the plain
3962    /// `Duration` refill period to a richer
3963    /// `{fill_interval, tokens_per_fill}` tuple once Envoy's
3964    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
3965    /// axis comes into scope, an addition of a `"d"` day suffix once
3966    /// Envoy's `rate_limit_action` grows daily-bucket support — would
3967    /// have had to be threaded through every open-coded copy in
3968    /// lockstep or the validate gate, the codec's render path, and
3969    /// the future M4 emit path would silently disagree on which
3970    /// refill period a given [`RateLimit`] resolves to (an author's
3971    /// `:rate-limit "100/s"` would satisfy validate while the render
3972    /// / emit paths silently read a drifted other value, or vice
3973    /// versa: a validated typed slot would land at the emit boundary
3974    /// as a limiter whose refill period is structurally so long that
3975    /// no realistic per-edge traffic shape stays inside the token
3976    /// budget). Lifting the resolution to a typed method on the
3977    /// substrate primitive means every downstream consumer of the
3978    /// Aplicacao's per-`:politicas :rate-limit` refill-period surface
3979    /// reaches for exactly one typed dispatch — the resolver's
3980    /// accept-set migrates as a unit on any future axis addition.
3981    ///
3982    /// Second sub-struct scalar accessor on the `RateLimit` axis —
3983    /// sibling in shape to the just-landed [`RateLimit::rate`]
3984    /// (7f81a60) required-`u32` accessor on the peer per-`RateLimit`
3985    /// required-axis, extended onto the per-sub-struct
3986    /// required-`Duration` axis; closes the last unlifted
3987    /// per-`RateLimit` scalar-value axis (the M3 mesh-slot family's
3988    /// per-sub-struct accessor coverage is now complete across both
3989    /// `CircuitBreaker` and `RateLimit`). Same "one typed dispatch on
3990    /// the substrate primitive, thin projections at each consumer"
3991    /// discipline the peer [`CircuitBreaker::max_failures`] (3a74062),
3992    /// [`CircuitBreaker::window`] (373957f), [`RateLimit::rate`]
3993    /// (7f81a60), [`WitContract::source`] / [`WitContract::destination`]
3994    /// (7f0fd43), [`WitContract::world_ref`] (0804823),
3995    /// [`Membro::nome`] (4a32abf),
3996    /// [`Membro::versao_requirement`] (a40b0e3),
3997    /// [`Entrada::destination`] (6db982c) accessors carry on their
3998    /// respective per-mesh-slot-atom scalar-value axes. Named
3999    /// `window()` to match the storage field's name; the accessor's
4000    /// identity maps onto the canonical MESH-COMPOSITION §III.2
4001    /// vocabulary the slot's docstring already carries.
4002    #[must_use]
4003    pub const fn window(&self) -> Duration {
4004        self.window
4005    }
4006
4007    /// Recognize this rate-limit's `:window` as a canonical
4008    /// [`RateLimitUnit`] arm — `Some(RateLimitUnit)` when the window
4009    /// exactly matches one of the three closed-set arm-Durations
4010    /// (`1s` / `60s` / `3600s`), `None` when the window carries a
4011    /// non-canonical magnitude the codec's round-trip would break on
4012    /// (sub-second residue, or a second-magnitude outside the set
4013    /// [`RateLimitUnit::ALL`] enumerates).
4014    ///
4015    /// Every validated [`RateLimit`] past [`AplicacaoSpec::validate_politicas`]
4016    /// returns `Some` here — the validate gate's
4017    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`] arm
4018    /// rejects every window this accessor returns `None` on. Downstream
4019    /// consumers past validate (the codec's [`rate_limit_codec::render`]
4020    /// path, the future M4 per-Aplicacao Envoy config reconciler's
4021    /// materialization pass, the future per-`:contratos`-edge rate-limit-
4022    /// override overlay the MESH-COMPOSITION §III.2 #3 roadmap
4023    /// acknowledges) that read the typed unit off a validated slot can
4024    /// pattern-match on the returned `Some` without re-checking
4025    /// canonicality at the consumer layer — the typed enum surface is
4026    /// the load-bearing carrier of the canonicality invariant.
4027    ///
4028    /// Preferred over the free [`is_canonical_rate_limit_window`]
4029    /// module-private helper at any call site that has the typed
4030    /// [`RateLimit`] in hand (the codec's `render` arm at
4031    /// [`rate_limit_codec::render`], the validate gate's canonical-form
4032    /// arm in [`AplicacaoSpec::validate_politicas`], any future
4033    /// per-`:contratos` edge-override overlay resolver): those consumers
4034    /// reach for the typed enum without going through the
4035    /// `.window()` scalar-projection layer, and get the enum value
4036    /// directly (which the codec's render arm can then format via
4037    /// [`RateLimitUnit::as_suffix`] / [`std::fmt::Display`]). Same
4038    /// "typed sub-struct scalar accessor, one dispatch on the substrate
4039    /// primitive" discipline the sibling [`RateLimit::rate`] and
4040    /// [`RateLimit::window`] accessors carry on the peer per-sub-struct
4041    /// scalar-value axes, extended onto the per-`RateLimit` typed-unit
4042    /// projection axis (the third scalar accessor on the [`RateLimit`]
4043    /// axis, first typed-enum-return projection).
4044    ///
4045    /// `pub const fn` — the typed-`RateLimit`-projection dispatch onto
4046    /// the canonical [`RateLimitUnit`] arm now carries the same
4047    /// `const`-eval-surface posture the sibling `pub const fn`
4048    /// [`Self::rate`] / [`Self::window`] scalar-projection accessors on
4049    /// this typed sub-struct already carry, composing through the
4050    /// peer-lifted `pub const fn` [`RateLimitUnit::from_window`]
4051    /// reverse-resolver in `const` context. Any downstream substrate-
4052    /// side `const`-context consumer of the typed unit (a module-scope
4053    /// `const _:() = assert!(matches!(rl.canonical_unit(), Some(RateLimitUnit::Second)))`
4054    /// invariant pin on a typed fixture, a future M4 admission-webhook
4055    /// `const fn` per-`:politicas :rate-limit :window` canonical-arm
4056    /// resolver over a typed [`RateLimit`], any future `const fn`
4057    /// per-`:contratos`-edge rate-limit-override overlay resolver over
4058    /// the substrate primitive) now reaches the same typed dispatch on
4059    /// the substrate primitive at const-eval time as at runtime.
4060    ///
4061    /// Pinned load-bearing at the substrate-primitive level by
4062    /// [`tests::rate_limit_canonical_unit_accessor_is_const_fn`] (const-
4063    /// eval-surface pin via `const fn` wrapper).
4064    #[must_use]
4065    pub const fn canonical_unit(&self) -> Option<RateLimitUnit> {
4066        RateLimitUnit::from_window(self.window)
4067    }
4068}
4069
4070/// Typed closed-set enum for the three canonical `:politicas :rate-limit`
4071/// `:window` units — `Second` / `Minute` / `Hour` — the `rate_limit_codec`
4072/// round-trips losslessly (`"<n>/s"` / `"<n>/m"` / `"<n>/h"`).
4073///
4074/// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer of
4075/// the `:politicas :rate-limit` unit surface reads from
4076/// ([`rate_limit_codec::parse`]'s `unit → Duration` dispatch,
4077/// [`rate_limit_codec::render`]'s `Duration → unit` projection, the
4078/// [`is_canonical_rate_limit_window`] predicate the
4079/// [`AplicacaoSpec::validate_politicas`] gate keys off, the future M4
4080/// per-Aplicacao Envoy config reconciler's `local_rate_limit.token_bucket.fill_interval`
4081/// projection) now lives inside this typed enum's `match self` arms — a
4082/// future rate-limit-unit addition (a `"d"` day suffix once Envoy's
4083/// `rate_limit_action` grows daily-bucket support) is one new variant
4084/// plus the exhaustiveness arms on the four methods, so every consumer
4085/// picks it up by compile-time construction rather than a runtime
4086/// table-scan miss.
4087///
4088/// The prior `RATE_LIMIT_UNIT_TABLE: &[(&str, u64)]` slice-of-tuples was
4089/// scanned via `find_map` at every projection call — an untyped runtime
4090/// walk that carried no compile-time link between the parse arm's
4091/// accepted suffixes, the render arm's emitted suffixes, and the
4092/// validate gate's accepted windows. A future rate-limit-unit addition
4093/// that landed one row without threading through the other consumers
4094/// (or a copy-paste flip that collapsed two rows onto one suffix) would
4095/// silently split the accepted-set across the three consumers — the
4096/// parse arm accepts `"d"` and rejects `"s"`, the render arm emits `"h"`
4097/// for a 24h window that parse can't round-trip, the validate gate
4098/// misses one canonical window. Lifting the pairs onto a typed
4099/// closed-set enum with exhaustive `match` arms makes any such
4100/// half-landed extension a caixa-core build error (the compiler enforces
4101/// arm coverage on every method), not a silent per-consumer drift
4102/// surfacing at apply time. Same "closed-set typed-enum discriminator"
4103/// discipline the sibling [`PlacementStrategy`] (cc8f749),
4104/// [`crate::supervisor::RestartStrategy`],
4105/// [`crate::supervisor::RestartPolicy`],
4106/// [`crate::upgrade::UpgradeInstruction`], and [`crate::CaixaKind`]
4107/// closed-set typed enums carry on their respective closed-set axes —
4108/// extended onto the seventh closed-set typed-enum discriminator axis
4109/// on the caixa typed surface (the `:politicas :rate-limit :window`
4110/// canonical-unit axis).
4111#[derive(
4112    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
4113)]
4114pub enum RateLimitUnit {
4115    /// 1-second window — canonical author-surface suffix `"s"`
4116    /// (`"<n>/s"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
4117    /// with a 1s magnitude.
4118    Second,
4119    /// 1-minute window — canonical author-surface suffix `"m"`
4120    /// (`"<n>/m"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
4121    /// with a 60s magnitude.
4122    Minute,
4123    /// 1-hour window — canonical author-surface suffix `"h"`
4124    /// (`"<n>/h"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
4125    /// with a 3600s magnitude.
4126    Hour,
4127}
4128
4129impl RateLimitUnit {
4130    /// Exhaustive iteration surface for every consumer that reads the
4131    /// full canonical-unit set (the byte-parity witness against the
4132    /// prior `RATE_LIMIT_UNIT_TABLE` shape, the future M4 admission
4133    /// webhook's accepted-suffix listing in its rejection body, any
4134    /// future round-trip fuzz harness). A future variant addition to
4135    /// [`RateLimitUnit`] extends this slice as a single edit and every
4136    /// consumer picks up the new entry by construction — the compiler-
4137    /// checked exhaustiveness on the sibling method `match` arms is the
4138    /// build-time guarantee that no arm forgets to grow.
4139    pub const ALL: &'static [Self] = &[Self::Second, Self::Minute, Self::Hour];
4140
4141    /// Canonical author-surface suffix — the `"s"` / `"m"` / `"h"` byte-
4142    /// string every `<n>/<unit>` rate-limit shape carries after its
4143    /// `/` separator. The single source of truth the codec's parse and
4144    /// render arms both dispatch on: the parse arm matches an incoming
4145    /// suffix against every [`RateLimitUnit::ALL`] entry's `as_suffix`
4146    /// output; the render arm emits the entry's `as_suffix` verbatim
4147    /// after the rate magnitude.
4148    #[must_use]
4149    pub const fn as_suffix(self) -> &'static str {
4150        match self {
4151            Self::Second => "s",
4152            Self::Minute => "m",
4153            Self::Hour => "h",
4154        }
4155    }
4156
4157    /// Canonical `Duration` for this unit — the token-bucket refill
4158    /// period the [`RateLimit::window`] axis carries when the surrounding
4159    /// slot's `:rate-limit` author surface named this unit.
4160    #[must_use]
4161    pub const fn window(self) -> Duration {
4162        Duration::from_secs(match self {
4163            Self::Second => 1,
4164            Self::Minute => 60,
4165            Self::Hour => 3_600,
4166        })
4167    }
4168
4169    /// Parse the `<n>/<unit>`-shaped suffix into the typed enum, or
4170    /// `None` when `suffix` is outside the closed-set arm-string set
4171    /// [`Self::as_suffix`] emits. The single `str → Self` projection
4172    /// [`rate_limit_codec::parse`] consumes.
4173    #[must_use]
4174    pub fn from_suffix(suffix: &str) -> Option<Self> {
4175        Self::ALL.iter().copied().find(|u| u.as_suffix() == suffix)
4176    }
4177
4178    /// Recognize a canonical rate-limit `Duration` as one of the three
4179    /// arms, or `None` when `window` carries sub-second residue or a
4180    /// second-magnitude outside the closed-set arm-window set
4181    /// [`Self::window`] emits. The single `Duration → Self` projection
4182    /// [`rate_limit_codec::render`] + [`is_canonical_rate_limit_window`]
4183    /// both consume.
4184    ///
4185    /// `pub const fn` — the reverse `Duration → Self` projection now
4186    /// carries the same `const`-eval-surface posture the sibling
4187    /// `pub const fn` [`Self::as_suffix`] / [`Self::window`] scalar-
4188    /// projection accessors on this closed-set typed enum already
4189    /// carry, and the paired `pub const fn` [`RateLimit::canonical_unit`]
4190    /// typed-`RateLimit`-projection sibling composes through in `const`
4191    /// context. Routes byte-for-byte through the peer `pub const fn`
4192    /// [`Self::window`] canonical-`Duration` projection so any future
4193    /// arm-magnitude edit on the sibling accessor reaches this reverse
4194    /// resolver by construction — the `s == Self::<Arm>.window().as_secs()`
4195    /// per-arm probes each dispatch through one `pub const fn` on the
4196    /// substrate primitive rather than a hand-authored per-arm second-
4197    /// magnitude literal that would silently drift on any future
4198    /// [`Self::window`] arm-magnitude edit.
4199    ///
4200    /// Prior to the `const` lift the body dispatched through
4201    /// `Self::ALL.iter().copied().find(|u| u.window() == window)` — an
4202    /// iterator-driven linear scan whose iterator methods
4203    /// (`.iter()` / `.copied()` / `.find()`) and `Duration`-side
4204    /// `PartialEq` dispatch each carry non-`const` bounds on stable
4205    /// Rust 1.94, so any downstream substrate-side `const`-context
4206    /// consumer of the reverse resolver (a module-scope
4207    /// `const _:() = assert!(RateLimitUnit::from_window(<canonical>).is_some())`
4208    /// invariant pin on a typed fixture, a future M4
4209    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
4210    /// webhook `const fn` per-`:politicas` canonical-window floor over a
4211    /// typed [`RateLimit`] scalar, any future `const fn`
4212    /// per-`:contratos`-edge rate-limit-override overlay resolver over
4213    /// the substrate primitive that wants to fan on the canonical unit
4214    /// at compile time) surfaced as a downstream E0015 far from the
4215    /// resolver's own declaration. The `pub const fn` posture closes
4216    /// the drift structurally at caixa-core build time.
4217    ///
4218    /// Pinned load-bearing at the substrate-primitive level by
4219    /// [`tests::rate_limit_unit_from_window_accessor_is_const_fn`] (const-
4220    /// eval-surface pin via `const fn` wrapper) and
4221    /// [`tests::rate_limit_unit_from_window_composes_through_window_accessor`]
4222    /// (composition-witness pin against the peer `Self::window` scalar
4223    /// dispatch).
4224    #[must_use]
4225    pub const fn from_window(window: Duration) -> Option<Self> {
4226        if window.subsec_nanos() != 0 {
4227            return None;
4228        }
4229        // Route through the peer `pub const fn` [`Self::window`]
4230        // canonical-`Duration` projection so any future arm-magnitude
4231        // edit on the sibling accessor reaches this reverse resolver by
4232        // construction — the per-arm `secs` comparison keys off
4233        // `Duration::as_secs` (`pub const fn`), not a hand-authored
4234        // per-arm second-magnitude literal that would silently drift.
4235        let secs = window.as_secs();
4236        if secs == Self::Second.window().as_secs() {
4237            Some(Self::Second)
4238        } else if secs == Self::Minute.window().as_secs() {
4239            Some(Self::Minute)
4240        } else if secs == Self::Hour.window().as_secs() {
4241            Some(Self::Hour)
4242        } else {
4243            None
4244        }
4245    }
4246
4247    /// Canonical rate-limit `Duration` for a unit suffix, or `None` when
4248    /// `suffix` is outside the closed-set arm-string set [`Self::as_suffix`]
4249    /// emits. Composes [`Self::from_suffix`] with [`Self::window`] — the
4250    /// single `&str → Duration` projection [`rate_limit_codec::parse`]
4251    /// consumes.
4252    ///
4253    /// The peer `Duration → &'static str` axis folded onto the substrate
4254    /// primitive [`RateLimit::canonical_unit`] typed accessor once both
4255    /// production consumers ([`rate_limit_codec::render`] and
4256    /// [`AplicacaoSpec::validate_politicas`]'s canonical-window gate)
4257    /// migrated (61421a6): the free helper's `Duration → &str` projection
4258    /// is now the two-step composition
4259    /// `rl.canonical_unit().map(RateLimitUnit::as_suffix)` every consumer
4260    /// reads through the typed accessor. This lift closes the peer
4261    /// `&str → Duration` axis by folding the vestigial module-private
4262    /// `rate_limit_window_from_unit` delegate onto this associated method
4263    /// — the codec's parse arm and every future wire-side consumer of the
4264    /// `&str → Duration` projection (a future admission-webhook that
4265    /// reads a `:rate-limit` shape off a CR spec's `raw string` value
4266    /// before it's promoted to a validated typed slot, a future
4267    /// `feira lint` shape-probe that reads the author-surface bytes
4268    /// verbatim) now reach for exactly one typed dispatch on the
4269    /// substrate primitive.
4270    ///
4271    /// Same "closed-set typed-enum discriminator with canonical
4272    /// projections per axis" discipline the sibling [`Self::as_suffix`]
4273    /// / [`Self::window`] / [`Self::from_suffix`] / [`Self::from_window`]
4274    /// methods carry — this associated method closes the fifth (and last
4275    /// unlifted) projection axis on the arm-table, so the closed-set enum
4276    /// now owns every `str ↔ Duration ↔ Self` typed dispatch every
4277    /// consumer of the `:politicas :rate-limit :window` axis reaches
4278    /// through. A future rate-limit-unit addition (a `"d"` day suffix
4279    /// once Envoy's `rate_limit_action` grows daily-bucket support, a
4280    /// `"ms"` sub-second window once high-throughput per-edge policies
4281    /// come into scope per MESH-COMPOSITION §III.2 #3) is one new
4282    /// variant plus one arm per method — the compiler enforces
4283    /// exhaustiveness on every consumer's `match self` arms and picks
4284    /// the new unit up by construction across all five projections.
4285    #[must_use]
4286    pub fn window_from_suffix(suffix: &str) -> Option<Duration> {
4287        Self::from_suffix(suffix).map(Self::window)
4288    }
4289}
4290
4291/// Route [`std::fmt::Display`] through [`RateLimitUnit::as_suffix`], so
4292/// every consumer that formats a canonical rate-limit unit as user-
4293/// facing text (future M4 admission-webhook rejection bodies naming
4294/// the accepted-suffix set, future `feira app graph` per-`:politicas`
4295/// unit column) lands on the same `"s"` / `"m"` / `"h"` byte-string the
4296/// codec's parse arm accepts and the render arm emits. Same
4297/// as_str-through-Display convergence discipline the sibling
4298/// [`PlacementStrategy`], [`crate::CaixaKind`],
4299/// [`crate::supervisor::RestartStrategy`], and
4300/// [`crate::supervisor::RestartPolicy`] closed-set typed enums carry.
4301impl std::fmt::Display for RateLimitUnit {
4302    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4303        f.write_str(self.as_suffix())
4304    }
4305}
4306
4307/// Upper-bound ceiling on the `:politicas :timeout` axis — every
4308/// validated [`MeshPolicy::timeout`] past
4309/// [`AplicacaoSpec::validate_politicas`] lies in `1ms..=POLICY_TIMEOUT_MAX`
4310/// (inclusive on both ends, integer-millisecond magnitudes by the
4311/// canonical-form gate immediately preceding).
4312///
4313/// The typed field is `Option<Duration>` (the zero-floor arm
4314/// [`AplicacaoError::PolicyTimeoutZero`] already rejects
4315/// `Duration::ZERO`, and the canonical-form arm
4316/// [`AplicacaoError::PolicyTimeoutNotCanonical`] already rejects
4317/// sub-millisecond residue), so a programmatic struct literal
4318/// (`MeshPolicy { timeout: Some(Duration::from_secs(86_400)), .. }` —
4319/// 24h) and the equivalent author-surface form
4320/// (`(:politicas (:timeout "24h"))` — the codec emits `"h"` for any
4321/// integer-hour magnitude) both round-trip cleanly through serde — a
4322/// structurally unbounded `Duration` ceiling. A `:timeout` value far
4323/// above the documented production-playbook band (Envoy default `15s`,
4324/// Istio per-route typical `≤ 30s`, AWS App Mesh `httpRouteTimeout`
4325/// schema typical `≤ 60s`, Linkerd `request_timeout` typical `10s`,
4326/// Kubernetes ingress-nginx `proxy_read_timeout` default `60s` capped
4327/// at `~3600s`) silently degenerates the mesh-policy contract: the
4328/// per-call deadline is structurally so long that no realistic
4329/// synchronous-`:contratos` traversal can reach it, so the typed slot
4330/// becomes a no-op carried on every emitted Envoy / Cilium L7 timeout
4331/// overlay — the MESH-COMPOSITION §V CSE invariant "no infinite
4332/// blocking" degenerates to a nominal-only contract on the
4333/// synchronous-call path. Pairs with the [`POLICY_RETRIES_MAX`] cap on
4334/// the sibling `:politicas :retries` axis and the
4335/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap on the sibling
4336/// `:politicas :circuit-breaker :max-failures` axis — all three close
4337/// the "structurally unbounded ceiling on a typed `:politicas` axis"
4338/// footgun the prior zero-floor-and-canonical-form-only checks left
4339/// open.
4340///
4341/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
4342/// shared duration codec emits (`"<n>h"` for any integer-hour
4343/// magnitude) — every value in the canonical authoring form's
4344/// `<integer><unit>` grammar at or below this cap renders to a clean
4345/// canonical string. The cap sits an order of magnitude above every
4346/// documented production-playbook recommendation band (Envoy default
4347/// `15s`, Istio production `≤ 30s`, Linkerd production `≤ 10s`, AWS
4348/// App Mesh production `≤ 60s`) and at the Kubernetes ingress-nginx
4349/// configured maximum (`proxy_read_timeout` typical max `3600s`),
4350/// below the clearly-pathological "effectively no timeout" floor
4351/// (`24h`, `7d`, `Duration::MAX`): a value the author can plausibly
4352/// want for a long-running synchronous workflow, but a hard wall above
4353/// which the mesh-level deadline is structurally a non-deadline.
4354/// Lifted as a typed `pub const` so the bound has exactly one source
4355/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4356/// materializer's admission webhook and the caixa-mesh-side
4357/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
4358/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
4359/// other typed upper bound in this crate carries
4360/// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
4361/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4362/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4363/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4364pub const POLICY_TIMEOUT_MAX: Duration = Duration::from_secs(3600);
4365
4366/// Upper-bound ceiling on the `:politicas :retries` axis — every
4367/// validated [`MeshPolicy::retries`] past
4368/// [`AplicacaoSpec::validate_politicas`] lies in `1..=POLICY_RETRIES_MAX`.
4369///
4370/// The typed slot is `Option<u32>` (`None` = no retries on transient
4371/// failure; `Some(0)` already rejected by the
4372/// [`AplicacaoError::PolicyRetriesZero`] zero-floor arm), so a
4373/// programmatic struct literal (`MeshPolicy { retries: Some(100_000),
4374/// .. }`) and the equivalent author-surface form
4375/// (`(:politicas (:retries 100000))`) both round-trip cleanly through
4376/// serde / the codec — a structurally unbounded `u32` ceiling. The
4377/// runtime substrate that consumes the value (Envoy's
4378/// `retry_policy.num_retries`, the `CiliumClusterwideEnvoyConfig`
4379/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 names, AWS
4380/// App Mesh's `gRPCRouteRetryPolicy.maxRetries` whose schema-side
4381/// admission cap is 10) translates a four-billion-retry policy into a
4382/// thundering-herd amplification vector on transient failure — the
4383/// caller's one request fans out to `retries` server-side calls per
4384/// edge per traversal, multiplying load by `(retries+1)^depth` across
4385/// the synchronous-`:contratos` subgraph. The MESH-COMPOSITION §V CSE
4386/// invariant "no infinite blocking" pairs with a no-runaway-amplification
4387/// invariant on the retry axis; both belong at the typed-slot layer.
4388///
4389/// The `10` ceiling matches AWS App Mesh's explicit hard cap (the only
4390/// upstream mesh-policy schema that documents one) and sits above the
4391/// Envoy / Istio practical-recommendation band (`num_retries ≤ 5` in
4392/// every documented production playbook): a value the author can
4393/// plausibly want, but a hard wall above which the policy is
4394/// structurally a footgun. Lifted as a typed `pub const` so the bound
4395/// has exactly one source of truth — a future axis reaching for the
4396/// same value (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4397/// materializer's admission webhook, the caixa-mesh-side
4398/// `CiliumClusterwideEnvoyConfig` overlay's per-edge cap) reads from
4399/// one place. Same shape every other typed upper bound in this crate
4400/// carries ([`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4401/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4402/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
4403/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4404pub const POLICY_RETRIES_MAX: u32 = 10;
4405
4406/// Upper-bound ceiling on the `:politicas :circuit-breaker :max-failures`
4407/// axis — every validated [`CircuitBreaker::max_failures`] past
4408/// [`AplicacaoSpec::validate_politicas`] lies in
4409/// `1..=POLICY_BREAKER_MAX_FAILURES_MAX`.
4410///
4411/// The typed field is `u32` (the zero-floor arm
4412/// [`AplicacaoError::PolicyBreakerZeroFailures`] already rejects
4413/// `0` — a breaker that trips on the first call), so a programmatic
4414/// struct literal (`CircuitBreaker { max_failures: u32::MAX, .. }`)
4415/// and the equivalent author-surface form
4416/// (`(:circuit-breaker (:max-failures 4294967295))`) both round-trip
4417/// cleanly through serde — a structurally unbounded `u32` ceiling. A
4418/// `max_failures` value far above the documented production-playbook
4419/// band (Hystrix `circuitBreaker.requestVolumeThreshold` default 20,
4420/// Istio `outlierDetection.consecutive5xxErrors` default 5, Envoy
4421/// `outlier_detection.consecutive_5xx` default 5, Polly / Resilience4j
4422/// typical 5–50) silently disables the breaker's protection role:
4423/// the threshold is structurally so high that no realistic
4424/// failures-per-`:window` traffic shape can reach it, so the breaker
4425/// never trips and the typed slot becomes a no-op carried on every
4426/// emitted Envoy / Cilium L7 overlay. Pairs with the
4427/// [`POLICY_RETRIES_MAX`] cap on the sibling `:politicas :retries`
4428/// axis — both close the "structurally unbounded `u32` ceiling on a
4429/// typed policy axis" footgun the prior zero-floor-only checks left
4430/// open.
4431///
4432/// The `1000` ceiling sits an order of magnitude above every
4433/// documented upstream production-playbook recommendation band (the
4434/// highest is Hystrix's 20-default `requestVolumeThreshold`, the
4435/// Istio / Envoy / Polly / Resilience4j ones all sit ≤ 50) and below
4436/// the clearly-pathological "effectively no protection"
4437/// floor (`10_000`, `100_000`, `u32::MAX`): a value the author can
4438/// plausibly want at hyperscale, but a hard wall above which the
4439/// policy is structurally a no-op. Lifted as a typed `pub const` so
4440/// the bound has exactly one source of truth — the future M4
4441/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
4442/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
4443/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
4444/// one place. Same shape every other typed upper bound in this crate
4445/// carries ([`POLICY_RETRIES_MAX`],
4446/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4447/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4448/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4449pub const POLICY_BREAKER_MAX_FAILURES_MAX: u32 = 1000;
4450
4451/// Upper-bound ceiling on the `:politicas :circuit-breaker :window` axis —
4452/// every validated [`CircuitBreaker::window`] past
4453/// [`AplicacaoSpec::validate_politicas`] lies in
4454/// `1ms..=POLICY_BREAKER_WINDOW_MAX` (inclusive on both ends,
4455/// integer-millisecond magnitudes by the canonical-form gate
4456/// immediately preceding).
4457///
4458/// The typed field is `Duration` (the zero-floor arm
4459/// [`AplicacaoError::PolicyBreakerZeroWindow`] already rejects
4460/// `Duration::ZERO`, and the canonical-form arm
4461/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`] already rejects
4462/// sub-millisecond residue), so a programmatic struct literal
4463/// (`CircuitBreaker { window: Duration::from_secs(86_400), .. }` — 24h)
4464/// and the equivalent author-surface form
4465/// (`(:circuit-breaker (:window "24h"))` — the codec emits `"h"` for any
4466/// integer-hour magnitude) both round-trip cleanly through serde — a
4467/// structurally unbounded `Duration` ceiling. A `:window` value far
4468/// above the documented production-playbook band (Hystrix
4469/// `metrics.rollingStats.timeInMilliseconds` default `10s`,
4470/// resilience4j `slidingWindowSize` time-based typical `10s..=60s`,
4471/// Istio `outlierDetection.interval` default `10s`, Envoy
4472/// `outlier_detection.interval` default `10s`, AWS App Mesh
4473/// circuit-breaker time-window typical `30s..=300s`) degenerates the
4474/// breaker's role: a rolling-window failure counter whose window is
4475/// hours long is operationally a lifetime counter, the breaker's
4476/// "recent failures" memory is structurally so long that transient
4477/// failures are never forgotten, and the typed slot becomes a no-op
4478/// trigger that trips once and stays tripped for the lifetime of the
4479/// component carried on every emitted Envoy / Cilium L7 overlay.
4480///
4481/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
4482/// shared duration codec emits (`"<n>h"` for any integer-hour
4483/// magnitude) — every value in the canonical authoring form's
4484/// `<integer><unit>` grammar at or below this cap renders to a clean
4485/// canonical string — and matches the sibling [`POLICY_TIMEOUT_MAX`]
4486/// cap on the first typed-`Duration` `:politicas` axis: the two
4487/// duration-typed `:politicas` axes now share a single uniform top
4488/// edge so the next typed-slot wiring (the future caixa-mesh
4489/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay, the M4
4490/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-policy
4491/// admission webhook) reaches for either field knowing the value is
4492/// in `1ms..=1h` without re-validating at the renderer layer. The cap
4493/// sits two orders of magnitude above every documented upstream
4494/// production-playbook recommendation band (Hystrix / resilience4j /
4495/// Istio / Envoy all default to 10s; AWS App Mesh maxes out at ~5m)
4496/// and below the clearly-pathological "rolling window degenerates to
4497/// lifetime counter" floor (`24h`, `7d`, `Duration::MAX`): a value the
4498/// author can plausibly want for a very-low-traffic long-tail
4499/// failure-detection window, but a hard wall above which the breaker's
4500/// rolling-window contract is structurally a lifetime-counter contract.
4501/// Lifted as a typed `pub const` so the bound has exactly one source
4502/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4503/// materializer's admission webhook and the caixa-mesh-side
4504/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
4505/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
4506/// other typed upper bound in this crate carries
4507/// ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
4508/// [`POLICY_BREAKER_MAX_FAILURES_MAX`],
4509/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4510/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4511/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4512pub const POLICY_BREAKER_WINDOW_MAX: Duration = Duration::from_secs(3600);
4513
4514/// Upper-bound ceiling on the `:politicas :rate-limit` rate axis —
4515/// every validated [`RateLimit::rate`] past
4516/// [`AplicacaoSpec::validate_politicas`] lies in
4517/// `1..=POLICY_RATE_LIMIT_MAX`.
4518///
4519/// The typed field is `u32` (the zero-floor arm
4520/// [`AplicacaoError::PolicyRateLimitZero`] already rejects `0` — a
4521/// zero-rate limit denies every request, the canonical "I forgot
4522/// that 0 means deny-everything" footgun), so a programmatic struct
4523/// literal (`RateLimit { rate: u32::MAX, window: Duration::from_secs(1) }`)
4524/// and the equivalent author-surface form (`(:rate-limit "4294967295/s")`
4525/// — the `rate_limit_codec` parses any `u32`-shaped magnitude) both
4526/// round-trip cleanly through serde — a structurally unbounded `u32`
4527/// ceiling. The runtime substrate consuming the value (Envoy's
4528/// `local_rate_limit.token_bucket.max_tokens`, the future
4529/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
4530/// MESH-COMPOSITION §III.2 #3 names) translates a four-billion-token
4531/// rate-limit into a no-op rate-limiter: the bucket capacity is
4532/// structurally so high no realistic per-edge traffic shape can
4533/// drain it, the limiter never trips, and the typed slot becomes a
4534/// "rate-limit declared, no enforcement" footgun — the canonical
4535/// declared-but-inert shape every other `:politicas` cap arm
4536/// closes ([`POLICY_RETRIES_MAX`] thundering-herd amplification,
4537/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] no-op-breaker, etc.).
4538///
4539/// The `1_000_000` (1M) ceiling sits two-to-three orders of magnitude
4540/// above every documented upstream production-playbook recommendation
4541/// band (Envoy `local_rate_limit` typical `10..=10_000` RPS, Istio
4542/// `RateLimitFilter` typical `10..=10_000` RPS, Cloudflare WAF
4543/// rate-rule Free / Pro `10_000` req/min, AWS API Gateway account
4544/// default `10_000` RPS, Kong typical `100..=10_000`, NGINX
4545/// `limit_req_zone` typical `1..=1_000` RPS) and below the
4546/// clearly-pathological "paste-from-binary blob" floor (`100_000_000`,
4547/// `u32::MAX`): a value the author can plausibly want at hyperscale
4548/// (Cloudflare Enterprise rate-plans run to ~6M/min ≈ 1M/h on the
4549/// /h-window arm), but a hard wall above which the policy is
4550/// structurally a no-op carried verbatim on every emitted Envoy /
4551/// Cilium L7 overlay. The cap brackets all three canonical windows
4552/// the [`rate_limit_codec`] accepts: at `1M/s` (absurd hyperscale
4553/// ceiling, ~1M RPS per edge), at `1M/m` (~16.7k RPS, the
4554/// hyperscale-tier WAF band), at `1M/h` (~277 RPS, the common
4555/// per-endpoint API band). Lifted as a typed `pub const` so the bound
4556/// has exactly one source of truth — the future M4
4557/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
4558/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
4559/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
4560/// one place. Same shape every other typed upper bound in this crate
4561/// carries ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
4562/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
4563/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4564/// [`crate::LIMITS_WALL_CLOCK_MAX`],
4565/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4566/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4567pub const POLICY_RATE_LIMIT_MAX: u32 = 1_000_000;
4568
4569// `:entrada :host` total-length and per-label cap axes route through
4570// the lifted [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] (253) and
4571// [`crate::render::DNS_1123_LABEL_MAX_LEN`] (63) canonical bounds. The
4572// pair of aplicacao-private aliases the previous `validate_entrada_host`
4573// arms consumed (`ENTRADA_HOST_MAX_LEN = 253`, `ENTRADA_HOST_LABEL_MAX_LEN
4574// = 63`) were structurally the same K8s Gateway API v1 Hostname
4575// admission-schema bounds — the total-length cap on the OpenAPI
4576// `Hostname` type and the per-`.`-separated-label DNS-1123 cap on the
4577// same regex — that the peer axes at the caixa-core::render level pin,
4578// so hoisting both readers onto the shared lifted constants closes the
4579// third-occurrence duplication threshold structurally: the M4
4580// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-host / per-
4581// label validator, the future per-`Certificate` SAN emitter, and every
4582// other per-Gateway-API-Hostname landing site reach the same one place
4583// as the `:entrada :host` gate does — no per-axis alias drift surface
4584// between them, by construction.
4585
4586/// Max byte length for an Akka-cluster-sharding `:placement :shard-key`
4587/// extractor expression — the upper bound `validate_placement_shard_key`
4588/// enforces on every well-shaped shard-key past validate. The realistic
4589/// shard-key forms in the wild (`tenantId`, `customerId`, `$tenantId`,
4590/// `metadata.tenantId`, `${tenant}`, `$.user.id`) all sit well under 64
4591/// bytes; the 63-byte cap mirrors the DNS-1123 label cap on the peer
4592/// `:placement :affinity` / `:placement :clusters` identifier-shaped
4593/// axes and surfaces the canonical "paste-from-doc multi-line blob landed
4594/// in `:shard-key`" footgun at validate time rather than at the future
4595/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass.
4596const PLACEMENT_SHARD_KEY_MAX_LEN: usize = 63;
4597
4598/// Reject `:membros :caixa` values the K8s apiserver would refuse at
4599/// admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
4600/// that maps the shared parser-shaped reason into the
4601/// [`AplicacaoError::MembroCaixaInvalid`] variant, so the diagnostic
4602/// is self-locating (the offending `caixa:` is named verbatim) and
4603/// the author can grep their caixa.lisp for `:caixa "<name>"` and
4604/// fix it in one edit. Same diagnostic shape as
4605/// [`AplicacaoError::EntradaHostInvalid`] (c7d05ec) and
4606/// [`AplicacaoError::MembroVersaoInvalid`] (9888b13).
4607fn validate_membro_caixa(caixa: &str) -> Result<(), AplicacaoError> {
4608    // Empty is already gated by `MembroCaixaEmpty` at the call site;
4609    // re-checking here keeps the predicate usable from any future
4610    // call site (the M4 CR materializer) without an empty-check
4611    // footgun. The shared
4612    // [`crate::render::require_valid_dns_1123_label`] helper brackets
4613    // the empty-first + shape cascade every peer name axis
4614    // (`:placement :clusters`, `:placement :affinity`, `:contratos
4615    // :de`/`:para`, `:entrada :para`, `:children :caixa`, `:nome`,
4616    // `:upgrade-from :module`) routes through, so drift between the
4617    // eight axes' accepted DNS-1123-label sets is structurally
4618    // impossible.
4619    crate::render::require_valid_dns_1123_label(
4620        caixa,
4621        || AplicacaoError::MembroCaixaEmpty,
4622        |reason| AplicacaoError::membro_caixa_invalid(caixa, reason),
4623    )
4624}
4625
4626/// Reject `:placement :clusters` entries the K8s apiserver would refuse
4627/// at admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
4628/// that maps the shared parser-shaped reason into the
4629/// [`AplicacaoError::PlacementClusterInvalid`] variant.
4630///
4631/// Cluster names land in DNS-1123-label territory across every consumer:
4632/// the K8s context name keying `kubeconfig`, the `clusters[]` filter
4633/// the `lareira-fleet-programs` aggregator applies to scope programs to
4634/// their owning cluster (caixa-mesh's `placement.clusters` overlay,
4635/// 4d91c0b), the namespace prefix the future cross-cluster fan-out
4636/// emits per entry, and the `cluster.x-k8s.io/v1beta1/Cluster.metadata.name`
4637/// cluster identity the M4 CR materializer round-trips. Each apiserver-
4638/// side schema enforces the DNS-1123 label rule on admission; a
4639/// structurally invalid cluster name (`"Rio"`, `"my_cluster"`,
4640/// `"team.rio"`, `"-rio"`, `"rio-"`, the >63-byte UUID-shaped
4641/// mistaken-identity slug) silently passes the prior empty-/duplicate-
4642/// only gate and the failure surfaces as a no-match at filter time —
4643/// the workload doesn't land in the named cluster, with no diagnostic
4644/// naming the offending `:clusters` entry. Lifting the gate to caixa-
4645/// build time mirrors the `:membros :caixa` value-shape trajectory
4646/// (3f9d7a0) on the peer name axis.
4647///
4648/// The diagnostic carries the offending `cluster:` verbatim plus a
4649/// parser-shaped `reason:` naming the specific violation, so the
4650/// author can grep their caixa.lisp for `:clusters` and fix it in
4651/// one edit. Same diagnostic shape as
4652/// [`AplicacaoError::MembroCaixaInvalid`] (3f9d7a0).
4653fn validate_placement_cluster(cluster: &str) -> Result<(), AplicacaoError> {
4654    // Empty is already gated by `PlacementClusterEmpty` at the call
4655    // site; re-checking here keeps the predicate usable from any
4656    // future call site (the M4 CR materializer's per-cluster validator)
4657    // without an empty-check footgun. Routes through the shared
4658    // [`crate::render::require_valid_dns_1123_label`] gate the peer
4659    // name axes each land on.
4660    crate::render::require_valid_dns_1123_label(
4661        cluster,
4662        || AplicacaoError::PlacementClusterEmpty,
4663        |reason| AplicacaoError::placement_cluster_invalid(cluster, reason),
4664    )
4665}
4666
4667/// Reject `:placement :affinity` hints whose shape can never legitimately
4668/// land in any downstream selector or label-keyed routing axis. Thin
4669/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
4670/// shared parser-shaped reason into the
4671/// [`AplicacaoError::PlacementAffinityInvalid`] variant, so the
4672/// diagnostic is self-locating (the offending `:affinity` is named
4673/// verbatim) and the author can grep their caixa.lisp for
4674/// `:affinity "<hint>"` and fix it in one edit.
4675///
4676/// The `:affinity` slot carries a placement-engine hint — canonical
4677/// examples in the M3 surface are `"data-locality"`, `"low-latency"`,
4678/// `"anti-affinity"` — that flows verbatim into the M3 Adaptive
4679/// compression overlay and the future M4 placement-engine's per-hint
4680/// routing axis. Each downstream consumer (caixa-mesh's
4681/// `placement.affinity` overlay at caixa-mesh/src/lib.rs:126, the
4682/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4683/// `spec.placement.affinity` admission rule, the future M4 per-hint
4684/// node-affinity / pod-affinity rule generator keying off the same
4685/// value as a K8s `app.pleme.io/affinity-hint=<value>` label
4686/// selector) requires the value to be a DNS-1123 label — K8s label
4687/// values are bounded by `[a-z0-9A-Z_.-]{,63}` with a stricter
4688/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?` floor in every identity-keyed
4689/// admission rule the apiserver enforces.
4690///
4691/// Until this gate landed an `:affinity "DataLocality"` (the canonical
4692/// TitleCase-from-an-ADR typo), `:affinity "data_locality"` (the
4693/// Python-module-name leak), `:affinity "data.locality"` (the
4694/// namespace-dot-on-a-label confusion), `:affinity "-data-locality"` /
4695/// `:affinity "data-locality-"` (boundary-hyphen violation),
4696/// `:affinity "data locality"` (paste-from-doc whitespace),
4697/// `:affinity "data-localité"` (un-Punycode-encoded IDN), or the
4698/// 64-byte over-cap slug silently passed the empty-only check and the
4699/// failure surfaced as a no-match at the M3 Adaptive compression
4700/// overlay's filter time (`placement.affinity` carried a malformed
4701/// value, no node matched, the workload landed on the default
4702/// heuristic) — the canonical "declared-but-inert" footgun mirroring
4703/// the empty-:affinity / empty-shard-key / zero-:politicas /
4704/// empty-:contratos-target gates already close on every other
4705/// declare-but-no-opinion axis. Lifting the rejection to a build-time
4706/// gate closes the fifth typed slot on the Aplicacao surface to land
4707/// on the canonical DNS-1123 label floor (after the four Servico-name
4708/// reference axes: `:membros :caixa` 3f9d7a0, `:placement :clusters`
4709/// 6c8c00b, `:contratos :de`/`:para` 8d5af6b, `:entrada :para`
4710/// b0e8748).
4711///
4712/// Same diagnostic shape as [`AplicacaoError::PlacementClusterInvalid`]
4713/// (6c8c00b) on the sibling `:placement :clusters` axis — both axes'
4714/// validated values are guaranteed-accepted by the apiserver without
4715/// re-validation at any downstream renderer or admission layer.
4716fn validate_placement_affinity(affinity: &str) -> Result<(), AplicacaoError> {
4717    // Empty is gated separately at the call site for a self-locating
4718    // diagnostic; re-checking here keeps the predicate usable from any
4719    // future call site (the M4 CR materializer's per-affinity
4720    // validator) without an empty-check footgun. Routes through the
4721    // shared [`crate::render::require_valid_dns_1123_label`] gate the
4722    // peer name axes each land on.
4723    crate::render::require_valid_dns_1123_label(
4724        affinity,
4725        || AplicacaoError::PlacementAffinityEmpty,
4726        |reason| AplicacaoError::placement_affinity_invalid(affinity, reason),
4727    )
4728}
4729
4730/// Reject `:placement :shard-key` extractor expressions whose shape can
4731/// never legitimately drive the future M4 Akka-style cluster-sharding
4732/// reconciler's hash-extractor pass. Maps the per-byte / length checks
4733/// into the [`AplicacaoError::ShardKeyInvalid`] variant, so the
4734/// diagnostic is self-locating (the offending `:shard-key` value is
4735/// named verbatim alongside the parser-shaped reason) and the author can
4736/// grep their caixa.lisp for `:shard-key "<expr>"` and fix it in one
4737/// edit.
4738///
4739/// The `:shard-key` slot is the Akka-cluster-sharding `ExtractEntityId`
4740/// axis (MESH-COMPOSITION §II.4) — a single-token entity-id extractor
4741/// expression naming the message property to hash on. The realistic
4742/// shapes in the wild (`tenantId` / `customerId` / `userId` — bare
4743/// property name; `$tenantId` — Akka entity-id placeholder;
4744/// `metadata.tenantId` / `$.user.id` — JSONPath-style nested reference;
4745/// `${tenant}` — interpolation-style template) all sit in the printable
4746/// ASCII subset; the realistic *non-shapes* (a paste-from-doc
4747/// multi-line blob landing in `:shard-key`, an embedded space from a
4748/// paste-from-aligned-doc, a trailing newline from a paste-from-shell
4749/// heredoc, a non-ASCII byte from a paste-from-Unicode-doc, the
4750/// `:shard-key "tenant Id"` typo) silently passed the prior empty-only
4751/// check and the failure surfaces at the future M4 reconciler's hash
4752/// pass as a runtime extractor-evaluation error far from the source
4753/// `caixa.lisp`, with no field naming which member's `:shard-key`
4754/// carried the offending value.
4755///
4756/// The contract — the printable ASCII single-token intersection-floor
4757/// every Akka-style entity-id extractor implementation admits:
4758///
4759///   - 1..=[`PLACEMENT_SHARD_KEY_MAX_LEN`] (63) bytes — same cap as the
4760///     peer DNS-1123-label-shaped `:placement :affinity` /
4761///     `:placement :clusters` identifier axes; realistic shard-keys sit
4762///     well under 32 bytes, the cap surfaces paste-from-doc multi-line
4763///     blob footguns at validate time;
4764///   - every byte in the printable ASCII range `0x21..=0x7E` —
4765///     rejects whitespace (space, tab, CR, LF — `"$tenant Id"` /
4766///     `"$tenantId\n"` from paste-from-aligned-doc /
4767///     paste-from-shell-heredoc), control characters (`\x00..\x1F`,
4768///     `\x7F` — the canonical "embedded null from a copy-paste-binary
4769///     footgun"), and non-ASCII bytes (`"$tenàntId"` —
4770///     un-Punycode-encoded IDN that round-trips inconsistently across
4771///     NFC/NFD normalization).
4772///
4773/// The accepted set is broader than the DNS-1123 label floor the peer
4774/// `:placement :clusters` / `:placement :affinity` axes use because the
4775/// `:shard-key` value is not a K8s `metadata.name` / label-selector
4776/// landing site; it's an extractor expression the future Akka-style
4777/// reconciler reads as a property reference. The realistic forms
4778/// (`$tenantId`, `metadata.tenantId`, `${tenant}`, `$.user.id`) carry
4779/// `$` / `.` / `{` / `}` characters that the DNS-1123 grammar forbids
4780/// but every Akka-style entity-id extractor parses. The
4781/// printable-ASCII-token floor accepts every shape any such extractor
4782/// would accept while rejecting the cross-implementation footguns
4783/// (whitespace breaks token boundaries; non-ASCII round-trips
4784/// inconsistently across YAML emitters and NFC/NFD normalization;
4785/// control characters silently corrupt the next read).
4786///
4787/// Until this gate landed `validate_placement` only refused the
4788/// `Some("")` empty arm via [`AplicacaoError::ShardedKeyEmpty`]; a
4789/// structurally invalid `:shard-key` (`":shard-key \" $tenantId\""` —
4790/// leading space from paste-from-aligned-doc, `":shard-key \"$tenant
4791/// Id\""` — embedded space, `":shard-key \"$tenantId\\n\""` — trailing
4792/// newline from paste-from-shell-heredoc, `":shard-key \"$tenàntId\""`
4793/// — un-Punycode-encoded IDN, `":shard-key \"$tenantId\\x01\""` —
4794/// control character from paste-from-binary, the 64-byte over-cap
4795/// paste-from-doc multi-line slug) silently passed validate. The future
4796/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass
4797/// would then surface the malformed value either as a runtime
4798/// extractor-evaluation error (whitespace breaks the extractor's token
4799/// boundary, no match) or as a silently-different shard assignment
4800/// across YAML emitters (non-ASCII normalizes differently between the
4801/// caixa-mesh-side YAML emitter and the in-cluster reconciler's YAML
4802/// parser, the same entity ID maps to two distinct shards on a
4803/// re-render). Lifting the shape gate to caixa-build time makes the
4804/// extractor-floor invariant a structural property of every validated
4805/// `Placement`: every `Sharded` placement past `validate_placement` has
4806/// a `:shard-key` the future M4 reconciler can hash without
4807/// re-validating at the runtime layer.
4808///
4809/// Mirrors the [`AplicacaoError::ContratoSlotInvalid`] /
4810/// [`AplicacaoError::ContratoSubjectInvalid`] /
4811/// [`AplicacaoError::ContratoEndpointInvalid`] payload-axis shape gates
4812/// on the peer `:contratos` payload axes — each lifts the
4813/// runtime-side parser's intersection-floor to a caixa-build-time gate,
4814/// closing the canonical "this passed validate but the runtime parser
4815/// rejected it" surprise.
4816fn validate_placement_shard_key(key: &str) -> Result<(), AplicacaoError> {
4817    // Empty is gated separately at the call site via the more
4818    // self-locating [`AplicacaoError::ShardedKeyEmpty`] diagnostic;
4819    // re-checking here keeps the predicate usable from any future call
4820    // site (the M4 CR materializer's per-shard-key validator) without
4821    // an empty-check footgun.
4822    if key.is_empty() {
4823        return Err(AplicacaoError::ShardedKeyEmpty);
4824    }
4825    if key.len() > PLACEMENT_SHARD_KEY_MAX_LEN {
4826        return Err(AplicacaoError::shard_key_invalid(
4827            key,
4828            format!(
4829                "exceeds :shard-key max length of {PLACEMENT_SHARD_KEY_MAX_LEN} bytes \
4830                 (got {} bytes; realistic Akka-style entity-id extractor expressions \
4831                 — `tenantId`, `$tenantId`, `metadata.tenantId`, `${{tenant}}` — sit \
4832                 well under 32 bytes, this length suggests a paste-from-doc \
4833                 multi-line blob landed in `:shard-key` instead of a single-token \
4834                 extractor expression)",
4835                key.len()
4836            ),
4837        ));
4838    }
4839    for &b in key.as_bytes() {
4840        if (0x21..=0x7E).contains(&b) {
4841            continue;
4842        }
4843        let reason = if b == b' ' {
4844            "contains a space (Akka-style entity-id extractor expressions are \
4845             single-token references like `tenantId` / `$tenantId` / `metadata.tenantId`; \
4846             whitespace breaks the extractor's token boundary at the runtime layer, \
4847             and the paste-from-aligned-doc / paste-from-CSV footgun silently lands \
4848             a multi-token blob in one `:shard-key` slot)"
4849                .to_string()
4850        } else if b == b'\t' {
4851            "contains a tab character (paste-from-aligned-doc footgun; the \
4852             Akka-style entity-id extractor reads `:shard-key` as a single-token \
4853             reference, embedded whitespace breaks the token boundary at the \
4854             runtime hash-extractor pass)"
4855                .to_string()
4856        } else if b == b'\n' || b == b'\r' {
4857            format!(
4858                "contains line terminator 0x{b:02x} (paste-from-shell-heredoc / \
4859                 paste-from-multiline-doc footgun; the Akka-style entity-id \
4860                 extractor reads `:shard-key` as a single-token reference, embedded \
4861                 newlines either truncate the value at the YAML emitter layer or \
4862                 break the token boundary at the runtime hash-extractor pass)"
4863            )
4864        } else if b < 0x20 || b == 0x7F {
4865            format!(
4866                "contains control character 0x{b:02x} (the canonical \
4867                 paste-from-binary / paste-from-screen-cleared-terminal footgun; \
4868                 control characters silently corrupt round-trip serialization \
4869                 across YAML emitters and break the runtime hash-extractor's \
4870                 single-token parser)"
4871            )
4872        } else {
4873            format!(
4874                "contains non-ASCII byte 0x{b:02x} (the canonical \
4875                 paste-from-Unicode-doc footgun; non-ASCII bytes round-trip \
4876                 inconsistently across NFC/NFD normalization on APFS / ext4 / \
4877                 across YAML emitter implementations — the same entity ID can \
4878                 silently map to two distinct shards on a re-render. Use a \
4879                 printable-ASCII extractor expression like `tenantId`, \
4880                 `$tenantId`, or `metadata.tenantId`)"
4881            )
4882        };
4883        return Err(AplicacaoError::shard_key_invalid(key, reason));
4884    }
4885    Ok(())
4886}
4887
4888/// Reject `:contratos :de` / `:contratos :para` values whose shape
4889/// can never legitimately match a validated `:membros :caixa`. Thin
4890/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
4891/// shared parser-shaped reason into the
4892/// [`AplicacaoError::ContratoCaixaInvalid`] variant, so the per-edge
4893/// diagnostic is self-locating (which slot — `:de` or `:para` — and
4894/// the offending value verbatim) and the author can grep their
4895/// caixa.lisp for `:de "<name>"` / `:para "<name>"` and fix it in
4896/// one edit.
4897///
4898/// Until this gate landed an empty or DNS-1123-malformed `:de` /
4899/// `:para` (`:de ""`, `:de "Cart"` the canonical TitleCase-from-an-ADR
4900/// typo, `:de "my_cart"` the Python-module-name leak, `:de "team.cart"`
4901/// the namespace-dot-on-a-label confusion, `:de "-cart"` / `:de "cart-"`
4902/// the boundary-hyphen violation, the 64-byte over-cap slug, `:de "café"`
4903/// un-Punycode-encoded IDN) silently passed the per-axis check and
4904/// surfaced as [`AplicacaoError::ContratoMemberMissing`] at the
4905/// membership lookup — diagnostic-framed as "this caixa is not in
4906/// `:membros`" when the root cause is "this `:de` value is not a
4907/// well-shaped Servico-name identifier and could never legitimately
4908/// match any validated member". Because every `:membros :caixa` is
4909/// shape-validated through [`validate_membro_caixa`] (3f9d7a0), the
4910/// `names` HashSet structurally never contains an empty / malformed
4911/// string, so the membership lookup arm misframes every empty /
4912/// malformed input. Lifting the shape arm ahead of the lookup
4913/// preserves the legitimate `ContratoMemberMissing` arm (a
4914/// well-shaped `:de` that simply isn't in `:membros` — a phantom
4915/// reference) while routing every structurally-impossible-to-match
4916/// input through the narrower self-locating shape diagnostic.
4917///
4918/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
4919/// (3f9d7a0) and [`AplicacaoError::PlacementClusterInvalid`]
4920/// (6c8c00b) — the third Aplicacao-level Servico-name reference axis
4921/// to land on the canonical [`crate::render::is_dns_1123_label`]
4922/// floor. The `slot: &'static str` field carries the kebab-case
4923/// `:de` / `:para` tag verbatim, mirroring [`BehaviorSpec::validate`]'s
4924/// per-callback-slot diagnostic shape and the
4925/// [`ManifestError::CodePathDuplicate`] (e113ace) / [`DepError::DepIsSelf`]
4926/// (85f102c) cross-list-tag pattern.
4927fn validate_contrato_caixa(slot: &'static str, caixa: &str) -> Result<(), AplicacaoError> {
4928    // Routes through the shared
4929    // [`crate::render::require_valid_dns_1123_label`] gate the peer
4930    // name axes each land on. The `slot: &'static str` field flows
4931    // through both error variants so the diagnostic names which
4932    // per-edge axis (`:de` vs `:para`) the offending value came from.
4933    crate::render::require_valid_dns_1123_label(
4934        caixa,
4935        || AplicacaoError::contrato_caixa_empty(slot),
4936        |reason| AplicacaoError::contrato_caixa_invalid(slot, caixa, reason),
4937    )
4938}
4939
4940/// Reject `:entrada :para` values whose shape can never legitimately
4941/// match a validated `:membros :caixa`. Thin wrapper around
4942/// [`crate::render::is_dns_1123_label`] that maps the shared parser-
4943/// shaped reason into the [`AplicacaoError::EntradaParaInvalid`]
4944/// variant, so the diagnostic is self-locating (the offending
4945/// `:entrada :para` value is named verbatim) and the author can grep
4946/// their caixa.lisp for `:para "<name>"` and fix it in one edit.
4947///
4948/// Until this gate landed an empty or DNS-1123-malformed `:entrada
4949/// :para` (`:para ""`, `:para "Cart"` the canonical TitleCase-from-an-
4950/// ADR typo, `:para "my_cart"` the Python-module-name leak,
4951/// `:para "team.cart"` the namespace-dot-on-a-label confusion,
4952/// `:para "-cart"` / `:para "cart-"` the boundary-hyphen violation,
4953/// the 64-byte over-cap slug, `:para "café"` un-Punycode-encoded IDN)
4954/// silently passed the per-axis check and surfaced as
4955/// [`AplicacaoError::EntradaMemberMissing`] at the membership lookup
4956/// — diagnostic-framed as "this caixa is not in `:membros`" when the
4957/// root cause is "this `:entrada :para` value is not a well-shaped
4958/// Servico-name identifier and could never legitimately match any
4959/// validated member". Because every `:membros :caixa` is shape-
4960/// validated through [`validate_membro_caixa`] (3f9d7a0), the `names`
4961/// `HashSet` structurally never contains an empty / malformed string,
4962/// so the membership lookup arm misframes every empty / malformed
4963/// input. Lifting the shape arm ahead of the lookup preserves the
4964/// legitimate `EntradaMemberMissing` arm (a well-shaped `:para` that
4965/// simply isn't in `:membros` — a phantom reference) while routing
4966/// every structurally-impossible-to-match input through the narrower
4967/// self-locating shape diagnostic.
4968///
4969/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
4970/// (3f9d7a0), [`AplicacaoError::PlacementClusterInvalid`] (6c8c00b),
4971/// and [`AplicacaoError::ContratoCaixaInvalid`] (8d5af6b) — the
4972/// fourth and last Aplicacao-level Servico-name reference axis to
4973/// land on the canonical [`crate::render::is_dns_1123_label`] floor.
4974/// No `slot: &'static str` field because there is only one axis
4975/// (`:entrada :para`), unlike the dual-axis `:contratos :de`/`:para`;
4976/// the simpler shape mirrors [`validate_membro_caixa`] and
4977/// [`validate_placement_cluster`].
4978fn validate_entrada_para(para: &str) -> Result<(), AplicacaoError> {
4979    // Empty is gated separately at the call site for a self-locating
4980    // diagnostic; re-checking here keeps the predicate usable from any
4981    // future call site (the M4 CR materializer's per-`:entrada`
4982    // validator) without an empty-check footgun. Routes through the
4983    // shared [`crate::render::require_valid_dns_1123_label`] gate the
4984    // peer name axes each land on.
4985    crate::render::require_valid_dns_1123_label(
4986        para,
4987        || AplicacaoError::EntradaParaEmpty,
4988        |reason| AplicacaoError::entrada_para_invalid(para, reason),
4989    )
4990}
4991
4992/// Reject `:entrada :host` values the K8s Gateway API v1 apiserver
4993/// would refuse at admission time. The contract — exactly the regex
4994/// the Gateway API CRD's OpenAPI schema enforces on `Listener.hostname`
4995/// and `HTTPRoute.spec.hostnames[]`,
4996/// `^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
4997/// (max length 253; per-label max length 63):
4998///
4999///   - lowercase RFC 1123 DNS subdomain (`[a-z0-9-]` only; no
5000///     uppercase, no underscore, no Unicode/IDN — IDN must be
5001///     pre-encoded as Punycode `xn--…` by the author);
5002///   - exactly one optional leading wildcard label (`*.`); a wildcard
5003///     in any non-leading label position is rejected;
5004///   - each `.`-separated label is 1..=63 bytes, with non-hyphen
5005///     alphanumeric at both boundaries (no `-foo`, no `foo-`);
5006///   - total length 1..=253 bytes;
5007///   - no IPv4 literal (Gateway API forbids IP literals);
5008///   - no scheme (`https://`, `http://`), no port (`:8080`), no
5009///     whitespace, no path (`/`).
5010///
5011/// Lifted as a typed gate (rather than an inline cascade in
5012/// `validate()`) so the contract lives in one place — every future
5013/// per-host axis (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5014/// materializer's host validator, the future per-`:entrada` SAN
5015/// emission for cert-manager Certificates, the multi-`:entrada`
5016/// host-collision gate when M4 lands `:entrada` as a `Vec`) reaches
5017/// for the same predicate, not its own. Same compounding shape as
5018/// `is_canonical_rate_limit_window` (808017c) and
5019/// [`WitTarget::label`] (previously the free `contrato_target_label`
5020/// helper, 5dbcfaf; lifted onto the typed [`WitTarget`] enum so the
5021/// per-variant label match is compiler-checked-exhaustive).
5022///
5023/// The diagnostic carries the offending `host:` verbatim plus a
5024/// parser-shaped `reason:` naming the specific violation, so the
5025/// author can grep their caixa.lisp for `:host "<host>"` and fix it
5026/// in one edit. Same diagnostic shape as `MembroVersaoInvalid`
5027/// (9888b13).
5028fn validate_entrada_host(host: &str) -> Result<(), AplicacaoError> {
5029    // Empty is already gated by `EmptyEntradaHost` at the call site;
5030    // re-checking here keeps the predicate usable from any future
5031    // call site (M4 CR materializer) without an empty-check footgun.
5032    if host.is_empty() {
5033        return Err(AplicacaoError::EmptyEntradaHost);
5034    }
5035    if host.len() > crate::render::GATEWAY_API_HOSTNAME_MAX_LEN {
5036        return Err(AplicacaoError::entrada_host_invalid(
5037            host,
5038            format!(
5039                "exceeds Gateway API v1 Hostname max length of {cap} bytes \
5040                 (got {} bytes; the K8s apiserver rejects longer hostnames at admission time)",
5041                host.len(),
5042                cap = crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
5043            ),
5044        ));
5045    }
5046    if host.contains("://") {
5047        return Err(AplicacaoError::entrada_host_invalid(
5048            host,
5049            "must not carry a scheme (drop the `https://` or `http://` prefix; \
5050             Gateway API takes the bare hostname)",
5051        ));
5052    }
5053    if host.contains('/') {
5054        return Err(AplicacaoError::entrada_host_invalid(
5055            host,
5056            "must not carry a path (drop the `/…` suffix; Gateway API path \
5057             matching is in `:entrada :paths`)",
5058        ));
5059    }
5060    // After the `://` scheme-prefix and `/` path arms have ruled out the
5061    // two `:`-bearing shapes the Gateway API actively rejects with
5062    // location-shaped diagnostics, any remaining `:` in the host body is
5063    // either the canonical "I put the port in the `:host` slot"
5064    // authoring footgun (`"checkout.quero.cloud:8080"` — the `:port`
5065    // slot lives one axis away on the same `:entrada` block) or an
5066    // unbracketed IPv6 literal (`"2001:db8::1"`) which Gateway API v1
5067    // Hostname forbids identically to the IPv4-literal arm below. Both
5068    // shapes silently fell through the `://` and `/` arms before this
5069    // lift and surfaced as a deep `label "<rest>:<port>" contains
5070    // invalid character ':'` diagnostic from the per-byte loop near the
5071    // bottom of this predicate, which named the offending byte but not
5072    // the canonical authoring fix — for the port case the author has to
5073    // know the `:entrada` block carries a separate `:port u16` slot
5074    // (`caixa-core/src/aplicacao.rs:1667`, `default_port = 8080`) and
5075    // move the value over; for the IPv6 case the author has to know
5076    // Gateway API v1 forbids IP literals across the board. The contract
5077    // doc-comment above already promises "no port (`:8080`)" verbatim
5078    // in the rejected-shape enumeration but the predicate's
5079    // implementation refused the `:` only as a side-effect of the
5080    // per-label `[a-z0-9-]` character-class loop; this arm brings the
5081    // implementation in line with the documented contract by surfacing
5082    // the canonical fix at the top-level shape gate, peer with how the
5083    // `://` arm names the scheme prefix and the `/` arm names the
5084    // `:entrada :paths` axis. Same compounding trajectory the recent
5085    // `is_gateway_api_http_path` (6a17961) per-byte tightening followed
5086    // — the typed slot's rejected set matches the apiserver's rejected
5087    // set, structurally, with a self-locating diagnostic at the
5088    // offending axis instead of a deep parser-shape leak.
5089    if host.contains(':') {
5090        return Err(AplicacaoError::entrada_host_invalid(
5091            host,
5092            "must not contain `:` (the port belongs in the `:entrada :port` \
5093             slot — a separate `u16` axis on the same `:entrada` block, \
5094             defaulting to 8080 — not in the host body; drop the `:<port>` \
5095             suffix and author the bare hostname. If you intended an IPv6 \
5096             literal (`2001:db8::1` / `::1` / `fe80::1`), Gateway API v1 \
5097             Hostname forbids IP literals identically to the IPv4-literal \
5098             arm — use a DNS name)",
5099        ));
5100    }
5101    // Routed through the lifted [`crate::render::find_ascii_whitespace_byte`]
5102    // predicate — the same single source of truth every peer
5103    // ASCII-whitespace scan in caixa-core flows through: the four
5104    // typed-magnitude codec sites (`limits::parse_byte_size` backing
5105    // `:limits :memory`, `limits::parse_duration` backing `:limits
5106    // :wall-clock`, `limits::parse_millicores` backing `:limits :cpu`,
5107    // `aplicacao::rate_limit_codec::parse` backing `:politicas
5108    // :rate-limit`) and the shared duration codec
5109    // (`supervisor::duration_codec::parse`) backing `:supervisor
5110    // :restart-window` / `:politicas :timeout` / `:politicas
5111    // :circuit-breaker :window`. This landing closes the last string-typed
5112    // slot in caixa-core still calling `.bytes().any(|b|
5113    // b.is_ascii_whitespace())` inline — every ASCII-whitespace scan
5114    // across every typed slot now shares one predicate, so a future
5115    // stricter classification (BOM `\u{FEFF}` / ZWSP `\u{200B}` / ZWJ
5116    // `\u{200D}` — the "invisible but not `char::is_whitespace`" class
5117    // deliberately excluded from the peer non-ASCII predicate) can
5118    // extend at this shared site in one edit rather than seven
5119    // independent scans diverging over time. Naming the offending byte
5120    // in the diagnostic (`0x20` space / `0x09` tab / `0x0a` LF / `0x0c`
5121    // FF / `0x0d` CR) matches the substrate-wide "the diagnostic carries
5122    // the offending byte verbatim" discipline every peer codec site
5123    // already carries (`limits.rs:722` / `limits.rs:784` / `limits.rs:845`
5124    // / `supervisor.rs:823` / `aplicacao.rs:1640`).
5125    if let Some(b) = crate::render::find_ascii_whitespace_byte(host) {
5126        return Err(AplicacaoError::entrada_host_invalid(
5127            host,
5128            format!(
5129                "contains ASCII whitespace byte 0x{b:02x} (Gateway API v1 \
5130                 Hostname is a single-token DNS name — leading, trailing, \
5131                 or embedded whitespace breaks the K8s apiserver's Hostname \
5132                 regex at admission time; the paste-from-aligned-doc / \
5133                 paste-from-shell-history / paste-from-CSV footgun silently \
5134                 lands a multi-token blob in `:entrada :host`. Strip every \
5135                 whitespace byte and author the bare hostname — space \
5136                 `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d` all \
5137                 refuse identically)"
5138            ),
5139        ));
5140    }
5141    // Peer of the ASCII-whitespace scan above: route the non-ASCII
5142    // subset of Unicode `White_Space` through the shared
5143    // [`crate::render::find_non_ascii_whitespace_char`] predicate — the
5144    // single source of truth every peer non-ASCII-whitespace scan in
5145    // caixa-core flows through: `limits::parse_byte_size` (`:limits
5146    // :memory`), `limits::parse_duration` (`:limits :wall-clock`),
5147    // `limits::parse_millicores` (`:limits :cpu`),
5148    // `aplicacao::rate_limit_codec::parse` (`:politicas :rate-limit`),
5149    // and `supervisor::duration_codec::parse` (`:supervisor
5150    // :restart-window` / `:politicas :timeout` / `:politicas
5151    // :circuit-breaker :window`). Before this arm, a NBSP-prefixed host
5152    // (`"\u{00A0}checkout.quero.cloud"` — paste-from-typography), a
5153    // LINE-SEPARATOR-suffixed host (`"checkout.quero.cloud\u{2028}"` —
5154    // paste-from-web-doc), or an EM-SPACE-split host
5155    // (`"checkout.\u{2003}quero.cloud"` — paste-from-typography)
5156    // survived this predicate's ASCII byte-scan (none of the UTF-8
5157    // bytes of `\u{00A0}` / `\u{2028}` / `\u{2003}` match
5158    // `u8::is_ascii_whitespace`), then landed on the per-label
5159    // `bytes[0].is_ascii_alphanumeric()` arm near the bottom of this
5160    // predicate with the generic `label "…" must start and end with an
5161    // alphanumeric` diagnostic — a "far from source at build-time"
5162    // leak that names the label-shape violation but not the
5163    // paste-from-typography origin the author actually needs to fix.
5164    // Peer with the four codec sites the 1b75b38 landing pinned: the
5165    // typed slot's diagnostic axis names the offending codepoint
5166    // (`U+XXXX`) verbatim rather than laundering the value through a
5167    // downstream label-shape arm, so the author can grep their
5168    // caixa.lisp for the invisible codepoint at the surfaced position
5169    // rather than eyeball a multi-byte host for embedded NBSP / LINE
5170    // SEPARATOR / EM-SPACE. Same "single lifted source of truth"
5171    // discipline the peer ASCII-whitespace arm (720ac3b) carries:
5172    // drift between any two typed-slot sites' non-ASCII-whitespace
5173    // rejection set becomes a single-edit fix at the shared predicate
5174    // rather than N independent inline scans diverging over time, and
5175    // a future stricter classification (BOM `\u{FEFF}` / ZWSP
5176    // `\u{200B}` / ZWJ `\u{200D}` — the "invisible but not
5177    // `char::is_whitespace`" class the peer non-ASCII predicate's
5178    // doc-comment names as the follow-up trajectory) extends at the
5179    // shared predicate in one edit rather than seven.
5180    if let Some(ch) = crate::render::find_non_ascii_whitespace_char(host) {
5181        return Err(AplicacaoError::entrada_host_invalid(
5182            host,
5183            format!(
5184                "contains non-ASCII Unicode whitespace character {ch:?} \
5185                 (U+{codepoint:04X}) — Gateway API v1 Hostname is a \
5186                 single-token DNS name limited to `[a-z0-9-]` labels; \
5187                 the paste-from-typography footgun silently lands an \
5188                 invisible codepoint (NBSP `U+00A0`, LINE SEPARATOR \
5189                 `U+2028`, EM-SPACE `U+2003`, IDEOGRAPHIC SPACE \
5190                 `U+3000`, and every other member of the Unicode \
5191                 `White_Space` property outside the ASCII byte range) \
5192                 in `:entrada :host`, which the K8s apiserver's \
5193                 Hostname regex refuses at admission time far from the \
5194                 caixa.lisp source line. Strip every non-ASCII \
5195                 whitespace character and author the bare hostname \
5196                 with only ASCII bytes (write \"checkout.quero.cloud\" \
5197                 verbatim)",
5198                codepoint = ch as u32,
5199            ),
5200        ));
5201    }
5202
5203    // Strip the optional single leading wildcard label *before* the
5204    // trailing-dot check so the bare `"*."` form surfaces the more
5205    // self-locating "wildcard without domain" diagnostic instead of
5206    // the generic "trailing dot" one.
5207    let (had_wildcard, rest) = match host.strip_prefix("*.") {
5208        Some(r) => (true, r),
5209        None => (false, host),
5210    };
5211    if had_wildcard && rest.is_empty() {
5212        return Err(AplicacaoError::entrada_host_invalid(
5213            host,
5214            "wildcard `*.` must be followed by a domain (e.g. `*.example.com`)",
5215        ));
5216    }
5217    if rest.contains('*') {
5218        return Err(AplicacaoError::entrada_host_invalid(
5219            host,
5220            "wildcard `*` is allowed only as the first label (`*.example.com`); \
5221             no inner or trailing `*` labels",
5222        ));
5223    }
5224    if rest.ends_with('.') {
5225        return Err(AplicacaoError::entrada_host_invalid(
5226            host,
5227            "must not have a trailing `.` (Gateway API hostnames are not \
5228             fully-qualified with a root dot; the apiserver regex rejects \
5229             trailing dots)",
5230        ));
5231    }
5232
5233    // Reject pure IPv4 literals: four dot-separated labels, every
5234    // label all-ASCII-digits. Gateway API v1 explicitly forbids IP
5235    // literals as Hostnames.
5236    let labels: Vec<&str> = rest.split('.').collect();
5237    if labels.len() == 4
5238        && labels
5239            .iter()
5240            .all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_digit()))
5241    {
5242        return Err(AplicacaoError::entrada_host_invalid(
5243            host,
5244            "must not be an IPv4 literal (Gateway API v1 Hostname forbids IP \
5245             literals; use a DNS name)",
5246        ));
5247    }
5248
5249    // Per-label shape: 1..=63 bytes, lowercase ASCII alphanumeric +
5250    // hyphen, with non-hyphen at both boundaries.
5251    for label in &labels {
5252        if label.is_empty() {
5253            return Err(AplicacaoError::entrada_host_invalid(
5254                host,
5255                "has an empty label (consecutive `..` or a leading `.`)",
5256            ));
5257        }
5258        if label.len() > crate::render::DNS_1123_LABEL_MAX_LEN {
5259            return Err(AplicacaoError::entrada_host_invalid(
5260                host,
5261                format!(
5262                    "label {label:?} exceeds DNS-1123 label max length of \
5263                     {cap} bytes (got {} bytes)",
5264                    label.len(),
5265                    cap = crate::render::DNS_1123_LABEL_MAX_LEN,
5266                ),
5267            ));
5268        }
5269        let bytes = label.as_bytes();
5270        if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
5271            return Err(AplicacaoError::entrada_host_invalid(
5272                host,
5273                format!(
5274                    "label {label:?} must start and end with an alphanumeric \
5275                     (no leading or trailing `-`)"
5276                ),
5277            ));
5278        }
5279        for &b in bytes {
5280            let valid = b.is_ascii_digit() || b.is_ascii_lowercase() || b == b'-';
5281            if !valid {
5282                let msg = if b.is_ascii_uppercase() {
5283                    format!(
5284                        "label {label:?} contains uppercase character {ch:?} \
5285                         (Gateway API hostnames are lowercase-only; use {lower:?})",
5286                        ch = b as char,
5287                        lower = label.to_ascii_lowercase()
5288                    )
5289                } else if b == b'_' {
5290                    format!(
5291                        "label {label:?} contains `_` (Gateway API hostnames \
5292                         allow only `[a-z0-9-]`; use `-` instead)"
5293                    )
5294                } else {
5295                    format!(
5296                        "label {label:?} contains invalid character {ch:?} \
5297                         (Gateway API hostnames allow only `[a-z0-9-]`)",
5298                        ch = b as char
5299                    )
5300                };
5301                return Err(AplicacaoError::entrada_host_invalid(host, msg));
5302            }
5303        }
5304    }
5305    Ok(())
5306}
5307
5308/// Reject `:entrada :paths` entries the K8s Gateway API v1 apiserver
5309/// would refuse at admission time. Thin wrapper around
5310/// [`crate::render::is_gateway_api_http_path`] that maps the shared
5311/// parser-shaped reason into the [`AplicacaoError::EntradaPathInvalid`]
5312/// variant, preserving the more self-locating
5313/// [`AplicacaoError::EntradaPathEmpty`] /
5314/// [`AplicacaoError::EntradaPathNotAbsolute`] diagnostics when the
5315/// path fails those narrower invariants first.
5316///
5317/// The contract is the canonical HTTP-path grammar — `1..=
5318/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`] (1024) bytes,
5319/// leading `/`, no consecutive `/`, no `.`/`..` segments, no `?`/`#`/
5320/// whitespace/control/non-ASCII bytes — shared with the
5321/// `:contratos :endpoint` axis through the lifted predicate so drift
5322/// between either landing site and the K8s apiserver-side
5323/// HTTPPathMatch.value OpenAPI schema is a build error visible at
5324/// the predicate, not a per-renderer "this passed validate but failed
5325/// admission" surprise. The diagnostic carries the offending `path:`
5326/// verbatim plus a parser-shaped `reason:` naming the specific
5327/// violation, so the author can grep their caixa.lisp for `:paths`
5328/// and fix it in one edit. Same diagnostic shape as
5329/// [`AplicacaoError::ContratoEndpointInvalid`] on the peer HTTP-path
5330/// axis.
5331fn validate_entrada_path(path: &str) -> Result<(), AplicacaoError> {
5332    // Empty and missing-leading-`/` are already gated at the call
5333    // site by `EntradaPathEmpty` and `EntradaPathNotAbsolute`; re-
5334    // checking here keeps the per-axis narrower diagnostics in force
5335    // when the predicate is reached directly (and `is_gateway_api_http_path`
5336    // itself defends against `bytes[0]`-style indexing on empty
5337    // input).
5338    if path.is_empty() {
5339        return Err(AplicacaoError::EntradaPathEmpty);
5340    }
5341    if !path.starts_with('/') {
5342        return Err(AplicacaoError::entrada_path_not_absolute(path));
5343    }
5344    crate::render::is_gateway_api_http_path(path)
5345        .map_err(|reason| AplicacaoError::entrada_path_invalid(path, reason))
5346}
5347
5348mod rate_limit_codec {
5349    // `Duration` is no longer named here — the codec routes through
5350    // the substrate primitive [`super::RateLimitUnit::window_from_suffix`]
5351    // (parse arm, `&str → Duration`) and [`super::RateLimit::canonical_unit`]
5352    // (render arm, `Duration → RateLimitUnit`) typed dispatches that carry
5353    // the canonical `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection on the
5354    // closed-set enum's arm-table rather than through vestigial free-helper
5355    // delegates.
5356    use super::{RateLimit, RateLimitUnit};
5357    use serde::{Deserializer, Serializer};
5358
5359    pub fn serialize<S: Serializer>(v: &Option<RateLimit>, s: S) -> Result<S::Ok, S::Error> {
5360        // Route through the canonical [`crate::render::serialize_option_via_str`]
5361        // — the substrate-side single-owner primitive for the forward
5362        // arm of the typed-magnitude codec family. See its docstring
5363        // for the full sibling roster.
5364        crate::render::serialize_option_via_str(v, s, render)
5365    }
5366
5367    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RateLimit>, D::Error> {
5368        // Route through the canonical [`crate::render::deserialize_option_via_str`]
5369        // — the substrate-side single-owner primitive for the reverse
5370        // arm of the typed-magnitude codec family. See its docstring
5371        // for the full sibling roster.
5372        crate::render::deserialize_option_via_str(d, parse)
5373    }
5374
5375    fn parse(s: &str) -> Result<RateLimit, String> {
5376        // Paired whitespace-rejection arm — same canonical-form
5377        // render-determinism discipline as the peer
5378        // `limits::parse_byte_size` / `limits::parse_duration` /
5379        // `limits::parse_millicores` /
5380        // `supervisor::duration_codec::parse` sites: the ASCII
5381        // byte-scan closes the WhatWG-conformant whitespace bytes
5382        // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
5383        // `char::is_whitespace` scan closes the strictly-complementary
5384        // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
5385        // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
5386        // codepoints) that `str::trim` at parse entry silently strips.
5387        // Either drift class would round-trip through `render` to a
5388        // *different* canonical form on next emit — breaking the
5389        // THEORY.md Part V render-determinism contract on
5390        // `:politicas :rate-limit`.
5391        //
5392        // Routed through the lifted [`crate::render::reject_whitespace`]
5393        // primitive — the substrate-side single-owner paired-arm gate
5394        // every typed-magnitude codec in caixa-core shares.
5395        crate::render::reject_whitespace::<String, _, _>(
5396            s,
5397            |b| {
5398                format!(
5399                    "rate-limit: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
5400                 authoring form for `:politicas :rate-limit` is `<integer>/<s|m|h>` (e.g. \
5401                 `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) with no whitespace bytes \
5402                 anywhere. A whitespace-carrying shape (`\" 100/s\"`, `\"100/s \"`, \
5403                 `\"100 /s\"`, `\"100/ s\"`, `\"100 / s\"`, `\"100/s\\n\"`, `\"\\t100/s\"`) \
5404                 round-trips through `render` to a *different* canonical form (`\"100/s\"`) \
5405                 on first serialize — breaking the THEORY.md Part V render-determinism \
5406                 contract every typed slot carries. Strip every whitespace byte (write \
5407                 `\"100/s\"` verbatim)"
5408                )
5409            },
5410            |ch| {
5411                format!(
5412                    "rate-limit: value {s:?} contains non-ASCII Unicode whitespace character \
5413                 {ch:?} (U+{cp:04X}) — the canonical authoring form for `:politicas \
5414                 :rate-limit` is `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, \
5415                 `\"10000/h\"`) with no whitespace characters anywhere (ASCII or Unicode). \
5416                 A non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}100/s\"`, \
5417                 `\"100/s\\u{{2028}}\"`, `\"100\\u{{2003}}/s\"`) survives the ASCII \
5418                 byte-scan but `str::trim` (which uses `char::is_whitespace` — the \
5419                 Unicode `White_Space` property, strictly wider than the ASCII byte set) \
5420                 silently strips it at parse entry, and the value round-trips through \
5421                 `render` to a *different* canonical form (`\"100/s\"`) on first \
5422                 serialize — breaking the THEORY.md Part V render-determinism contract \
5423                 every typed slot carries. Strip every non-ASCII whitespace character \
5424                 (write `\"100/s\"` verbatim with only ASCII bytes)",
5425                    cp = ch as u32
5426                )
5427            },
5428        )?;
5429        let s = s.trim();
5430        let (rate_str, unit) = s
5431            .split_once('/')
5432            .ok_or_else(|| format!("rate-limit must be `<n>/<unit>`, got {s:?}"))?;
5433        let rate_trim = rate_str.trim();
5434        // The canonical authoring form for `:politicas :rate-limit` is
5435        // `<integer>/<s|m|h>` — every magnitude [`render`] emits is a
5436        // non-negative integer with no decimal point and no leading
5437        // sign, so the parser's accepted set must match for
5438        // serialize/deserialize to round-trip without canonical-form
5439        // drift. Until this gate landed the parser accepted any
5440        // `u32::from_str`-shaped magnitude — and current Rust
5441        // `u32::from_str` permissively accepts a leading `+` (`"+100"`
5442        // → 100), so `"+100/s"` parsed to `RateLimit { 100, 1s }` and
5443        // serde silently round-tripped to `"100/s"` on the next emit
5444        // (a *different* canonical string) — breaking the THEORY.md
5445        // Part V render-determinism contract on the fifth typed-codec
5446        // surface in caixa-core (peer with the four duration codecs the
5447        // 1c55a2a / 818dd38 / d1fd67b / 737a676 / d53c922 trajectory
5448        // already covered: `supervisor::duration_codec` backing three
5449        // typed-duration slots, `limits::parse_duration` backing
5450        // `:limits :wall-clock`, `limits::parse_byte_size` backing
5451        // `:limits :memory`). The fractional / decimal-shaped sibling
5452        // (`"1.5/s"`, `"1.0/s"`, `"0.5/m"`) lands on `u32::from_str`'s
5453        // existing rejection arm, but the diagnostic is value-laundered
5454        // (the bare `"rate-limit rate \"1.5\" not a u32"` wording
5455        // doesn't name the canonical-form remediation or the round-trip
5456        // drift the next emit would produce); this gate lifts the
5457        // fractional arm onto the same canonical-form diagnostic the
5458        // peer codecs carry.
5459        //
5460        // Strict canonical form: every byte of the magnitude is an
5461        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
5462        // inputs the gate distinguishes "non-canonical-but-numeric"
5463        // (parses as f64 or i64 — surfaced with a self-locating
5464        // diagnostic naming the canonical authoring form and the
5465        // round-trip drift the rejected shape would produce on first
5466        // serialize) from "garbage" (parses as neither — surfaced with
5467        // the existing narrower `"not a u32"` wording so its
5468        // diagnostic shape remains stable for the parser-shape footgun
5469        // case).
5470        //
5471        // Routed through the lifted
5472        // [`crate::render::is_digit_only_magnitude`] predicate — the
5473        // same source of truth the four peer typed-magnitude codec
5474        // sites share.
5475        let digit_only = crate::render::is_digit_only_magnitude(rate_trim);
5476        if !digit_only {
5477            let numeric = rate_trim.parse::<f64>().is_ok() || rate_trim.parse::<i64>().is_ok();
5478            if numeric {
5479                return Err(format!(
5480                    "rate-limit: rate {rate_trim:?} is not a non-negative integer — the \
5481                     canonical authoring form for `:politicas :rate-limit` is \
5482                     `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
5483                     with no decimal point and no leading `+` / `-` sign. A fractional / \
5484                     signed magnitude (`\"1.5/s\"`, `\"+100/s\"`, `\"-1/s\"`) round-trips \
5485                     through `render` to a *different* canonical form (`\"1/s\"`, \
5486                     `\"100/s\"`, parser-reject) on first serialize — breaking the \
5487                     THEORY.md Part V render-determinism contract every typed slot \
5488                     carries. Pick an integer rate that fits the desired window \
5489                     (write `\"6000/m\"` instead of `\"1.66/s\"`)"
5490                ));
5491            }
5492            return Err(format!("rate-limit rate {rate_str:?} not a u32"));
5493        }
5494        // Leading-zero arm — peer with the prior `"+100/s"` arm above
5495        // (4eeae98's predecessor) on the same canonical-form
5496        // render-determinism axis. The digit-only gate accepts
5497        // `"0100/s"`, `"00/s"`, `"007/h"` as `u32::from_str` parses
5498        // them losslessly (= 100, 0, 7), but `render` emits the
5499        // leading-zero-stripped form (`"100/s"`, `"0/s"`, `"7/h"`) —
5500        // a *different* canonical string on the next emit, breaking
5501        // the THEORY.md Part V render-determinism contract the same
5502        // way `"+100/s"` did before the leading-`+` arm landed. The
5503        // single-byte magnitude `"0"` itself round-trips losslessly
5504        // through `render` (`render(0)` emits `"0/s"`) — the
5505        // downstream [`AplicacaoError::PolicyRateLimitZero`] gate is
5506        // what refuses rate-zero authoring, so `"0/s"` stays in the
5507        // accepted set at this codec layer and the diagnostic
5508        // partitioning between canonical-form drift (this arm) and
5509        // semantic-zero (the downstream gate) remains stable.
5510        // Peer with the future leading-zero arms on the three peer
5511        // typed-magnitude codecs the trajectory acknowledges:
5512        // `supervisor::duration_codec`, `limits::parse_duration`,
5513        // `limits::parse_byte_size` — each carries the same
5514        // canonical-form-drift class today; this gate lands the
5515        // discipline on the fourth typed-magnitude codec in
5516        // caixa-core first because the peer `"+100/s"` arm above is
5517        // the closest predecessor on the trajectory.
5518        //
5519        // Routed through the lifted
5520        // [`crate::render::is_leading_zero_padded_magnitude`]
5521        // predicate — the same source of truth the four peer
5522        // typed-magnitude codec sites share.
5523        if crate::render::is_leading_zero_padded_magnitude(rate_trim) {
5524            return Err(format!(
5525                "rate-limit: rate {rate_trim:?} has a non-canonical leading zero — the \
5526                 canonical authoring form for `:politicas :rate-limit` is \
5527                 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
5528                 with no leading-zero padding on the magnitude. A leading-zero magnitude \
5529                 (`\"0100/s\"`, `\"00/s\"`, `\"007/h\"`) round-trips through `render` to \
5530                 a *different* canonical form (`\"100/s\"`, `\"0/s\"`, `\"7/h\"`) on \
5531                 first serialize — breaking the THEORY.md Part V render-determinism \
5532                 contract every typed slot carries. Strip the leading zeros (write \
5533                 `\"100/s\"` instead of `\"0100/s\"`)"
5534            ));
5535        }
5536        // The digit-only gate guarantees every byte is `[0-9]`, and
5537        // the leading-zero arm above guarantees the magnitude is
5538        // either the single byte `"0"` or starts with `[1-9]`, so
5539        // the only way `u32::from_str` can fail here is overflow
5540        // (the magnitude exceeds `u32::MAX`). Surface that with an
5541        // overflow-shaped wording so the diagnostic names the
5542        // offending magnitude verbatim rather than collapsing onto
5543        // the non-canonical arm. Same shape
5544        // `supervisor::duration_codec` (1c55a2a) carries on the peer
5545        // duration-codec axis.
5546        let rate: u32 = rate_trim.parse::<u32>().map_err(|_| {
5547            format!("rate-limit rate {rate_trim:?} (digit-only magnitude overflows u32)")
5548        })?;
5549        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives on
5550        // the closed-set typed enum [`super::RateLimitUnit`]; this parse
5551        // arm reads the `&str → Duration` projection through the
5552        // substrate primitive [`super::RateLimitUnit::window_from_suffix`]
5553        // (a two-step typed dispatch composing [`super::RateLimitUnit::from_suffix`]
5554        // with [`super::RateLimitUnit::window`]) rather than the vestigial
5555        // module-private `rate_limit_window_from_unit` free helper the
5556        // predecessor 61421a6 left as the last unlifted delegate on this
5557        // axis. One typed dispatch on the substrate primitive instead of
5558        // one runtime call through the free-helper delegate; the sole
5559        // production consumer of the `&str → Duration` axis (this parse
5560        // arm) now reaches for exactly one typed method on the closed-set
5561        // enum, sibling to the codec's render arm's
5562        // [`super::RateLimit::canonical_unit`] dispatch on the paired
5563        // `Duration → RateLimitUnit` axis and to the validate gate's
5564        // [`super::RateLimit::canonical_unit`] shape-probe on the
5565        // canonical-window axis. A future rate-limit-unit addition (a
5566        // `"d"` day suffix once Envoy's `rate_limit_action` grows
5567        // daily-bucket support, a `"ms"` sub-second window once
5568        // high-throughput per-edge policies come into scope per
5569        // MESH-COMPOSITION §III.2 #3) is one variant + one arm per method
5570        // on the closed-set enum, and the compiler enforces exhaustiveness
5571        // on every consumer's `match self` arms — this parse arm's
5572        // accepted-suffix set, the render arm's emitted-suffix set, the
5573        // validate gate's canonical-window set, and every future
5574        // per-`:contratos`-edge rate-limit-override overlay all pick it up
5575        // by construction.
5576        let unit = unit.trim();
5577        let window = RateLimitUnit::window_from_suffix(unit)
5578            .ok_or_else(|| format!("unknown rate-limit window unit {unit:?}"))?;
5579        Ok(RateLimit { rate, window })
5580    }
5581
5582    fn render(rl: RateLimit) -> String {
5583        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
5584        // module scope on the closed-set typed enum [`super::RateLimitUnit`];
5585        // this render arm reads the `Duration → RateLimitUnit` projection
5586        // through the substrate primitive [`super::RateLimit::canonical_unit`]
5587        // (returns `None` on every non-canonical window — the sub-second /
5588        // non-`{1, 60, 3600}` shapes the validate gate rejects), then
5589        // formats the returned typed enum through its
5590        // [`std::fmt::Display`] impl (which routes through
5591        // [`super::RateLimitUnit::as_suffix`]). Two typed dispatches on
5592        // the substrate primitive instead of one runtime `find_map`
5593        // walk through the free-helper delegate chain
5594        // [`super::rate_limit_window_unit`] (the vestigial free helper's
5595        // sole production consumer was this arm; every other consumer of
5596        // the `Duration → unit` axis — the validate gate below and the
5597        // future M4 per-Aplicacao Envoy config reconciler — now reads
5598        // the same typed method).
5599        //
5600        // A future rate-limit-unit addition (a `"d"` day suffix once
5601        // Envoy's `rate_limit_action` grows daily-bucket support) is
5602        // one variant + one arm per method on the closed-set enum, and
5603        // the compiler enforces exhaustiveness on every consumer's
5604        // `match self` arms — the codec's `parse` accepted-suffix set,
5605        // this render arm's emitted-suffix set, the validate gate's
5606        // canonical-window set, and every future per-`:contratos`-edge
5607        // rate-limit-override overlay all pick it up by construction.
5608        if let Some(unit) = rl.canonical_unit() {
5609            format!("{}/{unit}", rl.rate())
5610        } else {
5611            // Defensive fallback for non-canonical windows. Note:
5612            // [`AplicacaoSpec::validate_politicas`] rejects any
5613            // non-canonical `:rate-limit :window` via
5614            // [`AplicacaoError::PolicyRateLimitWindowNotCanonical`], so
5615            // a validated `RateLimit` never reaches this branch. The
5616            // emitted `<n>/<k>s` form is *not* round-trippable through
5617            // [`parse`] (which accepts only the closed-set
5618            // [`super::RateLimitUnit`] suffixes, not `<k>s` with an
5619            // explicit count) — the validate gate is what makes the
5620            // round-trip a structural property; this branch exists only
5621            // so a programmatic non-validated serialize doesn't panic.
5622            format!("{}/{}s", rl.rate(), rl.window().as_secs())
5623        }
5624    }
5625}
5626
5627// ── placement strategy ───────────────────────────────────────────────
5628
5629/// How the Aplicacao distributes across clusters. Three options:
5630///
5631/// - `SingleNode` — one cluster runs the app at a time; takeover on
5632///   death (Erlang/OTP distributed-app semantics).
5633/// - `Replicated` — every named cluster runs an instance (active-active).
5634/// - `Sharded` — entities distribute by hash key across clusters
5635///   (Akka cluster sharding).
5636#[derive(
5637    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
5638)]
5639pub enum PlacementStrategy {
5640    SingleNode,
5641    Replicated,
5642    Sharded,
5643}
5644
5645/// Substrate-canonical M3-mesh-shaped per-`:placement :estrategia`
5646/// distribution-strategy default for the `:placement :estrategia` axis —
5647/// the [`PlacementStrategy::Replicated`] active-active-across-every-named-
5648/// cluster arm (MESH-COMPOSITION §II.2), extracted as a typed `pub const`
5649/// so every substrate-side consumer that resolves "what
5650/// [`PlacementStrategy`] variant does an author-omitted `:placement
5651/// :estrategia` slot degrade onto?" reaches for exactly one substrate-
5652/// primitive [`PlacementStrategy`].
5653///
5654/// The `:placement :estrategia` default axis has three production
5655/// consumers on the substrate side today: the [`Default for
5656/// PlacementStrategy`] impl's return arm, the [`Default for Placement`]
5657/// impl's struct-literal `estrategia` field, and the serde-side
5658/// `#[serde(default)]` on [`Placement::estrategia`] that resolves an
5659/// author-omitted `:placement :estrategia` scalar through the [`Default
5660/// for PlacementStrategy`] impl. Prior to this lift the three folded onto
5661/// a raw `Self::Replicated` arm at the [`Default for PlacementStrategy`]
5662/// impl and implicit `PlacementStrategy::default()` routes at the sibling
5663/// consumers, with no compile-time link back to the paired
5664/// [`crate::manifest::Caixa::aplicacao_view`] fold's
5665/// `.unwrap_or_default()` `Option<Placement>` collapse arm — the fourth
5666/// production consumer that resolves an author-omitted `:placement` slot
5667/// (entirely omitted, not just the `:estrategia` scalar within a declared
5668/// `:placement` block) through [`Placement::default`] which then routes
5669/// through this same discriminator. A future coherent rebrand of the
5670/// `:placement :estrategia` default (a widening to `Sharded` once the
5671/// substrate discovers hash-keyed distribution as the more common
5672/// production shape, a tightening to `SingleNode` for stateful Erlang/OTP
5673/// distributed-app-takeover semantics MESH-COMPOSITION §II.1 already
5674/// names, a per-cluster overlay the operator pins through a future
5675/// `:placement-overrides` slot) would have had to migrate a lifted
5676/// discriminator on one path and open-coded discriminators on the peers
5677/// in lockstep or the four consumers would silently drift out of
5678/// pairing. Lifting the resolution rule to a typed `pub const` on the
5679/// substrate primitive means the M3-mesh-canonical `:placement
5680/// :estrategia` default migrates as one unit on any future axis change.
5681///
5682/// The [`PlacementStrategy::Replicated`] value pins MESH-COMPOSITION
5683/// §II.2's active-active-across-every-named-cluster arm — the closest
5684/// canonical M3 production reference the substrate carries, matching the
5685/// caixa-mesh default axis every M3 renderer already keys off (a
5686/// `programs.yaml` fan-out that emits one `HelmRelease` per cluster is
5687/// the canonical shape a `:membros`+`:contratos`-declared Aplicacao lands on
5688/// under the substrate's fleet-programs aggregator without an explicit
5689/// `:placement :estrategia` override). The two alternatives the closed
5690/// [`PlacementStrategy::ALL`] accept-set carries
5691/// ([`PlacementStrategy::SingleNode`] — Erlang/OTP distributed-app
5692/// takeover, MESH-COMPOSITION §II.1; [`PlacementStrategy::Sharded`] —
5693/// Akka-style hash-keyed distribution across clusters,
5694/// MESH-COMPOSITION §II.4) express deliberate takeover / hash-keyed
5695/// postures an author declares explicitly, never a posture an omitted
5696/// slot should silently assume.
5697///
5698/// Lifted as a typed `pub const` so the M3-mesh-canonical default has
5699/// exactly one source of truth on the `:placement :estrategia` axis, on
5700/// the same substrate-primitive lift discipline the sibling M2
5701/// per-supervisor default set carries
5702/// ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`],
5703/// [`crate::supervisor::SUPERVISOR_MAX_RESTARTS_DEFAULT`],
5704/// [`crate::supervisor::SUPERVISOR_RESTART_WINDOW_DEFAULT`],
5705/// [`crate::supervisor::SUPERVISOR_CHILD_RESTART_DEFAULT`]) and the peer
5706/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes
5707/// ([`crate::render::DEFAULT_NAMESPACE`],
5708/// [`crate::render::DEFAULT_LIBRARY_NAME`],
5709/// [`crate::render::DEFAULT_SERVICO_PORT`]). The first typed default on
5710/// the M3 mesh-primitive-defining slot family to converge onto the
5711/// substrate-primitive-lift discipline the M2 supervisor-slot family
5712/// already carries end-to-end.
5713pub const PLACEMENT_ESTRATEGIA_DEFAULT: PlacementStrategy = PlacementStrategy::Replicated;
5714
5715impl Default for PlacementStrategy {
5716    fn default() -> Self {
5717        // Route the [`Default for PlacementStrategy`] impl through the
5718        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
5719        // `pub const` rather than a raw `Self::Replicated` arm — one
5720        // source of truth for the M3-mesh-canonical active-active-
5721        // across-every-named-cluster `:placement :estrategia` default
5722        // (MESH-COMPOSITION §II.2), on the same substrate-primitive
5723        // lift discipline the sibling M2 per-supervisor default set
5724        // ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`] +
5725        // paired halves) carries end-to-end. Pinned by
5726        // `placement_strategy_default_routes_through_lifted_default`.
5727        PLACEMENT_ESTRATEGIA_DEFAULT
5728    }
5729}
5730
5731impl PlacementStrategy {
5732    /// Exhaustive iteration surface for every consumer that reads the
5733    /// full closed-set (the future M4 admission-webhook's accepted-
5734    /// strategy listing in its rejection body, a future `feira app
5735    /// placement --list` CLI-side surfacing of the accepted arm-set,
5736    /// any future round-trip fuzz harness). A future variant addition
5737    /// (an `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint
5738    /// names as a trajectory item) extends this slice as a single edit
5739    /// and every consumer picks up the new entry by construction — the
5740    /// compiler-checked exhaustiveness on the sibling method `match`
5741    /// arms is the build-time guarantee that no arm forgets to grow.
5742    /// Same shape as the sibling closed-set typed enums'
5743    /// [`RateLimitUnit::ALL`] (6bce03d) and
5744    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
5745    /// surfaces — the third closed-set typed enum on the caixa surface
5746    /// to converge onto the same discipline.
5747    pub const ALL: &'static [Self] = &[Self::SingleNode, Self::Replicated, Self::Sharded];
5748
5749    /// Canonical camelCase-schema discriminator scalar this variant
5750    /// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
5751    /// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
5752    /// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5753    /// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
5754    /// every substrate consumer that dispatches on the strategy (the
5755    /// `lareira-fleet-programs` aggregator, the future `app-operator`
5756    /// reconciler, the M3 Adaptive compression pass) reads the same
5757    /// byte-string the `Serialize` derive emits — the pin test in
5758    /// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
5759    /// asserts the two paths agree.
5760    #[must_use]
5761    pub const fn as_str(self) -> &'static str {
5762        match self {
5763            Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
5764            Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
5765            Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
5766        }
5767    }
5768
5769    /// Substrate-canonical reverse projection on the `:placement
5770    /// :estrategia` closed-set axis — parses the camelCase-schema
5771    /// discriminator scalar back to the typed variant, or `None` when
5772    /// `s` is outside the closed-set arm-string set [`Self::as_str`]
5773    /// emits. Dispatches on the same lifted
5774    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
5775    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5776    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] constants the
5777    /// [`Self::as_str`] emitter walks, so the parse and emit halves of
5778    /// the round-trip migrate through one caixa-core edit on any future
5779    /// arm addition (an `Anycast` mesh-anycast arm the MESH-COMPOSITION
5780    /// §II.5 hint names as a trajectory item lands one variant + one
5781    /// arm per method and the compiler enforces exhaustiveness on every
5782    /// consumer's `match self` arms).
5783    ///
5784    /// Prior to this lift the substrate carried only the forward
5785    /// `Self → &str` projection (the [`Self::as_str`] emitter, the
5786    /// [`std::fmt::Display`] impl routed through it, the `Serialize`
5787    /// derive that emits the same byte-string under
5788    /// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]) — every non-serde
5789    /// consumer that wanted to parse a wire-form strategy scalar had to
5790    /// re-inline a three-arm `match s { "SingleNode" => …, "Replicated"
5791    /// => …, "Sharded" => …, _ => … }` cascade that expressed no
5792    /// compile-time link back to the typed variant's canonical lifted
5793    /// constant. A future variant rename or a per-arm serde-attribute
5794    /// drift would silently split the wire byte-string one non-serde
5795    /// consumer parsed from the one the emitter wrote, with the
5796    /// failure surfacing at parse time far from the rebrand commit.
5797    ///
5798    /// Same closed-set-reverse-projection discipline the sibling
5799    /// [`crate::CaixaKind::from_wire`] (2aa6d23) and
5800    /// [`RateLimitUnit::from_suffix`] typed enums carry on the peer
5801    /// wire-side `str → Self` axes — extended onto the M3 mesh-primitive-
5802    /// defining `:placement :estrategia` closed-set axis, the third
5803    /// substrate-side closed-set typed enum to converge on the two-way
5804    /// `str ↔ Self` round-trip. Method-named `from_wire` (not `from_str`)
5805    /// to match the peer [`crate::CaixaKind::from_wire`] shape verbatim
5806    /// and side-step the [`std::str::FromStr`]-collision clippy
5807    /// (`clippy::should_implement_trait`) the plain `from_str` name
5808    /// carries; a future explicit [`std::str::FromStr`] impl can layer
5809    /// on top by delegating to this canonical arm-dispatch method.
5810    ///
5811    /// Returns `Option<Self>` (rather than `Result<Self, _>`) to match
5812    /// the sibling [`crate::CaixaKind::from_wire`] shape: the caller
5813    /// picks the diagnostic form appropriate for its use site — a
5814    /// future `feira app placement --set` CLI-side arg-parse that wants
5815    /// an `"unknown strategy: {s} (accepted: SingleNode, Replicated,
5816    /// Sharded)"` diagnostic builds one on top by iterating
5817    /// [`Self::ALL`], while the future M4 admission-webhook's rejection
5818    /// path folds `None` onto its per-CR structured refusal body.
5819    #[must_use]
5820    pub fn from_wire(s: &str) -> Option<Self> {
5821        match s {
5822            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE => Some(Self::SingleNode),
5823            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED => Some(Self::Replicated),
5824            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED => Some(Self::Sharded),
5825            _ => None,
5826        }
5827    }
5828
5829    /// Substrate-canonical per-arm predicate naming the cross-slot
5830    /// `:placement :estrategia` ↔ `:placement :shard-key` invariant on the
5831    /// closed-set typed [`PlacementStrategy`] enum: `true` iff the strategy
5832    /// consumes the paired [`Placement::shard_key`] axis (and therefore
5833    /// requires — and is the only strategy that permits — a non-empty
5834    /// `:shard-key` on the paired slot). Today the accept-set is the
5835    /// singleton `{Sharded}` — `Sharded` is the sole Akka-style
5836    /// hash-keyed distribution arm (MESH-COMPOSITION §II.4) that keys off a
5837    /// per-entity extractor expression; `SingleNode` (Erlang/OTP
5838    /// distributed-app takeover — §II.1) and `Replicated` (active-active
5839    /// across every named cluster) have no hash-keyed routing axis to
5840    /// consume the slot and refuse a declared-but-inert `:shard-key`
5841    /// through [`AplicacaoError::ShardKeyOnNonSharded`].
5842    ///
5843    /// Every validated [`Placement`] past [`AplicacaoSpec::validate_placement`]
5844    /// satisfies `placement.shard_key().is_some() ==
5845    /// placement.estrategia().requires_shard_key()` by construction — the
5846    /// cross-slot partition the pin
5847    /// [`tests::validate_placement_admits_paired_shape_iff_strategy_requires_shard_key`]
5848    /// locks load-bearing, so every downstream consumer that reaches for
5849    /// the paired shape (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
5850    /// CR materializer's per-CR shard-key resolver, the future
5851    /// [`feira app graph --shard-key`] per-Aplicacao column, the future
5852    /// per-cluster Akka-style cluster-sharding reconciler's per-entity
5853    /// hash-routing gate, the M5 adaptive-placement engine's per-strategy
5854    /// shard-key requirement probe, a future author-facing tatara-lisp
5855    /// linter that flags `(:placement (:estrategia Replicated :shard-key
5856    /// "tenantId"))` shapes before `feira lint` reaches
5857    /// [`AplicacaoSpec::validate`]) can reach for one typed dispatch on
5858    /// the substrate primitive — the predicate names *the cross-slot
5859    /// invariant*, not the arm identity.
5860    ///
5861    /// Prior to this lift the "does this strategy consume `:shard-key`"
5862    /// classification lived under the `gen_platform::IsVariant`-derived
5863    /// [`Self::is_sharded`] predicate at three fixture-builder sites in
5864    /// this crate (the [`tests::placement_strategy_variants_round_trip`]
5865    /// per-variant `Placement`-builder's `if s.is_sharded() { Some("$key"…)
5866    /// } else { None }` cascade, the
5867    /// [`tests::estrategia_returns_placement_estrategia_verbatim_across_permutations`]
5868    /// per-variant `Placement`-builder's `estrategia.is_sharded().then(||
5869    /// "tenantId".to_string())` cascade, and the
5870    /// [`tests::validate_placement_reads_through_lifted_estrategia_accessor`]
5871    /// per-variant spec-mutator's identical `.is_sharded().then(…)`
5872    /// cascade). Each site conflated two semantically distinct questions:
5873    /// "is the variant `Sharded`?" (arm-identity, what
5874    /// [`Self::is_sharded`] answers) and "does the variant consume
5875    /// `:shard-key`?" (cross-slot-invariant, what this predicate answers).
5876    /// The two questions land on the same three-way answer under today's
5877    /// closed accept-set (both trip on the singleton `{Sharded}`), but a
5878    /// future arm addition that consumed `:shard-key` under a different
5879    /// name (a hypothetical `Anycast` mesh-anycast arm the MESH-COMPOSITION
5880    /// §II.5 roadmap-hint names that hash-partitions across the cluster
5881    /// pool by client-IP hash rather than an author-declared extractor
5882    /// expression, a hypothetical `WeightedShard` variant that carries a
5883    /// shard-key + per-cluster weight table under a promoted M5
5884    /// adaptive-placement engine) or an addition that did *not* consume
5885    /// `:shard-key` on a semantically Sharded-shaped arm would silently
5886    /// split the two questions. Any consumer that read
5887    /// `.is_sharded().then(…)` for the shard-key requirement gate would
5888    /// silently misclassify the new arm as non-consuming — a fixture
5889    /// builder would omit `:shard-key` where the new arm required one and
5890    /// [`AplicacaoSpec::validate_placement`] would refuse the fixture with
5891    /// [`AplicacaoError::ShardedWithoutKey`] far from the arm-addition
5892    /// commit, a future M4 CR materializer would fall through the
5893    /// `.is_sharded()`-only branch to the non-shard-key resolver arm and
5894    /// silently emit an empty extractor at the Akka reconciler layer.
5895    ///
5896    /// Lifting the classification as a substrate-primitive method on the
5897    /// closed-set typed enum names the cross-slot invariant on the
5898    /// primitive that owns the partition: every future arm addition
5899    /// declares its `:shard-key` consumption in one place (this predicate's
5900    /// `match self` arm-set), and every downstream consumer that reaches
5901    /// for the paired shape reads through one typed dispatch. Same
5902    /// discipline as the sibling [`WitContract::is_capability`] (7b97d26)
5903    /// per-arm predicate on the pre-projection WIT-shape axis and the
5904    /// [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
5905    /// paired predicate on the post-projection typed-view axis — a
5906    /// per-arm semantic-classification predicate paired with the
5907    /// arm-identity predicate the derive already emits, closing the drift
5908    /// footgun on the cross-slot invariant axis.
5909    ///
5910    /// Method-named `requires_shard_key` (not `has_shard_key`, not
5911    /// `is_shard_keyed`, not `takes_shard_key`) because the cross-slot
5912    /// invariant reads as "this strategy *requires* the paired
5913    /// `:shard-key` axis" — the `SingleNode`/`Replicated` arms *refuse*
5914    /// the axis through [`AplicacaoError::ShardKeyOnNonSharded`], not
5915    /// merely omit it. The `has_*` framing would read as an accessor
5916    /// (returning the presence of an already-carried value) rather than a
5917    /// requirement (naming the invariant the paired slot must satisfy).
5918    /// Returns `bool` (not `Option<()>` or a marker-type witness), same
5919    /// shape as the sibling [`WitContract::is_capability`] /
5920    /// [`Self::is_sharded`] per-arm boolean predicates on the closed-set
5921    /// arm-family, so every consumer reaches for `.requires_shard_key()`
5922    /// as a drop-in replacement for the `.is_sharded()` conflated read
5923    /// without a return-shape migration.
5924    #[must_use]
5925    pub const fn requires_shard_key(self) -> bool {
5926        match self {
5927            Self::Sharded => true,
5928            Self::SingleNode | Self::Replicated => false,
5929        }
5930    }
5931}
5932
5933// Compile-time pins on the [`PlacementStrategy::requires_shard_key`]
5934// cross-slot-invariant per-arm predicate: the module-scope const-eval
5935// assertions below trip at caixa-core build time (not test time) if a
5936// future edit rewires the predicate's arm-set away from the singleton
5937// `{Sharded}` accept-set MESH-COMPOSITION §II.4 pins. The
5938// [`tests::placement_strategy_requires_shard_key_partitions_the_arm_set`]
5939// runtime pin covers the same truth-table with a more descriptive
5940// diagnostic on failure; these const-eval items add a build-time failure
5941// surface strictly stronger than the runtime pin (a downstream renderer's
5942// `const`-context reader that composed against a rebound predicate would
5943// still surface here before the test suite even ran) and side-step the
5944// `clippy::assertions_on_constants` lint the runtime `assert!(CONST)` pin
5945// would otherwise accumulate on the caixa-core module baseline.
5946const _: () = assert!(!PlacementStrategy::SingleNode.requires_shard_key());
5947const _: () = assert!(!PlacementStrategy::Replicated.requires_shard_key());
5948const _: () = assert!(PlacementStrategy::Sharded.requires_shard_key());
5949
5950/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
5951/// the pretty-printed byte-string every consumer that formats the strategy
5952/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
5953/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
5954/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
5955/// per-Aplicacao strategy line, the future M4 CR materializer's per-
5956/// admission-webhook rejection body) reaches for the same lifted
5957/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
5958/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5959/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
5960/// `Serialize` derive already emits under
5961/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
5962/// [`PlacementStrategy::as_str`] helper already returns.
5963///
5964/// Until this lift landed the sibling OTP-shape typed enums —
5965/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
5966/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
5967/// so [`std::fmt::Display`] routes through the same discriminant string
5968/// the wire format emits) — carried a stable [`std::fmt::Display`]
5969/// surface but [`PlacementStrategy`] did not; every consumer reaching
5970/// for a strategy byte-string past the wire format had to pick between
5971/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
5972/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
5973/// derive), any two of which a future variant rename or
5974/// `#[serde(rename_all = "kebab-case")]` attribute would silently
5975/// desynchronize — with the failure surfacing as a downstream renderer /
5976/// operator's per-strategy dispatch reading one spelling while the wire
5977/// format emitted another, far from the source rebrand commit and with
5978/// no field naming the drift. Routing `Display` through
5979/// [`PlacementStrategy::as_str`] makes the three paths
5980/// (`Debug` for structural inspection, `Display` for user-facing text,
5981/// `Serialize` for the wire format) converge on the same lifted
5982/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
5983/// the diagnostic byte-string, and the pretty-printed byte-string move
5984/// as a single unit through one canonical declaration each, by
5985/// construction. Same trajectory as [`PlacementStrategy::as_str`]
5986/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
5987/// closes the third path.
5988///
5989/// Pin tests
5990/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
5991/// and
5992/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
5993/// assert the three paths agree byte-for-byte on every variant, so a
5994/// future variant rename or per-arm serde attribute drift is a build
5995/// error visible at caixa-core test time, not a silent per-consumer
5996/// dispatch miss at apply / reconcile time.
5997impl std::fmt::Display for PlacementStrategy {
5998    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5999        f.write_str(self.as_str())
6000    }
6001}
6002
6003/// Where the Aplicacao runs.
6004#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
6005#[serde(rename_all = "camelCase")]
6006pub struct Placement {
6007    /// Distribution strategy.
6008    #[serde(default)]
6009    pub estrategia: PlacementStrategy,
6010
6011    /// Named clusters that host this Aplicacao. Required for
6012    /// `Replicated` and `SingleNode`; for `Sharded` declares the
6013    /// shard pool.
6014    #[serde(default)]
6015    pub clusters: Vec<String>,
6016
6017    /// Optional hint to the placement engine: `"data-locality"`,
6018    /// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
6019    #[serde(default, skip_serializing_if = "Option::is_none")]
6020    pub affinity: Option<String>,
6021
6022    /// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
6023    #[serde(default, skip_serializing_if = "Option::is_none")]
6024    pub shard_key: Option<String>,
6025}
6026
6027impl Placement {
6028    /// Substrate-canonical per-`:placement` Akka-cluster-sharding
6029    /// `:shard-key` extractor-expression scalar accessor every consumer
6030    /// of the Aplicacao's hash-keyed distribution routing keys off —
6031    /// returns the author-declared `:placement :shard-key` byte-string
6032    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
6033    /// own `Option<String>` storage; `None` when the slot is absent
6034    /// (the canonical shape under `:estrategia Replicated` /
6035    /// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
6036    /// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
6037    /// partition — `validate` refuses any `Placement` past this call
6038    /// that lands `Some` on a non-`Sharded` strategy or `None` on
6039    /// `Sharded`).
6040    ///
6041    /// The `:placement :shard-key` slot carries the Akka-style
6042    /// cluster-sharding entity-id extractor expression
6043    /// (MESH-COMPOSITION §II.4) — validated by
6044    /// [`validate_placement_shard_key`] to be a non-empty printable-
6045    /// ASCII single-token reference (`tenantId`, `$tenantId`,
6046    /// `metadata.tenantId`, `${tenant}` — the canonical shapes the
6047    /// future M4 Akka-style cluster-sharding reconciler hashes without
6048    /// re-validating at the runtime layer), and every downstream
6049    /// consumer that reads the key keys off this scalar (the
6050    /// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
6051    /// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
6052    /// declared-but-inert refusal diagnostic, the caixa-mesh
6053    /// per-Aplicacao `placement.shardKey` emit path the substrate
6054    /// operator's per-entity hash-routing reader consumes, the future
6055    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6056    /// per-shard-key resolver).
6057    ///
6058    /// Prior to this lift the `.shard_key` field was accessed inline at
6059    /// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
6060    /// `Sharded` arm's `match &self.placement.shard_key { None => …,
6061    /// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
6062    /// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
6063    /// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
6064    /// — two open-coded field-accesses that expressed no compile-time
6065    /// link back to the typed slot. A future extension of the
6066    /// `:placement :shard-key` axis to a richer author surface — a
6067    /// per-cluster override the operator pins through a future
6068    /// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
6069    /// §II.4 roadmap acknowledges, a per-tenant extractor-expression
6070    /// alias table the M4 CR materializer resolves per-CR, a
6071    /// per-Aplicacao dynamic `:shard-key` derivation the future
6072    /// adaptive placement engine computes from `:affinity` weights —
6073    /// would have had to be threaded through both open-coded copies in
6074    /// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
6075    /// arm refusal would silently disagree on which extractor
6076    /// expression a given Placement resolves to. Lifting the resolution
6077    /// rule to a typed method on the substrate primitive means every
6078    /// downstream consumer of the Aplicacao's per-`:placement`
6079    /// hash-key surface reaches for exactly one typed dispatch — the
6080    /// resolver's accept-set migrates as a unit on any future axis
6081    /// addition.
6082    ///
6083    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
6084    /// [`WitContract::destination`] / [`WitContract::world_ref`]
6085    /// (7f0fd43, 0804823) scalar accessors, per-`:membros`
6086    /// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
6087    /// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
6088    /// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
6089    /// typed dispatch on the substrate primitive, thin projections at
6090    /// each consumer" discipline extended onto the per-`:placement`
6091    /// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
6092    /// First `Option<&str>`-return accessor on the M3 mesh-slot family
6093    /// — opens the "optional per-slot scalar" projection pattern the
6094    /// sibling per-`:placement` `:affinity`, per-`:politicas`
6095    /// `:rate-limit` future lifts fold on. Named `shard_key()` to
6096    /// match the storage field's name; the accessor's identity name
6097    /// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
6098    /// slot's docstring already carries.
6099    #[must_use]
6100    pub const fn shard_key(&self) -> Option<&str> {
6101        match &self.shard_key {
6102            Some(s) => Some(s.as_str()),
6103            None => None,
6104        }
6105    }
6106
6107    /// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
6108    /// compression-hint scalar accessor every weighting-consumer of the
6109    /// Aplicacao's per-hint routing surface keys off — returns the
6110    /// author-declared `:placement :affinity` byte-string verbatim as
6111    /// an `Option<&str>`, borrowed from the typed slot's own
6112    /// `Option<String>` storage; `None` when the slot is absent (the
6113    /// canonical shape of an Aplicacao that leaves the compression
6114    /// weighting up to the placement engine's cluster-default arm — no
6115    /// author-authored `data-locality` / `low-latency` / etc. hint
6116    /// biases the routing).
6117    ///
6118    /// The `:placement :affinity` slot carries the M3 Adaptive-
6119    /// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
6120    /// by [`validate_placement_affinity`] to be a DNS-1123 label
6121    /// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
6122    /// K8s-conformant label-selector shape every apiserver-side pod-
6123    /// affinity / node-affinity materializer already gates on
6124    /// admission), and every downstream consumer that reads the hint
6125    /// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
6126    /// per-hint value-shape gate, the caixa-mesh per-Aplicacao
6127    /// `placement.affinity` overlay emit path the substrate operator's
6128    /// per-hint weighting-consumer reads, the future M4
6129    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
6130    /// pod-affinity / node-affinity selector resolver).
6131    ///
6132    /// Prior to this lift the `.affinity` field was accessed inline at
6133    /// the sole caixa-core site — the
6134    /// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
6135    /// `if let Some(a) = &self.placement.affinity { …
6136    /// validate_placement_affinity(a)? … }` cascade — one open-coded
6137    /// field-access that expressed no compile-time link back to the
6138    /// typed slot. A future extension of the `:placement :affinity`
6139    /// axis to a richer author surface — a per-cluster override the
6140    /// operator pins through a future `:placement :affinity-overrides`
6141    /// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
6142    /// tenant hint alias table the M4 CR materializer resolves per-CR,
6143    /// a per-Aplicacao dynamic `:affinity` derivation the future
6144    /// adaptive placement engine computes from `:clusters` topology —
6145    /// would have had to be threaded through the open-coded copy in
6146    /// lockstep with any future caixa-mesh / caixa-flux / M4 CR
6147    /// materializer reader that landed on the axis, or the per-hint
6148    /// value-shape gate and its downstream weighting consumers would
6149    /// silently disagree on which hint a given Placement resolves to.
6150    /// Lifting the resolution rule to a typed method on the substrate
6151    /// primitive means every downstream consumer of the Aplicacao's
6152    /// per-`:placement` compression-hint surface reaches for exactly
6153    /// one typed dispatch — the resolver's accept-set migrates as a
6154    /// unit on any future axis addition.
6155    ///
6156    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
6157    /// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
6158    /// optional-scalar axis — same "one typed dispatch on the substrate
6159    /// primitive, thin projections at each consumer" discipline extended
6160    /// onto the per-`:placement` M3-Adaptive-compression-hint
6161    /// `Option<String>` optional-scalar axis. Second `Option<&str>`-
6162    /// return accessor on the M3 mesh-slot family; closes the last
6163    /// un-lifted per-`:placement` `Option<String>` axis. Named
6164    /// `affinity()` to match the storage field's name; the accessor's
6165    /// identity name maps onto the canonical MESH-COMPOSITION §II.4
6166    /// vocabulary the slot's docstring already carries.
6167    #[must_use]
6168    pub const fn affinity(&self) -> Option<&str> {
6169        match &self.affinity {
6170            Some(s) => Some(s.as_str()),
6171            None => None,
6172        }
6173    }
6174
6175    /// Substrate-canonical per-`:placement` `:estrategia` distribution-
6176    /// strategy scalar accessor every consumer that dispatches on the
6177    /// Aplicacao's per-cluster distribution shape keys off — returns the
6178    /// author-declared `:placement :estrategia` variant verbatim as a
6179    /// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
6180    /// `PlacementStrategy` storage.
6181    ///
6182    /// The `:placement :estrategia` slot carries the closed-set
6183    /// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
6184    /// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
6185    /// `Replicated` — active-active across every named cluster; `Sharded`
6186    /// — Akka-style hash-keyed entity distribution across the cluster pool
6187    /// per §II.4) that every downstream consumer of the Aplicacao's
6188    /// per-cluster fan-out shape keys off. Validated by
6189    /// [`AplicacaoSpec::validate_placement`] to be paired coherently with
6190    /// the sibling `:shard-key` axis (`shard_key.is_some() ==
6191    /// matches!(estrategia, Sharded)` — the cross-slot partition the
6192    /// [`Placement::shard_key`] accessor's docstring pins), and every
6193    /// downstream consumer that reads the strategy keys off this scalar
6194    /// (the [`AplicacaoSpec::validate_placement`]
6195    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
6196    /// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
6197    /// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
6198    /// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
6199    /// declared-but-inert refusal's
6200    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
6201    /// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
6202    /// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
6203    /// emit path the substrate operator's per-strategy fan-out reader
6204    /// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
6205    /// materializer's per-strategy admission-webhook resolver).
6206    ///
6207    /// Prior to this lift the `.estrategia` field was accessed inline at
6208    /// four sites — the [`AplicacaoSpec::validate_placement`]
6209    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
6210    /// `estrategia: self.placement.estrategia`, the same method's
6211    /// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
6212    /// partition dispatch, the non-`Sharded`-arm
6213    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
6214    /// `estrategia: self.placement.estrategia`, and the `feira app graph`
6215    /// per-Aplicacao strategy print line at
6216    /// `println!("… {} …", spec.placement.estrategia, …)`
6217    /// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
6218    /// expressed no compile-time link back to the typed slot. A future
6219    /// extension of the `:placement :estrategia` axis to a richer author
6220    /// surface (a per-cluster override the operator pins through a future
6221    /// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
6222    /// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
6223    /// materializer resolves per-CR, a per-Aplicacao dynamic strategy
6224    /// derivation the future adaptive placement engine computes from
6225    /// `:affinity` + `:clusters` topology) would have had to be threaded
6226    /// through every open-coded copy in lockstep — one consumer reading
6227    /// the raw variant while a peer read the operator-resolved variant
6228    /// would silently split the `PlacementWithoutClusters` /
6229    /// `ShardKeyOnNonSharded` diagnostic quotes from the actual
6230    /// partition-dispatch input, a two-consumer split at the validator
6231    /// far from the source `caixa.lisp` with no field naming the
6232    /// strategy-drift root cause. Lifting the resolution rule to a typed
6233    /// method on the substrate primitive means every downstream consumer
6234    /// of the Aplicacao's per-`:placement` distribution-strategy surface
6235    /// reaches for exactly one typed dispatch — the resolver's accept-set
6236    /// migrates as a unit on any future axis addition.
6237    ///
6238    /// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
6239    /// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
6240    /// same "one typed dispatch on the substrate primitive, thin
6241    /// projections at each consumer" discipline extended onto the
6242    /// per-`:placement` distribution-strategy `Copy`-composite-enum
6243    /// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
6244    /// family; first `Copy`-return accessor on the M3 mesh-slot
6245    /// `Placement` type — companion to the sibling per-`:placement`
6246    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
6247    /// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
6248    /// optional-scalar axes, closing the last unlifted per-`:placement`
6249    /// scalar-value axis (the closed-set `PlacementStrategy`
6250    /// distribution-strategy discriminator) so every downstream
6251    /// per-`:placement` reader now routes through a typed dispatch on
6252    /// the substrate primitive. Named `estrategia()` to match the storage
6253    /// field's name; the accessor's identity name maps onto the
6254    /// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
6255    /// already carries. Declared `pub const fn` (matching the peer M3
6256    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
6257    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
6258    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
6259    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
6260    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
6261    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
6262    /// [`RateLimit`] — every one a `pub const fn`) so every future
6263    /// substrate-side `const`-context consumer of the resolved
6264    /// distribution-strategy variant (a `const _: () = assert!(…)`
6265    /// module-scope invariant pin on a per-fixture typed [`Placement`],
6266    /// a future M4 admission-webhook `const fn` resolver over a typed
6267    /// [`Placement`], any `const fn` composer that fans on the strategy
6268    /// at compile time) reaches through the same typed dispatch on the
6269    /// substrate primitive at const-eval time as at runtime. Pinned by
6270    /// [`placement_estrategia_accessor_is_const_fn`] which witnesses the
6271    /// const-eval posture at module scope via `const _:() = …` items so
6272    /// any future accidental downgrade to non-`const` trips at caixa-core
6273    /// build time.
6274    #[must_use]
6275    pub const fn estrategia(&self) -> PlacementStrategy {
6276        self.estrategia
6277    }
6278
6279    /// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
6280    /// per-cluster distribution-target slice accessor every consumer that
6281    /// walks the Aplicacao's declared cluster-pool keys off — returns the
6282    /// author-declared `:placement :clusters` `Vec<String>` verbatim as a
6283    /// `&[String]` slice-view, borrowed from the typed slot's own
6284    /// `Vec<String>` storage (a zero-copy slice-view over the same
6285    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
6286    /// through). Non-optional: the empty slice is the load-bearing
6287    /// pre-validation sentinel every downstream consumer of the paired
6288    /// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
6289    /// off — every strategy in the closed
6290    /// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
6291    /// requires a non-empty list (`SingleNode` / `Replicated` use the
6292    /// list as hosting / takeover candidates per Erlang/OTP distributed-
6293    /// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
6294    /// shard pool per Akka cluster-sharding convention, §II.4), so the
6295    /// `.is_empty()` probe is the shared pre-condition every
6296    /// [`AplicacaoSpec::validate_placement`] arm heads on.
6297    ///
6298    /// The `:placement :clusters` slot carries the K8s-conformant DNS-
6299    /// 1123-label per-cluster distribution-target list — the same
6300    /// set-not-multiset shape the sibling `:membros :caixa` /
6301    /// `:children :caixa` axes carry (`validate_placement`'s per-entry
6302    /// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
6303    /// pins the shape). Every downstream consumer that fans on the list
6304    /// keys off this slice (the [`AplicacaoSpec::validate_placement`]
6305    /// pre-flight `.is_empty()` probe that trips
6306    /// [`AplicacaoError::PlacementWithoutClusters`], the same method's
6307    /// per-cluster value-shape + duplicate-detection fan-out loop, the
6308    /// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
6309    /// that materializes the list verbatim onto every
6310    /// programs.yaml entry the substrate operator's per-cluster
6311    /// `placement.clusters | contains .Values.cluster` filter reads,
6312    /// the `feira app graph` per-Aplicacao cluster print line, the
6313    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6314    /// per-cluster admission-webhook fan-out, the future M5 adaptive-
6315    /// placement engine's cluster-topology reader).
6316    ///
6317    /// Prior to this lift the `.clusters` `Vec<String>` was accessed
6318    /// inline at three production sites — the
6319    /// [`AplicacaoSpec::validate_placement`] pre-flight
6320    /// `self.placement.clusters.is_empty()` refusal probe, the same
6321    /// method's per-cluster validate loop's
6322    /// `for c in &self.placement.clusters` traversal head, and the
6323    /// `feira app graph` per-Aplicacao print line's
6324    /// `spec.placement.clusters` `{:?}` formatter argument
6325    /// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
6326    /// that expressed no compile-time link back to the typed slot. A
6327    /// future extension of the `:placement :clusters` axis to a richer
6328    /// author surface (a per-tenant cluster-pool overlay the operator
6329    /// pins through a future `:placement :clusters-overrides` slot the
6330    /// MESH-COMPOSITION §V cross-cluster-federation roadmap
6331    /// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
6332    /// the future M5 adaptive-placement engine computes from
6333    /// `:affinity` weights + live cluster-topology probes, a promotion
6334    /// of the plain `Vec<String>` to a richer `{static, dynamic}`
6335    /// partition once the substrate operator's cluster-membership
6336    /// reconciler comes into typed scope) would have had to be threaded
6337    /// through all three open-coded copies in lockstep or one consumer
6338    /// would silently disagree with the peers on which cluster-pool a
6339    /// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
6340    /// reading the raw slot while the peer per-cluster validate loop
6341    /// read an operator-resolved slot would silently split the paired
6342    /// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
6343    /// `PlacementClusterDuplicate` refusal cascade's actual traversal
6344    /// input from the pre-flight input, a three-consumer split at the
6345    /// validator and formatter far from the source `caixa.lisp` with
6346    /// no field naming the cluster-pool-drift root cause. Lifting the
6347    /// resolution rule to a typed method on the substrate primitive
6348    /// means every downstream consumer of the Aplicacao's
6349    /// per-`:placement` cluster-pool surface reaches for exactly one
6350    /// typed dispatch — the resolver's accept-set migrates as a unit
6351    /// on any future axis addition.
6352    ///
6353    /// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
6354    /// slot — sibling to the seed M2
6355    /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
6356    /// slice-return accessor on the peer per-`:supervisor` static-
6357    /// child-list `Vec`-carry axis, extended onto the first M3 mesh-
6358    /// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
6359    /// primitive, thin projections at each consumer" discipline. The
6360    /// three peer `Vec`-carry axes still unlifted at the time of this
6361    /// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
6362    /// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
6363    /// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
6364    /// [`crate::UpgradeFromEntry::instructions`]
6365    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
6366    /// — inherit this accessor's discipline as future compounding runs
6367    /// migrate their consumers onto the shared slice-return shape.
6368    /// Fourth (and final) accessor on the M3 mesh-slot `Placement`
6369    /// type, sibling to the two `Option<&str>`-return
6370    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
6371    /// (74ec2d3) accessors and the `Copy`-return
6372    /// [`Placement::estrategia`] (921fe1b) accessor — closes the last
6373    /// unlifted per-`:placement` field axis (the `Vec<String>`
6374    /// distribution-target-list carrier) so every downstream
6375    /// per-`:placement` reader now routes through a typed dispatch on
6376    /// the substrate primitive. Named `clusters()` to match the storage
6377    /// field's name verbatim and the tatara-lisp author-surface term
6378    /// (`:clusters`) the field's own docstring already carries; the
6379    /// accessor's identity maps onto the canonical MESH-COMPOSITION
6380    /// §II.1 / §II.4 vocabulary the slot's docstring already reaches
6381    /// for. Returns `&[String]` (not `&Vec<String>`) because every
6382    /// downstream consumer of the cluster list treats it as a read-only
6383    /// sequence — the slice-view is the narrowest borrow that supports
6384    /// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
6385    /// `.len()`) without leaking the backing `Vec`'s
6386    /// grow/push/reserve surface that no consumer of the typed view
6387    /// reaches for (the storage-side `Vec` remains reachable through
6388    /// the `pub clusters` field for the mutation-carrying serde
6389    /// round-trip and per-test fixture-mutation paths).
6390    #[must_use]
6391    pub const fn clusters(&self) -> &[String] {
6392        self.clusters.as_slice()
6393    }
6394}
6395
6396impl Default for Placement {
6397    fn default() -> Self {
6398        Self {
6399            // Route the struct-literal `estrategia` default arm through
6400            // the substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`]
6401            // typed `pub const` rather than the transitively-derived
6402            // [`PlacementStrategy::default`] route — one source of truth
6403            // for the M3-mesh-canonical [`PlacementStrategy::Replicated`]
6404            // active-active-across-every-named-cluster arm
6405            // (MESH-COMPOSITION §II.2) that both this struct-literal
6406            // altitude and the sibling [`Default for PlacementStrategy`]
6407            // impl already key off through the same substrate primitive.
6408            // Pinned by
6409            // `placement_default_estrategia_routes_through_lifted_default`.
6410            estrategia: PLACEMENT_ESTRATEGIA_DEFAULT,
6411            clusters: Vec::new(),
6412            affinity: None,
6413            shard_key: None,
6414        }
6415    }
6416}
6417
6418// ── external entry point ─────────────────────────────────────────────
6419
6420/// External entry point — what an outside caller sees. Renders to a
6421/// Gateway / Ingress + a route to the named member Servico.
6422#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
6423#[serde(rename_all = "camelCase")]
6424pub struct Entrada {
6425    /// Public hostname (e.g. `"checkout.quero.cloud"`).
6426    pub host: String,
6427
6428    /// Member Servico the gateway routes to. Must be in `:membros`.
6429    pub para: String,
6430
6431    /// Optional path filter — if set, only matching paths route to
6432    /// this Aplicacao (the rest fall through to other route rules).
6433    #[serde(default)]
6434    pub paths: Vec<String>,
6435
6436    /// Default port on the destination Servico (the trigger.service.port).
6437    #[serde(default = "default_port")]
6438    pub port: u16,
6439}
6440
6441impl Entrada {
6442    /// Substrate-canonical per-`:entrada` URL-path fallback resolver
6443    /// every HTTPRoute-aware renderer keys off — returns the author-
6444    /// declared `:entrada :paths` list verbatim when non-empty, and the
6445    /// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
6446    /// all fallback otherwise (so an Aplicacao author who declares an
6447    /// external `:entrada` block but no per-path rule surface still
6448    /// gets a route whose sole `HTTPPathMatch` matches every incoming
6449    /// request under the paired
6450    /// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
6451    ///
6452    /// Prior to this lift the "if `:entrada :paths` is empty use the
6453    /// substrate catch-all; else return each declared path verbatim"
6454    /// cascade lived inline at
6455    /// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
6456    /// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
6457    /// per-Aplicacao HTTPRoute per-rule path-list emit site the
6458    /// substrate ships today, with no typed method on the substrate
6459    /// primitive that named the rule. A future path-resolution axis
6460    /// addition — a per-cluster `:entrada :default-path` override the
6461    /// operator pins through a future `:placement`-scoped slot, an
6462    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
6463    /// admission-webhook floor that materializes the catch-all before
6464    /// the CR lands, a future per-`:entrada :paths` overlay from a
6465    /// per-cluster policy the future `feira app deploy` pipeline
6466    /// consumes — would have to be threaded through every renderer's
6467    /// inline copy of the cascade in lockstep or one consumer would
6468    /// silently disagree with the peers on which path list a given
6469    /// `:entrada` block resolves to. Lifting the rule to a typed
6470    /// method on the substrate primitive means every downstream
6471    /// HTTPRoute-aware consumer (the M4 CR materializer, the future
6472    /// per-cluster overlay resolver, every future per-Aplicacao
6473    /// snapshot renderer) reaches for exactly one typed dispatch —
6474    /// the resolver's accept-set moves as a unit on any future axis
6475    /// addition.
6476    ///
6477    /// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
6478    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
6479    /// per-`:entrada` scalar-value axes — extends the "one typed
6480    /// dispatch on the substrate primitive, thin projections at each
6481    /// consumer" discipline onto the per-`:entrada` path-list
6482    /// resolution axis every HTTPRoute-aware renderer consumes. Same
6483    /// shape as the [`MeshPolicy::is_empty`] typed predicate on the
6484    /// sibling `:politicas` primitive — one typed method on the
6485    /// substrate primitive that names the cascade every renderer
6486    /// otherwise re-inlines.
6487    #[must_use]
6488    pub fn resolved_paths(&self) -> Vec<&str> {
6489        // Route the internal cascade-head + per-entry projection reads
6490        // through the lifted [`Self::paths`] slice accessor rather than
6491        // the raw `self.paths` field access — the substrate-primitive
6492        // per-`:entrada` path-list resolver's two internal reads now
6493        // key off the canonical raw-slot surface every downstream
6494        // per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
6495        // per-entry value-shape gate, `feira app graph`'s per-Aplicacao
6496        // entrada summary line's `{:?}` Debug print) routes through, so
6497        // any future rebrand on the typed slot's raw-slot reader lands
6498        // at exactly one place. Same two-consumer coherence discipline
6499        // the sibling `Placement::clusters` (a6e18d7) accessor pins on
6500        // the peer M3 mesh-slot `Vec<String>`-carry axis.
6501        if self.paths().is_empty() {
6502            vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
6503        } else {
6504            self.paths().iter().map(String::as_str).collect()
6505        }
6506    }
6507
6508    /// Substrate-canonical per-`:entrada` DNS-hostname singular
6509    /// accessor every Gateway-API `Listener.hostname` reader keys off
6510    /// — returns the author-declared `:entrada :host` byte-string
6511    /// verbatim as a `&str`, borrowed from the typed slot's own
6512    /// [`String`] storage.
6513    ///
6514    /// Named the "singular" half of the DNS-hostname resolver pair on
6515    /// the substrate primitive: the parent-Gateway per-listener
6516    /// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
6517    /// (`Listener.hostname: Option<PreciseHostname>` — at most one
6518    /// hostname per listener), and this accessor is the typed dispatch
6519    /// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
6520    /// reaches for. Its plural sibling [`Entrada::hostnames`] carries
6521    /// the per-HTTPRoute `spec.hostnames[]` list axis the same
6522    /// per-Aplicacao ingress-hostname surface projects onto.
6523    ///
6524    /// Prior to this lift the `entrada.host.clone()` byte-string was
6525    /// accessed inline at two `caixa-mesh` sites — the parent-Gateway
6526    /// per-listener singular `hostname:` axis
6527    /// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
6528    /// per-HTTPRoute plural `spec.hostnames[]` axis
6529    /// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
6530    /// consumers read the same `entrada.host` field but the two-site
6531    /// duplication expressed no compile-time contract that the singular
6532    /// Gateway-listener filter and the plural `HTTPRoute` filter list
6533    /// stay in lockstep on future extensions of the `:entrada` slot to
6534    /// a multi-hostname author surface (an `:entrada :alt-hosts` list
6535    /// overlay, a per-cluster SNI fan-out the operator pins through a
6536    /// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
6537    /// Aplicacao` CR materializer's per-listener virtual-host filter
6538    /// admission-webhook overlay). Any such extension would have to be
6539    /// threaded through every renderer's inline copy of the resolution
6540    /// in lockstep or the Gateway listener's `hostname:` filter would
6541    /// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
6542    /// — a Gateway-API-conformance divergence whose apply-time symptom
6543    /// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
6544    /// `NoMatchingParent` — the API server rejects the route because
6545    /// its `hostnames[]` filter doesn't intersect the parent listener's
6546    /// `hostname` filter) is far from the source `caixa.lisp` and never
6547    /// surfaces in the emitted YAML. Lifting the singular and plural
6548    /// resolvers to typed methods on the substrate primitive means
6549    /// every consumer of the Aplicacao's ingress-hostname surface
6550    /// reaches for exactly one typed dispatch, and the pair-invariant
6551    /// `hostnames() == vec![hostname()]` pinned by the sibling
6552    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
6553    /// keeps the two axes in lockstep by construction.
6554    ///
6555    /// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
6556    /// (1449891) path-list resolver on the per-HTTPRoute per-rule
6557    /// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
6558    /// the substrate primitive, thin projections at each consumer"
6559    /// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
6560    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
6561    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
6562    /// [`Entrada::resolved_paths`] lifts apply on the sibling per-
6563    /// `:entrada` scalar-value + list-value axes.
6564    #[must_use]
6565    pub const fn hostname(&self) -> &str {
6566        self.host.as_str()
6567    }
6568
6569    /// Substrate-canonical per-`:entrada` DNS-hostname plural
6570    /// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
6571    /// keys off — returns the singleton `[hostname()]` list under
6572    /// today's single-hostname-per-Aplicacao author surface, and the
6573    /// authoritative multi-hostname list under a future
6574    /// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
6575    ///
6576    /// Plural half of the DNS-hostname resolver pair — see the
6577    /// companion [`Entrada::hostname`] docstring for the two-consumer
6578    /// lift + pair-invariant discipline (`hostnames() ==
6579    /// vec![hostname()]`, pinned load-bearing by the sibling
6580    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
6581    /// test).
6582    ///
6583    /// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
6584    /// per-`:entrada` plural-list resolver on the per-HTTPRoute
6585    /// per-rule path-list axis — same `Vec<&str>` shape, same
6586    /// substrate-primitive-owns-the-resolver discipline extended to
6587    /// the per-HTTPRoute virtual-host filter-list axis.
6588    #[must_use]
6589    pub fn hostnames(&self) -> Vec<&str> {
6590        vec![self.hostname()]
6591    }
6592
6593    /// Substrate-canonical per-`:entrada` destination-Servico scalar
6594    /// accessor every Gateway-API `HTTPRoute` reader keys off — returns
6595    /// the author-declared `:entrada :para` byte-string verbatim as a
6596    /// `&str`, borrowed from the typed slot's own [`String`] storage.
6597    ///
6598    /// The `:entrada :para` slot names the single member Servico the
6599    /// external Gateway routes to (validated by
6600    /// [`AplicacaoSpec::validate`] to be a
6601    /// [`Membro::caixa`] the Aplicacao declares — a stray
6602    /// `:para` that doesn't name a member is
6603    /// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
6604    /// backend-attachment miss at cluster-apply time). Under today's
6605    /// single-destination author surface `:entrada :para` is the ingress
6606    /// apex Servico's canonical identity; under a hypothetical
6607    /// future multi-backend author surface (a `:entrada
6608    /// :split :backends` weighted-fan-out overlay for canary /
6609    /// blue-green traffic-split rollouts, per-path override for
6610    /// path-based per-Servico routing beyond the single-apex model,
6611    /// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6612    /// per-CR admission-webhook that promotes the scalar to a
6613    /// weighted list) this accessor is the substrate primitive's typed
6614    /// dispatch every downstream `HTTPRoute`-aware consumer routes
6615    /// through, so the resolution shape migrates as a unit on one
6616    /// caixa-core edit rather than a coordinated rewrite across every
6617    /// renderer's inline field-access.
6618    ///
6619    /// Prior to this lift the `entrada.para` byte-string was accessed
6620    /// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
6621    /// `metadata.name` composer's per-destination discriminator arg
6622    /// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
6623    /// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
6624    /// per-HTTPRoute per-rule `backendRefs[0].name` axis
6625    /// (`entrada.para.clone()`,
6626    /// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
6627    /// consumers read the same `entrada.para` field but the two-site
6628    /// duplication expressed no compile-time contract that the HTTPRoute
6629    /// name-discriminator and the per-rule backend name stay in
6630    /// lockstep on future extensions of the `:entrada` slot to a
6631    /// multi-destination author surface. Any such extension would have
6632    /// to be threaded through every renderer's inline copy of the
6633    /// destination projection in lockstep or the HTTPRoute
6634    /// `metadata.name` would silently reference a different destination
6635    /// than its own `backendRefs[]` — an operator-side
6636    /// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
6637    /// grep-by-name lookup would land on a route whose `backendRefs[]`
6638    /// silently point at a peer Servico, dropping every external
6639    /// `:entrada` flow at the gateway with the destination-drift root
6640    /// cause invisible in the emitted YAML.
6641    ///
6642    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
6643    /// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
6644    /// the per-listener singular / per-HTTPRoute plural filter axes and
6645    /// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
6646    /// resolver on the per-HTTPRoute per-rule matches axis. Same "one
6647    /// typed dispatch on the substrate primitive, thin projections at
6648    /// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
6649    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
6650    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
6651    /// [`Entrada::resolved_paths`] (1449891) lifts apply on the
6652    /// sibling per-`:entrada` scalar-value + list-value axes — this
6653    /// accessor closes the last unlifted per-`:entrada` scalar axis
6654    /// (the destination-Servico byte-string) so every downstream
6655    /// per-`:entrada` reader now routes through a typed dispatch on
6656    /// the substrate primitive.
6657    #[must_use]
6658    pub const fn destination(&self) -> &str {
6659        self.para.as_str()
6660    }
6661
6662    /// Substrate-canonical per-`:entrada` L4-port scalar accessor every
6663    /// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
6664    /// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
6665    /// reader keys off — returns the author-declared `:entrada :port`
6666    /// value verbatim as a `u16`, `Copy`-projected from the typed slot's
6667    /// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
6668    /// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
6669    /// [`AplicacaoError::EntradaPortZero`], not a silent
6670    /// admission-webhook rejection at cluster-apply time).
6671    ///
6672    /// The `:entrada :port` slot carries the destination Servico's
6673    /// canonical in-cluster L4 listener port (`trigger.service.port` on
6674    /// the `pleme-computeunit` library chart), and every downstream
6675    /// consumer that reads the port keys off this scalar (the
6676    /// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
6677    /// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
6678    /// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
6679    /// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
6680    /// CR materializer's per-Aplicacao gateway port resolver).
6681    ///
6682    /// Prior to this lift the `.port` field was accessed inline at two
6683    /// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
6684    /// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
6685    /// the [`AplicacaoSpec::port_for_destination`] resolver's
6686    /// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
6687    /// open-coded field-accesses that expressed no compile-time link
6688    /// back to the typed slot. A future extension of the `:entrada :port`
6689    /// axis to a richer author surface — a per-cluster override the
6690    /// operator pins through a future `:placement :default-port` slot the
6691    /// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
6692    /// `Option<u16>`-shape migration once the substrate grows per-`:membros`
6693    /// heterogeneous listener ports, an M4
6694    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
6695    /// admission-webhook floor that promotes the scalar to a
6696    /// per-destination map — would have had to be threaded through both
6697    /// open-coded copies in lockstep or the structural-floor validator
6698    /// and the [`AplicacaoSpec::port_for_destination`] resolver would
6699    /// silently disagree on which port a given [`Entrada`] resolves to.
6700    /// Lifting the resolution rule to a typed method on the substrate
6701    /// primitive means every downstream consumer of the Aplicacao's
6702    /// per-`:entrada` L4-port surface reaches for exactly one typed
6703    /// dispatch — the resolver's accept-set migrates as a unit on any
6704    /// future axis addition.
6705    ///
6706    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
6707    /// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
6708    /// accessors on the per-`:entrada` scalar-value axis — same "one
6709    /// typed dispatch on the substrate primitive, thin projections at
6710    /// each consumer" discipline extended onto the per-`:entrada`
6711    /// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
6712    /// the M3 mesh-slot `Entrada` type — closes the last unlifted
6713    /// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
6714    /// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
6715    /// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
6716    /// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
6717    /// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
6718    /// storage field's name; the accessor's identity name maps onto the
6719    /// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
6720    /// already carries. Declared `pub const fn` (matching the peer M3
6721    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
6722    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
6723    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
6724    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
6725    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
6726    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
6727    /// [`RateLimit`], and the sibling per-`:placement`
6728    /// [`Placement::estrategia`] on the peer M3 mesh-slot `Copy`-composite-
6729    /// enum scalar axis — every one a `pub const fn`) so every future
6730    /// substrate-side `const`-context consumer of the resolved
6731    /// per-`:entrada` L4-port scalar (a `const _: () = assert!(…)`
6732    /// module-scope pin on a per-fixture typed [`Entrada`] anchoring
6733    /// `entrada.port() >= SERVICO_PORT_MIN` at compile time, a future M4
6734    /// admission-webhook `const fn` per-CR gateway-port floor over a
6735    /// typed [`Entrada`], any `const fn` composer that fans on the port
6736    /// at compile time) reaches through the same typed dispatch on the
6737    /// substrate primitive at const-eval time as at runtime. Pinned by
6738    /// [`entrada_port_accessor_is_const_fn`] which witnesses the
6739    /// const-eval posture at module scope via `const _:() = …` items so
6740    /// any future accidental downgrade to non-`const` trips at caixa-core
6741    /// build time.
6742    #[must_use]
6743    pub const fn port(&self) -> u16 {
6744        self.port
6745    }
6746
6747    /// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
6748    /// slice accessor every HTTPRoute-aware renderer keys off when it
6749    /// wants the raw author-declared path-list (not the fallback-
6750    /// applied projection [`Self::resolved_paths`] returns) — returns
6751    /// the author-declared `:entrada :paths` list verbatim as `&[String]`,
6752    /// borrowed from the typed slot's own [`Vec<String>`] storage.
6753    ///
6754    /// Named the "raw slot" half of the per-`:entrada` path-list resolver
6755    /// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
6756    /// (1449891) closes the fallback-applying arm every per-Aplicacao
6757    /// HTTPRoute per-rule `matches[].path` emitter routes through (empty
6758    /// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
6759    /// catch-all; non-empty slot → per-entry verbatim projection); this
6760    /// accessor closes the raw-slot arm every consumer that must see the
6761    /// author's declaration verbatim (the [`AplicacaoSpec::validate`]
6762    /// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
6763    /// not `Err(EntradaPathEmpty)`, so it cannot route through the
6764    /// fallback-applying sibling; the `feira app graph` per-Aplicacao
6765    /// external-gateway summary line's `{:?}` Debug print — which must
6766    /// name the author's declaration, not the substrate's fallback, so
6767    /// an author reading their graph output can grep their caixa.lisp
6768    /// for the exact list they authored) routes through.
6769    ///
6770    /// Prior to this lift the `.paths` field was accessed inline at four
6771    /// production sites: the two internal reads in [`Self::resolved_paths`]
6772    /// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
6773    /// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
6774    /// value-shape gate's `for p in &e.paths` traversal head, and the
6775    /// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
6776    /// Debug print — four open-coded field-accesses that expressed no
6777    /// compile-time link back to the typed slot. A future extension of
6778    /// the `:entrada :paths` axis to a richer author surface — a
6779    /// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
6780    /// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
6781    /// spec supports through `matches[].method`), a per-path per-header
6782    /// filter overlay (`matches[].headers[]`), a per-cluster override
6783    /// the operator pins through a future `:placement :path-overlay`
6784    /// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6785    /// per-CR admission-webhook that normalized the list at admission
6786    /// time — would have had to be threaded through every open-coded
6787    /// copy in lockstep or the validator's per-entry gate would silently
6788    /// disagree with the renderer's per-entry emit on which list a given
6789    /// `:entrada` block resolves to. Lifting the resolution to a typed
6790    /// method on the substrate primitive means every downstream consumer
6791    /// of the Aplicacao's per-`:entrada` path-list surface reaches for
6792    /// exactly one typed dispatch — the resolver's accept-set migrates
6793    /// as a unit on any future axis addition.
6794    ///
6795    /// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
6796    /// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
6797    /// carry axis — same "one typed dispatch on the substrate primitive,
6798    /// thin projections at each consumer" discipline extended onto the
6799    /// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
6800    /// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
6801    /// carrier) so every downstream per-`:entrada` reader now routes
6802    /// through a typed dispatch on the substrate primitive. Returns
6803    /// `&[String]` (not `&Vec<String>`) because every downstream consumer
6804    /// treats the list as a read-only sequence — the slice-view is the
6805    /// narrowest borrow that supports every present + roadmapped consumer
6806    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
6807    /// `Vec`'s grow/push/reserve surface that no consumer of the typed
6808    /// view reaches for (the storage-side `Vec` remains reachable through
6809    /// the `pub paths` field for the mutation-carrying serde round-trip
6810    /// and per-test fixture-mutation paths).
6811    #[must_use]
6812    pub const fn paths(&self) -> &[String] {
6813        self.paths.as_slice()
6814    }
6815}
6816
6817/// Canonical default L4 port every typed Servico exposes on its
6818/// in-cluster K8s Service (the `trigger.service.port` axis the
6819/// `pleme-computeunit` library chart emits, the `:entrada :port` author
6820/// surface defaults to when the author omits the slot, and the
6821/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
6822/// `:entrada` block matches the per-`:contratos` destination Servico).
6823/// The single source of truth all three typed-port consumers reach for:
6824///
6825///   - [`Entrada::port`]'s serde default (via the
6826///     [`default_port`] helper this constant feeds); the author surface
6827///     `(:entrada (:host … :para …))` without an explicit `:port` slot
6828///     reads back as a typed [`Entrada`] carrying this exact value;
6829///   - the
6830///     [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
6831///     emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
6832///     fallback, fired when the typed `:entrada` block doesn't name
6833///     the per-`:contratos` destination Servico — the typed
6834///     `:contratos` graph carries no per-destination port axis (the
6835///     destination port is the destination Servico's
6836///     `lareira-<nome>` chart's `trigger.service.port`, which the
6837///     Aplicacao-level renderer has no visibility into without a
6838///     resolver round-trip), so the renderer falls back to the
6839///     substrate's canonical Servico-port assumption — by
6840///     construction the same value the destination's own
6841///     `pleme-computeunit` chart emits, the same value the
6842///     destination's own typed `:entrada :port` slot defaults to;
6843///   - every future per-Servico renderer the absorption-roadmap
6844///     acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
6845///     CR materializer's per-edge port resolver, the future
6846///     per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
6847///     emitter's per-route bucket key, the future caixa-otel
6848///     collector-pipeline emitter's per-Servico scrape port).
6849///
6850/// Until this lift landed the value `8080` lived at two production-code
6851/// call-sites: the [`default_port`] helper at
6852/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
6853/// and the `.unwrap_or(8080)` literal at
6854/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
6855/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
6856/// resolver). A future Servico-port rebrand — the substrate moving the
6857/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
6858/// gateway grows direct `:80` listeners, to `8443` once the substrate
6859/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
6860/// override the operator pins through a future
6861/// `:placement :default-port` slot — without a coordinated edit on
6862/// both sides would silently emit Servicos listening on one port and
6863/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
6864/// The CNP's apply-time symptom (the policy is admitted but every L4
6865/// flow on the destination Servico's actual port silently drops because
6866/// it doesn't match the whitelisted port) is far from the rebrand
6867/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
6868/// in hubble traces, not in `kubectl describe`. Lifting the literal to
6869/// a shared constant closes the drift footgun structurally — both
6870/// consumers read from the same `u16`, so any rebrand reaches both
6871/// sites by construction.
6872///
6873/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
6874/// per-renderer canonical-K8s-axis constant — the namespace string
6875/// and the canonical Servico port both lived as duplicated literals
6876/// across caixa-core / caixa-mesh / caixa-flux before their respective
6877/// lifts. Same "the typed constant lives in one place" discipline the
6878/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
6879/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
6880/// shared-string axes.
6881///
6882/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
6883pub const DEFAULT_SERVICO_PORT: u16 = 8080;
6884
6885/// Structural floor for the typed `:entrada :port` axis — every
6886/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
6887/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
6888///
6889/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
6890/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
6891/// interprets as "let the kernel pick a free port at bind time", not a
6892/// well-defined destination the substrate's per-`:entrada` Gateway API
6893/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
6894/// carrying `port: 0` degenerates to a nominal-only routing target: the
6895/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
6896/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
6897/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
6898/// at build time rather than at `kubectl apply` time), and the
6899/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
6900/// (caixa-mesh/src/lib.rs:2657 through
6901/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
6902/// [`Entrada::port`] typed value — silently emits a policy whose
6903/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
6904/// actual listener, dropping every L4 flow at the eBPF data plane far
6905/// from the source caixa.lisp with no field naming the port-zero-drift
6906/// root cause.
6907///
6908/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
6909/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
6910/// on the top edge (unlike the peer capped-`u32` `:politicas` /
6911/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
6912/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
6913/// well below `u32::MAX` and therefore need explicit typed caps).
6914///
6915/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
6916/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
6917/// scalar every `(:entrada (:host … :para …))` slot without an explicit
6918/// `:port` inherits through the serde default hook; this constant names
6919/// the accept-set floor every declared port must satisfy. The pair is
6920/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
6921/// substrate's default must satisfy its own accept-set floor by
6922/// construction) — a future rebrand that accidentally moved
6923/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
6924/// negative-cast typo, a per-cluster override the operator pins through
6925/// a future `:placement :default-port` slot that lands out-of-range)
6926/// would silently invalidate the serde-default emission at every
6927/// author-side `(:entrada (:host … :para …))` slot — the compile-time
6928/// invariant pin
6929/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
6930/// closes the drift footgun at caixa-core build time.
6931///
6932/// Lifted as a typed `pub const` (rather than an inline `0` literal at
6933/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
6934/// has exactly one source of truth — the future M4
6935/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
6936/// gateway resolver, the future per-Servico
6937/// `computeunit.trigger.service.port` renderer's per-CR port-value
6938/// validator, and every downstream test-fixture navigator asserting
6939/// the accept-set floor all read from one place. Same shape every
6940/// other typed bracket-floor / bracket-ceiling in this crate carries
6941/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
6942/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
6943/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
6944/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
6945/// [`POLICY_RATE_LIMIT_MAX`]).
6946pub const SERVICO_PORT_MIN: u16 = 1;
6947
6948const fn default_port() -> u16 {
6949    DEFAULT_SERVICO_PORT
6950}
6951
6952// ── the typed view ───────────────────────────────────────────────────
6953
6954/// Typed composition view of the flat Aplicacao slots on
6955/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
6956/// validation + downstream renderer consumption.
6957#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
6958#[serde(rename_all = "camelCase")]
6959pub struct AplicacaoSpec {
6960    pub membros: Vec<Membro>,
6961    pub contratos: Vec<WitContract>,
6962    pub politicas: MeshPolicy,
6963    pub placement: Placement,
6964    pub entrada: Option<Entrada>,
6965}
6966
6967impl AplicacaoSpec {
6968    /// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
6969    /// per-Aplicacao member-list slice-return accessor every
6970    /// per-Aplicacao member-list reader keys off — returns the author-
6971    /// declared `:membros` list verbatim as a `&[Membro]` slice-view
6972    /// over the same backing buffer the raw `self.membros.as_slice()`
6973    /// field access borrows from.
6974    ///
6975    /// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
6976    /// member list — the load-bearing identity of the application graph
6977    /// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
6978    /// multiset). Every per-`:membros` entry pairs a `:caixa` member-
6979    /// caixa name (through the lifted [`Membro::nome`] (4a32abf)
6980    /// accessor) with a `:versao` semver-requirement string (through
6981    /// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
6982    /// and every downstream consumer that fans on the member-set keys
6983    /// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
6984    /// membership-lookup `HashSet<&str>` seed's collect input, the
6985    /// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
6986    /// [`AplicacaoError::NoMembros`] refusal probe, the same method's
6987    /// per-member DNS-1123 / semver-requirement / duplicate-detection
6988    /// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
6989    /// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
6990    /// programs.yaml per-`:membros` fan-out emitter's per-entry
6991    /// mapping-composition loop, the `feira app graph` per-Aplicacao
6992    /// member-count print line and per-member tree traversal,
6993    /// every future wasm-operator (M4) per-Aplicacao CR materializer's
6994    /// per-member `ComputeUnit` fan-out, the future M5 adaptive-
6995    /// placement engine's per-member weight-topology reader).
6996    ///
6997    /// Prior to this lift the `.membros` `Vec<Membro>` was accessed
6998    /// inline at six production sites — the [`AplicacaoSpec::validate`]
6999    /// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
7000    /// [`AplicacaoSpec::validate_membros`]'s pre-flight
7001    /// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
7002    /// probe, the same method's per-member `for m in &self.membros`
7003    /// validate-loop traversal head, the
7004    /// [`AplicacaoSpec::detect_sync_cycles`]'s
7005    /// `for m in &self.membros` adjacency-list seed, the
7006    /// [`caixa_mesh::programs_for_aplicacao`] emitter's
7007    /// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
7008    /// paired with the peer `for m in &spec.membros` per-entry fan-out
7009    /// loop, and the `feira app graph` per-Aplicacao print line's
7010    /// `spec.membros.len()` count formatter argument paired with the
7011    /// peer `for m in &spec.membros` per-member tree traversal — six
7012    /// open-coded field-accesses that expressed no compile-time link
7013    /// back to the typed slot. A future extension of the `:membros`
7014    /// axis to a richer author surface (a per-cluster member-set
7015    /// overlay the operator pins through a future
7016    /// `:membros-overrides` slot the MESH-COMPOSITION §V federation
7017    /// roadmap acknowledges, a per-tenant member-alias table the M4
7018    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
7019    /// CR at admission time, a per-Aplicacao dynamic member-set
7020    /// derivation the future adaptive-placement engine computes from
7021    /// weighted membership topology, a promotion of the plain
7022    /// `Vec<Membro>` to a richer `{static, dynamic}` partition once
7023    /// Orleans-style virtual-actor dynamic-membership comes into typed
7024    /// scope) would have had to be threaded through all six open-coded
7025    /// copies in lockstep or one consumer would silently disagree with
7026    /// the peers on which member-set a given Aplicacao resolves to —
7027    /// the `HashSet<&str>` name-set seed reading the raw slot while
7028    /// the peer `.is_empty()` refusal probe read an operator-resolved
7029    /// slot would silently split the `:contratos` membership-lookup
7030    /// input from the pre-flight-refusal input, a six-consumer split
7031    /// at the validator + programs.yaml emitter + graph printer far
7032    /// from the source `caixa.lisp` with no field naming the member-
7033    /// set-drift root cause. Lifting the resolution rule to a typed
7034    /// method on the substrate primitive means every downstream
7035    /// consumer of the Aplicacao's per-`:membros` member-list surface
7036    /// reaches for exactly one typed dispatch — the resolver's accept-
7037    /// set migrates as a unit on any future axis addition.
7038    ///
7039    /// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
7040    /// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
7041    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
7042    /// static-child-list `Vec`-carry axis, and to the M3
7043    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
7044    /// on the peer per-`:placement` distribution-target-list `Vec`-
7045    /// carry axis. Same "one typed dispatch on the substrate primitive,
7046    /// thin projections at each consumer" discipline. The two peer
7047    /// `Vec`-carry axes still unlifted at the time of this lift —
7048    /// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
7049    /// WIT-typed edge list) and
7050    /// [`crate::UpgradeFromEntry::instructions`]
7051    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
7052    /// — inherit this accessor's discipline as future compounding runs
7053    /// migrate their consumers onto the shared slice-return shape.
7054    /// First `&[T]`-return accessor on the top-level M3 mesh-slot
7055    /// `AplicacaoSpec` type itself, extending the discipline beyond
7056    /// the inner per-slot types ([`crate::Placement`],
7057    /// [`crate::SupervisorSpec`]) onto the outermost typed composition
7058    /// view every renderer consumes. Named `membros()` to match the
7059    /// storage field's name verbatim and the tatara-lisp author-
7060    /// surface term (`:membros`) the field's own docstring already
7061    /// carries; the accessor's identity maps onto the canonical
7062    /// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
7063    /// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
7064    /// every downstream consumer of the member list treats it as a
7065    /// read-only sequence — the slice-view is the narrowest borrow
7066    /// that supports every present + roadmapped consumer
7067    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
7068    /// backing `Vec`'s grow/push/reserve surface that no consumer of
7069    /// the typed view reaches for (the storage-side `Vec` remains
7070    /// reachable through the `pub membros` field for the mutation-
7071    /// carrying serde round-trip and per-test fixture-mutation paths).
7072    #[must_use]
7073    pub const fn membros(&self) -> &[Membro] {
7074        self.membros.as_slice()
7075    }
7076
7077    /// Substrate-canonical per-`:contratos` `Vec<WitContract>`
7078    /// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
7079    /// accessor every per-Aplicacao contract-list reader keys off —
7080    /// returns the author-declared `:contratos` list verbatim as a
7081    /// `&[WitContract]` slice-view over the same backing buffer the raw
7082    /// `self.contratos.as_slice()` field access borrows from.
7083    ///
7084    /// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
7085    /// WIT-typed edge list — the load-bearing set of directed edges
7086    /// on the application graph whose nodes are the `:membros` entries
7087    /// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
7088    /// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
7089    /// six-tuple is the edge identity every downstream duplicate gate
7090    /// keys off). Every per-`:contratos` entry pairs a `:de` source-
7091    /// Servico caller name + a `:para` destination-Servico callee name
7092    /// (through the lifted [`WitContract::source`] +
7093    /// [`WitContract::destination`] (7f0fd43) accessor pair on the
7094    /// caller/callee-Servico axis) with a `:wit` world-reference
7095    /// (through the lifted [`WitContract::world_ref`] (0804823)
7096    /// accessor) and the target-shape-appropriate payload-carrier
7097    /// scalar (through the lifted [`WitContract::endpoint`] (7020470),
7098    /// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
7099    /// (ed22b66) accessor on the per-target-shape payload-carrier
7100    /// axis). Every downstream consumer that fans on the edge-set
7101    /// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
7102    /// name-set / self-edge / target-shape / dedup fan-out loop, the
7103    /// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
7104    /// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
7105    /// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
7106    /// grouping loop, the `feira app graph` per-Aplicacao contract-
7107    /// count print line and per-contract tree traversal, every future
7108    /// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
7109    /// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
7110    /// mesh-policy overlay resolver's per-contract typed-edge weight
7111    /// reader).
7112    ///
7113    /// Prior to this lift the `.contratos` `Vec<WitContract>` was
7114    /// accessed inline at four production sites — the
7115    /// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
7116    /// per-edge validate-loop traversal head (which drives every
7117    /// per-edge name-set membership lookup, self-edge check,
7118    /// target-shape dispatch, and dedup `HashSet` insert), the
7119    /// [`AplicacaoSpec::detect_sync_cycles`]'s
7120    /// `for c in &self.contratos` adjacency-list seed head (which
7121    /// drives every per-edge sync-vs-pub-sub partition and per-edge
7122    /// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
7123    /// emitter's `for c in &spec.contratos` per-`(:de, :para)`
7124    /// `BTreeMap` grouping loop head (which drives every per-CNP
7125    /// fan-out emit), and the `feira app graph` per-Aplicacao print
7126    /// line's `spec.contratos.len()` count formatter argument paired
7127    /// with the peer `for c in &spec.contratos` per-contract tree
7128    /// traversal — four open-coded field-accesses that expressed no
7129    /// compile-time link back to the typed slot. A future extension
7130    /// of the `:contratos` axis to a richer author surface (a
7131    /// per-cluster contract overlay the operator pins through a
7132    /// future `:contratos-overrides` slot the MESH-COMPOSITION §V
7133    /// federation roadmap acknowledges, a per-tenant edge-policy
7134    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
7135    /// materializer resolves per-CR at admission time, a per-edge
7136    /// weight scalar the future adaptive-placement engine reads to
7137    /// bias sync-subgraph routing, a promotion of the plain
7138    /// `Vec<WitContract>` to a richer `{static, dynamic}` partition
7139    /// once virtual-actor-style dynamic-edge composition comes into
7140    /// typed scope) would have had to be threaded through all four
7141    /// open-coded copies in lockstep or one consumer would silently
7142    /// disagree with the peers on which edge-set a given Aplicacao
7143    /// resolves to — the validator's per-edge dedup `HashSet` seed
7144    /// reading the raw slot while the peer sync-cycle adjacency-list
7145    /// seed read an operator-resolved slot would silently split the
7146    /// build-time edge-set gate from the runtime deadlock-detection
7147    /// gate, a four-consumer split at the validator, the cycle
7148    /// detector, the CNP emitter, and the graph printer far from
7149    /// the source `caixa.lisp` with no field naming the edge-set-
7150    /// drift root cause. Lifting the resolution rule to a typed method on the
7151    /// substrate primitive means every downstream consumer of the
7152    /// Aplicacao's per-`:contratos` edge-list surface reaches for
7153    /// exactly one typed dispatch — the resolver's accept-set
7154    /// migrates as a unit on any future axis addition.
7155    ///
7156    /// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
7157    /// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
7158    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
7159    /// static-child-list `Vec`-carry axis, to the M3
7160    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
7161    /// on the peer per-`:placement` distribution-target-list `Vec`-
7162    /// carry axis, and to the immediately-adjacent sibling M3
7163    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
7164    /// the peer per-`:membros` node-list `Vec`-carry axis — the
7165    /// per-`:contratos` edge-list accessor is the natural pair of
7166    /// the per-`:membros` node-list accessor (graph edges over graph
7167    /// nodes; every graph-shaped consumer reads both). Same "one
7168    /// typed dispatch on the substrate primitive, thin projections
7169    /// at each consumer" discipline. The last remaining `Vec`-carry
7170    /// axis still unlifted at the time of this lift —
7171    /// [`crate::UpgradeFromEntry::instructions`]
7172    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction
7173    /// list) — inherits this accessor's discipline as future
7174    /// compounding runs migrate its consumers onto the shared slice-
7175    /// return shape. Second `&[T]`-return accessor on the top-level
7176    /// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
7177    /// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
7178    /// `:contratos` are the two `Vec` fields on the outer typed
7179    /// composition view — `:politicas`, `:placement`, `:entrada` are
7180    /// scalar/option-shaped and already route through their per-slot
7181    /// accessor families). Named `contratos()` to match the storage
7182    /// field's name verbatim and the tatara-lisp author-surface term
7183    /// (`:contratos`) the field's own docstring already carries; the
7184    /// accessor's identity maps onto the canonical MESH-COMPOSITION
7185    /// §III.1 vocabulary the slot's docstring already reaches for.
7186    /// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
7187    /// every downstream consumer of the contract list treats it as a
7188    /// read-only sequence — the slice-view is the narrowest borrow
7189    /// that supports every present + roadmapped consumer
7190    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
7191    /// backing `Vec`'s grow/push/reserve surface that no consumer of
7192    /// the typed view reaches for (the storage-side `Vec` remains
7193    /// reachable through the `pub contratos` field for the mutation-
7194    /// carrying serde round-trip and per-test fixture-mutation paths).
7195    #[must_use]
7196    pub const fn contratos(&self) -> &[WitContract] {
7197        self.contratos.as_slice()
7198    }
7199
7200    /// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
7201    /// per-Aplicacao mesh-policy composite-reference accessor every
7202    /// per-Aplicacao policy-block reader keys off — returns the author-
7203    /// declared `:politicas` composite verbatim as a `&MeshPolicy`
7204    /// reference over the same backing storage the raw `&self.politicas`
7205    /// field access borrows from.
7206    ///
7207    /// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
7208    /// mesh-policy composite — the load-bearing container of every
7209    /// mesh-level operational-policy axis every downstream mesh-artifact
7210    /// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
7211    /// mesh-policy overlay is the single typed surface a
7212    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
7213    /// from). Every per-`:politicas` axis threads through a lifted
7214    /// per-slot accessor on the [`MeshPolicy`] type: the
7215    /// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
7216    /// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
7217    /// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
7218    /// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
7219    /// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
7220    /// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
7221    /// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
7222    /// Envoy-local-rate-limit-mesh token-bucket-declaration composite
7223    /// accessor. Every downstream consumer that reaches for a policy
7224    /// axis first passes through this outer accessor onto the composite
7225    /// and then dispatches onto the per-axis accessor — the two-level
7226    /// dispatch means every per-`:politicas` reader now routes through
7227    /// a typed dispatch on the substrate primitive at both altitudes.
7228    ///
7229    /// Prior to this lift the `.politicas` `MeshPolicy` composite was
7230    /// accessed inline at four production sites — the
7231    /// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
7232    /// &self.politicas;` traversal seed (which drives every per-axis
7233    /// zero-floor + upper-cap + canonical-form bracket dispatch through
7234    /// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
7235    /// `p.rate_limit()` on the axis-level lifted accessors), the
7236    /// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
7237    /// emitter's `spec.politicas.mtls_required()` field-then-accessor
7238    /// chain (which drives every per-`(:de, :para)` CNP
7239    /// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
7240    /// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
7241    /// timeout + retry overlay emitter's paired
7242    /// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
7243    /// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
7244    /// deadline + budget overlay onto the emitted `HTTPRoute`) — four
7245    /// open-coded outer-field accesses that expressed no compile-time
7246    /// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
7247    /// future extension of the `:politicas` outer axis to a richer
7248    /// author surface (a per-cluster policy overlay the operator pins
7249    /// through a future `:politicas-overrides` slot the MESH-COMPOSITION
7250    /// §V federation roadmap acknowledges, a per-tenant policy-alias
7251    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
7252    /// resolves per-CR at admission time, a per-Aplicacao dynamic
7253    /// policy-composite derivation the future adaptive-placement engine
7254    /// computes from a per-cluster load-topology reader, a promotion of
7255    /// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
7256    /// partition once virtual-actor-style dynamic-mesh-policy
7257    /// composition comes into typed scope) would have had to be threaded
7258    /// through all four open-coded copies in lockstep or one consumer
7259    /// would silently disagree with the peers on which mesh-policy
7260    /// composite a given Aplicacao resolves to — the validator's
7261    /// per-axis bracket-dispatch seed reading the raw slot while the
7262    /// peer CNP mTLS-overlay emitter read an operator-resolved slot
7263    /// would silently split the build-time policy-shape gate from the
7264    /// runtime CNP-emission gate, a four-consumer split at the
7265    /// validator, the CNP emitter, and the `HTTPRoute` emitter far from
7266    /// the source `caixa.lisp` with no field naming the policy-drift
7267    /// root cause. Lifting the resolution rule to a typed method on the
7268    /// substrate primitive means every downstream consumer of the
7269    /// Aplicacao's per-`:politicas` mesh-policy composite surface
7270    /// reaches for exactly one typed dispatch — the resolver's accept-
7271    /// set migrates as a unit on any future axis addition.
7272    ///
7273    /// First `&Composite`-return accessor on the top-level M3 mesh-slot
7274    /// `AplicacaoSpec` type itself — sibling to the seed slice-return
7275    /// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
7276    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
7277    /// close the two `Vec`-carry axes on the outer typed composition
7278    /// view; the outer `:politicas` composite-reference axis is the
7279    /// natural pair to the paired outer `Vec`-carry accessors on the
7280    /// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
7281    /// emitter reads all four axes as one unit (graph nodes + graph
7282    /// edges + mesh policy + placement pool). Peer to the same
7283    /// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
7284    /// slot: every M2 `SupervisorSpec`-scoped composite reader
7285    /// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
7286    /// `restart_window`, `children`) already routes through the M2
7287    /// `SupervisorSpec` accessor family — this lift extends the same
7288    /// "one typed dispatch on the substrate primitive at the outer
7289    /// composition altitude" discipline to the M3 mesh-slot
7290    /// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
7291    /// remaining peer outer-composite axes still unlifted at the time
7292    /// of this lift — [`AplicacaoSpec::placement`] (`Placement`
7293    /// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
7294    /// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
7295    /// inherit this accessor's discipline as future compounding runs
7296    /// migrate their consumers onto the shared reference-return shape.
7297    /// Named `politicas()` to match the storage field's name verbatim
7298    /// and the tatara-lisp author-surface term (`:politicas`) the
7299    /// field's own docstring already carries; the accessor's identity
7300    /// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
7301    /// slot's docstring already reaches for. Returns `&MeshPolicy`
7302    /// (not the owning composite by copy or clone) because every
7303    /// downstream consumer of the mesh-policy composite treats it as a
7304    /// read-only per-axis dispatch source — the reference-view is the
7305    /// narrowest borrow that supports every present + roadmapped
7306    /// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
7307    /// emptiness probe) without cloning the composite through every
7308    /// consumer's fast path.
7309    #[must_use]
7310    pub const fn politicas(&self) -> &MeshPolicy {
7311        &self.politicas
7312    }
7313
7314    /// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
7315    /// per-Aplicacao distribution-composite composite-reference accessor
7316    /// every per-Aplicacao placement-block reader keys off — returns the
7317    /// author-declared `:placement` composite verbatim as a `&Placement`
7318    /// reference over the same backing storage the raw `&self.placement`
7319    /// field access borrows from.
7320    ///
7321    /// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
7322    /// distribution composite — the load-bearing container of every
7323    /// where-does-this-Aplicacao-run axis every downstream cluster-artifact
7324    /// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
7325    /// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
7326    /// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
7327    /// hosting-pool identity, §V for the `M3-Adaptive`-compression
7328    /// `:affinity` hint). Every per-`:placement` axis threads through a
7329    /// lifted per-slot accessor on the [`Placement`] type: the
7330    /// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
7331    /// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
7332    /// per-cluster distribution-target slice-return accessor, the
7333    /// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
7334    /// optional-scalar accessor, and the [`Placement::shard_key`]
7335    /// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
7336    /// downstream consumer that reaches for a placement axis first passes
7337    /// through this outer accessor onto the composite and then dispatches
7338    /// onto the per-axis accessor — the two-level dispatch means every
7339    /// per-`:placement` reader now routes through a typed dispatch on the
7340    /// substrate primitive at both altitudes.
7341    ///
7342    /// Prior to this lift the `.placement` `Placement` composite was
7343    /// accessed inline at three production sites — the
7344    /// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
7345    /// seed (six `self.placement.<axis>()` field-then-inner-accessor
7346    /// chains: the pre-flight `.clusters().is_empty()` refusal probe
7347    /// paired with the `.estrategia()` diagnostic-carry copy, the per-
7348    /// cluster `.clusters()` validate-loop traversal head, the per-
7349    /// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
7350    /// non-`Sharded` partition's `.estrategia()` match arm scrutinee
7351    /// paired with the shape-gate cascade's `.shard_key()` /
7352    /// `.estrategia()` diagnostic-carry pair), the
7353    /// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
7354    /// per-entry placement-block emitter's outer
7355    /// `serde_yaml::to_value(&spec.placement)` composite-serialization
7356    /// seed (which fans onto every per-cluster `programs[]` entry as a
7357    /// self-describing distribution overlay the aggregator filters by),
7358    /// and the `feira app graph` per-Aplicacao print line's paired
7359    /// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
7360    /// then-inner-accessor chains (which drive the human-readable
7361    /// distribution summary of the typed Aplicacao view) — three open-
7362    /// coded outer-field accesses that expressed no compile-time link
7363    /// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
7364    /// extension of the `:placement` outer axis to a richer author surface
7365    /// (a per-cluster placement overlay the operator pins through a
7366    /// future `:placement-overrides` slot the MESH-COMPOSITION §V
7367    /// federation roadmap acknowledges, a per-tenant placement-alias
7368    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
7369    /// resolves per-CR at admission time, a per-Aplicacao dynamic
7370    /// placement-composite derivation the future M5 adaptive-placement
7371    /// engine computes from a per-cluster load-topology reader, a
7372    /// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
7373    /// partition once Orleans-style virtual-actor dynamic-placement comes
7374    /// into typed scope) would have had to be threaded through all three
7375    /// open-coded copies in lockstep or one consumer would silently
7376    /// disagree with the peers on which placement composite a given
7377    /// Aplicacao resolves to — the validator's per-axis bracket-dispatch
7378    /// seed reading the raw slot while the peer
7379    /// `programs_for_aplicacao` emitter read an operator-resolved slot
7380    /// would silently split the build-time distribution-shape gate from
7381    /// the runtime programs.yaml distribution-annotation gate, a three-
7382    /// consumer split at the validator, the programs.yaml emitter, and
7383    /// the `feira app graph` printer far from the source `caixa.lisp`
7384    /// with no field naming the placement-drift root cause. Lifting the
7385    /// resolution rule to a typed method on the substrate primitive
7386    /// means every downstream consumer of the Aplicacao's per-
7387    /// `:placement` distribution composite surface reaches for exactly
7388    /// one typed dispatch — the resolver's accept-set migrates as a unit
7389    /// on any future axis addition.
7390    ///
7391    /// Second `&Composite`-return accessor on the top-level M3 mesh-slot
7392    /// `AplicacaoSpec` type itself — sibling to the seed
7393    /// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
7394    /// composite-reference accessor on the peer per-`:politicas` outer-
7395    /// composite axis, and to the paired slice-return accessors
7396    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
7397    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
7398    /// the two `Vec`-carry axes on the outer typed composition view; the
7399    /// outer `:placement` composite-reference axis is the natural pair
7400    /// to the peer `:politicas` composite-reference axis on the two
7401    /// operationally-symmetric M3 mesh slots (`:politicas` carries the
7402    /// how-to-run policy overlay, `:placement` carries the where-to-run
7403    /// distribution composite — every whole-Aplicacao mesh-artifact
7404    /// emitter reads both as one unit). Same "one typed dispatch on the
7405    /// substrate primitive, thin projections at each consumer"
7406    /// discipline the peer per-`:politicas` composite-reference axis
7407    /// already routes through. The one remaining outer-composite axis
7408    /// still unlifted at the time of this lift —
7409    /// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
7410    /// external-gateway composite) — inherits this accessor's discipline
7411    /// as the next compounding run migrates its consumers onto the shared
7412    /// reference-return shape, closing the outer-composite altitude on
7413    /// every M3 mesh-slot axis. Named `placement()` to match the storage
7414    /// field's name verbatim and the tatara-lisp author-surface term
7415    /// (`:placement`) the field's own docstring already carries; the
7416    /// accessor's identity maps onto the canonical MESH-COMPOSITION §II
7417    /// vocabulary the slot's docstring already reaches for. Returns
7418    /// `&Placement` (not the owning composite by copy or clone) because
7419    /// every downstream consumer of the placement composite treats it as
7420    /// a read-only per-axis dispatch source — the reference-view is the
7421    /// narrowest borrow that supports every present + roadmapped consumer
7422    /// (per-axis accessor dispatch, serde composite-serialization) without
7423    /// cloning the composite through every consumer's fast path.
7424    #[must_use]
7425    pub const fn placement(&self) -> &Placement {
7426        &self.placement
7427    }
7428
7429    /// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
7430    /// per-Aplicacao external-gateway composite optional-composite-
7431    /// reference accessor every per-Aplicacao gateway-block reader
7432    /// keys off — returns the author-declared `:entrada` composite
7433    /// verbatim as an `Option<&Entrada>` reference over the same
7434    /// backing storage the raw `self.entrada.as_ref()` field access
7435    /// borrows from, with `None` naming the internal-only mesh shape
7436    /// (the author-omitted `:entrada` slot the K8s Gateway API v1
7437    /// gateway_routes emitter treats as "emit nothing" and the peer
7438    /// `feira app graph` printer treats as "internal-only mesh").
7439    ///
7440    /// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
7441    /// external-gateway composite — the load-bearing container of
7442    /// every does-this-Aplicacao-expose-a-public-endpoint axis every
7443    /// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
7444    /// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
7445    /// hostname axis, §III.4 for the `:para` destination-Servico
7446    /// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
7447    /// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
7448    /// axis threads through a lifted per-slot accessor on the
7449    /// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
7450    /// Gateway-API `Listener.hostname` scalar accessor, the paired
7451    /// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
7452    /// singleton-list resolver, the [`Entrada::destination`] (821a80e)
7453    /// backendRefs destination-Servico scalar accessor, the
7454    /// [`Entrada::resolved_paths`] path-fallback resolver, and the
7455    /// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
7456    /// scalar accessor. Every downstream consumer that reaches for
7457    /// an entrada axis first passes through this outer accessor onto
7458    /// the composite and then dispatches onto the per-axis accessor
7459    /// — the two-level dispatch means every per-`:entrada` reader
7460    /// now routes through a typed dispatch on the substrate primitive
7461    /// at both altitudes.
7462    ///
7463    /// Prior to this lift the `.entrada` `Option<Entrada>` composite
7464    /// was accessed inline at four production sites — the
7465    /// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
7466    /// gate's `if let Some(e) = &self.entrada { … }` traversal head
7467    /// (which drives every per-axis refusal on the composite: the
7468    /// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
7469    /// `EntradaMemberMissing` membership lookup against the
7470    /// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
7471    /// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
7472    /// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
7473    /// per-path shape gate on each entry of `e.paths`), the
7474    /// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
7475    /// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
7476    /// composite-projection seed (which drives the destination-
7477    /// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
7478    /// backendRefs port emitter fans on), the
7479    /// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
7480    /// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
7481    /// early-return seed (which drives the "no `:entrada` ⇒ no
7482    /// external artifacts" partition on the whole-Aplicacao Gateway-
7483    /// API emitter's fan-out), and the `feira app graph` per-
7484    /// Aplicacao print line's `if let Some(e) = &spec.entrada`
7485    /// external-gateway summary emitter (which drives the human-
7486    /// readable `entrada: host → para (paths=…, port=…)` /
7487    /// `entrada: (internal-only mesh)` partition on the typed
7488    /// Aplicacao view) — four open-coded outer-field accesses that
7489    /// expressed no compile-time link back to the typed slot at the
7490    /// [`AplicacaoSpec`] altitude. A future extension of the
7491    /// `:entrada` outer axis to a richer author surface (a
7492    /// multi-`:entrada` list the M4 CR materializer resolves per-CR
7493    /// at admission time so an Aplicacao can expose a public-web +
7494    /// admin-web pair, a per-cluster `:entrada-overrides` slot the
7495    /// MESH-COMPOSITION §V federation roadmap acknowledges so an
7496    /// operator can pin a per-cluster hostname override without
7497    /// re-authoring the `caixa.lisp`, a promotion of the plain
7498    /// `Option<Entrada>` to a richer `{single, multi}` partition once
7499    /// the multi-`:entrada` roadmap lands) would have had to be
7500    /// threaded through all four open-coded copies in lockstep or one
7501    /// consumer would silently disagree with the peers on which
7502    /// entrada composite a given Aplicacao resolves to — the
7503    /// validator's per-axis bracket-dispatch seed reading the raw
7504    /// slot while the peer `gateway_routes` emitter read an
7505    /// operator-resolved slot would silently split the build-time
7506    /// gateway-shape gate from the runtime Gateway + HTTPRoute
7507    /// emission gate, a four-consumer split at the validator, the
7508    /// `port_for_destination` L4-port resolver, the `gateway_routes`
7509    /// emitter, and the `feira app graph` printer far from the
7510    /// source `caixa.lisp` with no field naming the entrada-drift
7511    /// root cause. Lifting the resolution rule to a typed method on
7512    /// the substrate primitive means every downstream consumer of
7513    /// the Aplicacao's per-`:entrada` external-gateway composite
7514    /// surface reaches for exactly one typed dispatch — the
7515    /// resolver's accept-set migrates as a unit on any future axis
7516    /// addition.
7517    ///
7518    /// Third and final `&Composite`-return accessor on the top-level
7519    /// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
7520    /// unlifted outer-composite axis on the outer typed composition
7521    /// view, sibling to the seed [`AplicacaoSpec::politicas`]
7522    /// (534dc21) `&MeshPolicy` mesh-policy composite-reference
7523    /// accessor on the per-`:politicas` outer-composite axis and to
7524    /// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
7525    /// distribution-composite composite-reference accessor on the
7526    /// per-`:placement` outer-composite axis; extends the outer-
7527    /// composite reference-return discipline the two peers already
7528    /// route through onto the last unlifted per-`AplicacaoSpec`
7529    /// outer-composite axis. The `:entrada` outer-composite axis is
7530    /// the natural pair to the two peer outer-composite axes on the
7531    /// three operationally-symmetric M3 mesh-slot outer composites
7532    /// (`:politicas` carries the how-to-run policy overlay,
7533    /// `:placement` carries the where-to-run distribution composite,
7534    /// `:entrada` carries the who-can-reach-it external-gateway
7535    /// composite — every whole-Aplicacao mesh-artifact emitter reads
7536    /// all three as one unit). Same "one typed dispatch on the
7537    /// substrate primitive, thin projections at each consumer"
7538    /// discipline the peer outer-composite axes already route through.
7539    /// Named `entrada()` to match the storage field's name verbatim
7540    /// and the tatara-lisp author-surface term (`:entrada`) the
7541    /// field's own docstring already carries; the accessor's
7542    /// identity maps onto the canonical MESH-COMPOSITION §III.4
7543    /// vocabulary the slot's docstring already reaches for. Returns
7544    /// `Option<&Entrada>` (not the owning composite by copy or
7545    /// clone) because every downstream consumer of the entrada
7546    /// composite treats it as a read-only per-axis dispatch source
7547    /// — the reference-view is the narrowest borrow that supports
7548    /// every present + roadmapped consumer (per-axis accessor
7549    /// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
7550    /// port-fallback projection, early-return partition on the
7551    /// `None` arm) without cloning the composite through every
7552    /// consumer's fast path. The `Option` half of the return-type
7553    /// preserves the load-bearing "author-omitted `:entrada` ⇒
7554    /// internal-only mesh" partition (not a default composite the
7555    /// downstream must reject on emptiness) — the accessor projects
7556    /// the raw `Option<Entrada>` slot's presence bit through the
7557    /// reference-return unchanged.
7558    #[must_use]
7559    pub const fn entrada(&self) -> Option<&Entrada> {
7560        self.entrada.as_ref()
7561    }
7562
7563    /// Validate the typed shape:
7564    ///   - `:membros` is non-empty; every entry has a non-empty `:caixa`
7565    ///     and a non-empty `:versao`; no two entries share the same
7566    ///     `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
7567    ///     not a multiset)
7568    ///   - every `:contratos` :de + :para must be in `:membros`
7569    ///   - no `:contratos` edge is a self-edge (`:de == :para`) — a
7570    ///     contract is an inter-Servico edge, so a Servico contracting
7571    ///     with itself is a build error under every WIT shape
7572    ///     (MESH-COMPOSITION §III.1)
7573    ///   - no two `:contratos` entries agree on
7574    ///     `(de, para, wit, endpoint, subject, slot)` — the typed-graph
7575    ///     edges are a set, not a multiset (peer of the `:membros` /
7576    ///     `:placement :clusters` / `:entrada :paths` duplicate gates)
7577    ///   - `:entrada :para` must be in `:membros`
7578    ///   - `:placement Sharded` must declare `:shard-key` (non-empty);
7579    ///     `:placement Replicated`/`SingleNode` must NOT declare
7580    ///     `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
7581    ///     consumes it (MESH-COMPOSITION §II.4), and the typed partition
7582    ///     between strategy and shard-key is symmetric: every validated
7583    ///     `Placement` has `shard_key.is_some()` iff `estrategia ==
7584    ///     Sharded`
7585    ///   - every `:placement` strategy must declare ≥1 `:clusters` entry —
7586    ///     `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
7587    ///     the shard pool (MESH-COMPOSITION §III.1)
7588    ///   - every `:clusters` entry is non-empty and unique
7589    ///   - `:placement :affinity`, when set, is non-empty
7590    ///   - the synchronous-`:contratos` subgraph is acyclic
7591    ///     (MESH-COMPOSITION §III.3)
7592    ///   - every declared `:politicas` value is operationally meaningful
7593    ///     (zero timeout, zero retries, zero breaker thresholds, zero rate
7594    ///     limit are all build errors — MESH-COMPOSITION §V CSE invariants;
7595    ///     omit the field instead to express "no policy on this axis")
7596    pub fn validate(&self) -> Result<(), AplicacaoError> {
7597        self.validate_membros()?;
7598
7599        // `:contratos` per-slot gate — folds both structural axes on the
7600        // slot into one substrate primitive: the per-entry cascade (shape
7601        // + membership + self-loop + `:wit` emptiness + WIT-shape ↔
7602        // target + whole-edge dedup) and the cross-edge sync-cycle axis
7603        // ([`AplicacaoSpec::detect_sync_cycles`], MESH-COMPOSITION §III.3
7604        // — pub-sub edges excluded, "acyclic by construction"). Same
7605        // fold-per-axis-plus-cross-axis discipline the sibling
7606        // [`AplicacaoSpec::validate_politicas`] per-slot gate carries via
7607        // [`MeshPolicy::validate`] (f03a154 / 90a6f87), extended here
7608        // onto `:contratos` so every future consumer of the slot (the M4
7609        // admission webhook re-checking `:contratos` after a per-edge
7610        // patch, the per-edge policy resolver MESH-COMPOSITION §III.2 #3
7611        // acknowledges) reaches *both* structural axes through one call.
7612        self.validate_contratos()?;
7613
7614        self.validate_entrada()?;
7615
7616        self.validate_placement()?;
7617
7618        self.validate_politicas()?;
7619
7620        Ok(())
7621    }
7622
7623    /// The `:membros` graph-node name set — the membership oracle every
7624    /// per-Aplicacao name-reference axis resolves against.
7625    ///
7626    /// Three per-Aplicacao axes carry a Servico-name *reference* rather
7627    /// than a Servico-name *declaration*: `:contratos :de`, `:contratos
7628    /// :para`, and `:entrada :para`. Each must resolve to a declared
7629    /// `:membros :caixa` (MESH-COMPOSITION §III.1 — the typed edges and
7630    /// the external gateway both address graph nodes, so a reference to
7631    /// a node the graph does not contain is a build error). All three
7632    /// resolve against *this* set, so the set's construction is the one
7633    /// shared substrate primitive underneath the whole reference-
7634    /// resolution surface.
7635    ///
7636    /// Lifted out of [`AplicacaoSpec::validate`]'s inline
7637    /// `self.membros().iter().map(Membro::nome).collect()` builder so
7638    /// the two per-slot gates that consume it — the per-`:contratos`
7639    /// membership arms still inline at `validate` and the lifted
7640    /// [`AplicacaoSpec::validate_entrada`] below — reach the same
7641    /// oracle through one dispatch rather than each open-coding the
7642    /// projection. Every future consumer on the same axis (the M4
7643    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
7644    /// reference resolver, the per-`:contratos`-edge `:politicas`
7645    /// override MESH-COMPOSITION §III.2 #3 acknowledges — which
7646    /// resolves an edge's endpoints against the same membership set
7647    /// before it can key a per-edge policy off them) inherits the
7648    /// projection through the same call, so a future rebrand of the
7649    /// node-identity axis (a namespace-qualified member name the CR
7650    /// materializer applies per-CR, the `:membros :nome-suffix`
7651    /// overlay §III.2 acknowledges) lands at exactly one place rather
7652    /// than at every reference-resolution site in lockstep. Peer of
7653    /// the sibling per-slot substrate primitives
7654    /// [`MeshPolicy::validate`] (f03a154) and
7655    /// [`WitContract::identity`] on their own axes.
7656    fn membro_names(&self) -> std::collections::HashSet<&str> {
7657        self.membros().iter().map(Membro::nome).collect()
7658    }
7659
7660    /// Reject `:contratos` entries whose endpoints are malformed,
7661    /// reference a Servico outside the graph, self-loop, carry an
7662    /// empty `:wit` shape, duplicate a prior entry on the six-axis
7663    /// identity key, or close a synchronous-edge cycle in the
7664    /// resulting typed graph.
7665    ///
7666    /// The `:contratos` slot is the typed inter-Servico edge set
7667    /// (MESH-COMPOSITION §III.1): each entry is a WIT-typed directed
7668    /// edge whose `:de` / `:para` reference two distinct members and
7669    /// whose `:wit` picks the payload shape the paired L4/L7 renderer
7670    /// (caixa-mesh's per-`(:de, :para)` `CiliumNetworkPolicy` +
7671    /// per-HTTP `HTTPRoute`) fans out on.
7672    ///
7673    /// Two structural axes on the slot are folded into this per-slot
7674    /// gate: the per-entry axis (six per-edge arms, listed below) and
7675    /// the cross-edge synchronous-cycle axis (MESH-COMPOSITION §III.3,
7676    /// dispatched to [`AplicacaoSpec::detect_sync_cycles`] after the
7677    /// per-entry cascade). Same
7678    /// per-axis-plus-cross-axis-fold-into-one-per-slot-gate discipline
7679    /// the sibling [`AplicacaoSpec::validate_politicas`] per-slot gate
7680    /// carries via [`MeshPolicy::validate`] (f03a154 / 90a6f87) on the
7681    /// `:politicas` slot, extended here onto `:contratos`.
7682    ///
7683    /// Six per-entry axes are gated first, in the canonical
7684    /// edge-direction order the paired diagnostics already encode
7685    /// (per-arm value shape before graph-membership lookup; structural
7686    /// self-edge before payload-shape target dispatch; whole-edge dedup
7687    /// last):
7688    ///
7689    ///   - per-arm `:de` / `:para` value shape via
7690    ///     [`validate_contrato_caixa`] (empty + DNS-1123 grammar),
7691    ///     `:de` before `:para`;
7692    ///   - per-edge graph-membership against the
7693    ///     [`AplicacaoSpec::membro_names`] oracle via
7694    ///     [`WitContract::require_endpoints_in`] (folds the twin
7695    ///     `:de` / `:para` arms onto one substrate-primitive
7696    ///     dispatch), `:de` before `:para`;
7697    ///   - structural self-edge via [`WitContract::is_self_loop`]
7698    ///     (caller-equals-callee under any WIT shape);
7699    ///   - `:wit` emptiness ([`AplicacaoError::EmptyWit`]);
7700    ///   - WIT shape ↔ target consistency via [`WitContract::target`]
7701    ///     (the four `WitTarget` arms — `Http` / `PubSub` / `Store` /
7702    ///     `Capability` — each carry their own required payload field);
7703    ///   - six-axis whole-edge dedup via [`WitContract::identity`]
7704    ///     ([`ContratoIdentity`]'s `(de, para, wit, endpoint, subject,
7705    ///     slot)` tuple).
7706    ///
7707    /// One cross-edge axis is gated last, after the per-entry cascade
7708    /// completes cleanly:
7709    ///
7710    ///   - synchronous-edge cycle detection via
7711    ///     [`AplicacaoSpec::detect_sync_cycles`] (iterative DFS with
7712    ///     three-coloring over the sync-only subgraph, pub-sub edges
7713    ///     skipped per MESH-COMPOSITION §III.3 —
7714    ///     [`AplicacaoError::ContratoCycle`]). Runs *after* the
7715    ///     per-entry cascade so a per-entry defect surfaces through its
7716    ///     narrower shape/membership/dedup arm before the cross-edge
7717    ///     cycle diagnostic, matching the pre-fold `validate`-side
7718    ///     dispatch ordering (`validate_contratos()? →
7719    ///     detect_sync_cycles()?`).
7720    ///
7721    /// Lifted out of [`AplicacaoSpec::validate`]'s inline `let mut
7722    /// seen_contracts = …; for c in self.contratos() { … }` block onto
7723    /// a named per-slot gate, closing the last unlifted per-slot gate
7724    /// on the M3 mesh-slot family. Every peer slot already carries the
7725    /// shape ([`AplicacaoSpec::validate_membros`],
7726    /// [`AplicacaoSpec::validate_entrada`],
7727    /// [`AplicacaoSpec::validate_placement`],
7728    /// [`AplicacaoSpec::validate_politicas`]).
7729    ///
7730    /// Self-contained on `&self` — it resolves its own membership
7731    /// oracle through [`AplicacaoSpec::membro_names`] rather than
7732    /// borrowing one threaded down from `validate`, and runs its own
7733    /// cross-edge cycle probe rather than deferring the axis to an
7734    /// outer dispatch — so a future consumer that re-validates *one*
7735    /// slot against a mutated spec (the M4 admission webhook
7736    /// re-checking `:contratos` after a per-`(:de, :para)` edge patch
7737    /// without re-walking `:membros` / `:entrada` / `:placement` /
7738    /// `:politicas`, or the M4 per-edge policy resolver
7739    /// MESH-COMPOSITION §III.2 #3 acknowledges — which resolves an
7740    /// effective per-edge [`MeshPolicy`] and must re-check the edge's
7741    /// own identity closure *and* the sync-cycle invariant before it
7742    /// can key a per-edge override off the endpoint tuple) reaches
7743    /// *both* structural axes on the slot through one call, exactly as
7744    /// [`AplicacaoSpec::validate_politicas`] reaches both per-axis and
7745    /// cross-axis surfaces on `:politicas` through
7746    /// [`MeshPolicy::validate`].
7747    fn validate_contratos(&self) -> Result<(), AplicacaoError> {
7748        let names = self.membro_names();
7749
7750        // Identity key for the typed-edge duplicate gate below: every
7751        // field that distinguishes one contract from another. Two
7752        // entries that agree on all six are *the same edge declared
7753        // twice*, the typed-graph analogue of duplicate `:membros` /
7754        // `:placement :clusters` / `:entrada :paths` entries (which
7755        // are already build errors at this layer). Rejecting it at the
7756        // validate gate closes a renderer-side footgun: caixa-mesh's
7757        // `cilium_network_policies` keys each emitted policy by
7758        // `<aplicacao>-<de>-to-<para>`, so two contracts with identical
7759        // (de, para) and identical payload would land as two K8s
7760        // objects with colliding `metadata.name`, rejected at apply
7761        // time far from the source caixa.lisp.
7762        let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
7763            std::collections::HashSet::new();
7764        for c in self.contratos() {
7765            // Per-axis value-shape gate on every `:contratos` name
7766            // reference, before any graph-membership lookup. Empty +
7767            // DNS-1123-malformed `:de`/`:para` values silently fell
7768            // through to `ContratoMemberMissing` at the lookup arm
7769            // because every `:membros :caixa` is shape-validated
7770            // (3f9d7a0), so the `names` set structurally cannot contain
7771            // an empty / malformed string and the membership-lookup
7772            // diagnostic always misframed the root cause as
7773            // "this caixa is not in `:membros`". The shape gate runs
7774            // ahead of the lookup so structurally-impossible-to-match
7775            // inputs route through the narrower self-locating
7776            // diagnostic, preserving the legitimate "well-shaped
7777            // phantom reference" arm. `:de` runs before `:para` per
7778            // the canonical edge-direction order the existing
7779            // membership lookup, self-edge check, target dispatch,
7780            // and diagnostic strings already use.
7781            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
7782            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
7783            // Per-edge graph-membership gate on the twin `:de` / `:para`
7784            // arms — folded onto the substrate-primitive dispatch
7785            // [`WitContract::require_endpoints_in`] so every per-edge
7786            // consumer of the endpoint-resolution axis (this per-slot
7787            // gate at build time, the M4 admission webhook re-checking
7788            // one edge after a per-`(:de, :para)` patch, the per-edge
7789            // `:politicas` override MESH-COMPOSITION §III.2 #3
7790            // acknowledges) reaches the axis through one call rather
7791            // than re-inlining the twin `if !names.contains(...)`
7792            // cascade. `:de` fires before `:para` inside the primitive,
7793            // preserving byte-equal diagnostic ordering with the
7794            // pre-lift inline cascade.
7795            c.require_endpoints_in(&names)?;
7796            // A `:contratos` entry is an *inter*-Servico contract
7797            // (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
7798            // typed edge between two distinct graph nodes. An edge whose
7799            // `:de` equals its `:para` is a Servico contracting with
7800            // itself — a degenerate edge under every WIT shape. Firing
7801            // the gate before the `:wit`/`target()` shape checks means
7802            // the structural "this edge can't exist" error precedes the
7803            // narrower payload-shape diagnostics, and shape-agnostically
7804            // covers all four `WitTarget` arms (HTTP / Store / Capability
7805            // / PubSub) at one point. Peer of the duplicate-`:contratos`
7806            // / duplicate-`:membros` set gates: both reject a structurally
7807            // ill-formed graph at the typed surface, before the renderer
7808            // emits a K8s object that fails or no-ops far from the source
7809            // caixa.lisp.
7810            if c.is_self_loop() {
7811                return Err(AplicacaoError::contrato_self_loop(c));
7812            }
7813            if c.world_ref().is_empty() {
7814                return Err(AplicacaoError::empty_wit(c.edge_pair()));
7815            }
7816            // Shape ↔ target consistency — surfaces "HTTP wit without
7817            // :endpoint", "NATS wit with :endpoint set", etc. as named
7818            // build errors instead of silent renderer drops. Threaded
7819            // through the duplicate-edge diagnostic below (via
7820            // [`WitTarget::label`]) so the "which typed target arm did
7821            // the duplicate carry" question is answered by the typed
7822            // enum's variant discriminator, not by re-probing the raw
7823            // `Option<String>` payload fields.
7824            let target_view = c.target()?;
7825            // Contract identity: (de, para, wit, endpoint, subject, slot).
7826            // Two contracts that match on all six are the same typed edge
7827            // declared twice — author error, not a legitimate variant of
7828            // "same caller-callee pair, different payload" (e.g.
7829            // cart→catalog at /products vs /search), which keeps distinct
7830            // identity keys via the differing endpoint payloads.
7831            let key = c.identity();
7832            crate::render::insert_first_seen(&mut seen_contracts, key, || {
7833                AplicacaoError::contrato_duplicate(c, &target_view)
7834            })?;
7835        }
7836
7837        // Cross-edge cycle axis on the `:contratos` slot — folded into
7838        // the per-slot gate so the two structural axes on `:contratos`
7839        // (per-entry shape + membership + dedup above; cross-edge sync-
7840        // cycle detection here) reach every consumer through one call.
7841        // Same discipline the sibling per-slot compound gate
7842        // [`MeshPolicy::validate`] (f03a154) established on `:politicas`
7843        // — one named per-slot gate that folds *both* per-axis and
7844        // cross-axis surfaces on the same slot onto one substrate
7845        // primitive — extended here onto `:contratos`, closing the last
7846        // per-slot-axis-family that lived split across `validate` (the
7847        // per-entry `validate_contratos` half here and the cross-edge
7848        // `detect_sync_cycles` call the sibling below at `validate`
7849        // dispatched separately).
7850        //
7851        // Runs after the per-entry cascade so a per-entry defect (empty
7852        // arm, unknown endpoint, self-loop, empty `:wit`, WIT-shape ↔
7853        // target inconsistency, whole-edge duplicate) surfaces first
7854        // through its narrower [`AplicacaoError`] arm before the cross-
7855        // edge cycle diagnostic. This matches the pre-lift ordering the
7856        // `validate`-side dispatch used verbatim (`self.validate_contratos()?
7857        // → self.detect_sync_cycles()?`) — the cycle detector was
7858        // already the second `:contratos`-axis gate in the dispatch,
7859        // just at the outer altitude; the fold moves it under the same
7860        // named per-slot gate without reshaping the diagnostic order.
7861        self.detect_sync_cycles()?;
7862
7863        Ok(())
7864    }
7865
7866    /// Reject `:entrada` values that are operationally meaningless,
7867    /// structurally malformed, or reference a Servico outside the
7868    /// graph.
7869    ///
7870    /// The `:entrada` slot is the Aplicacao's single external ingress
7871    /// (MESH-COMPOSITION §III.1): `:host` + `:port` become a K8s
7872    /// Gateway API v1 `Listener`, `:paths` become the paired
7873    /// `HTTPRoute`'s `matches[].path.value` entries, and `:para` names
7874    /// the member the route forwards to. Omitting the slot entirely is
7875    /// the internal-only-mesh partition — an Aplicacao with no external
7876    /// surface — so the `None` arm is a clean pass, not a refusal.
7877    ///
7878    /// Five axes are gated here, in the canonical order the paired
7879    /// diagnostics already encode (reference-resolution before value
7880    /// shape, per-axis emptiness before per-axis grammar):
7881    ///
7882    ///   - `:para` — DNS-1123 value shape, then membership against the
7883    ///     [`AplicacaoSpec::membro_names`] oracle;
7884    ///   - `:host` — emptiness, then the Gateway API hostname grammar;
7885    ///   - `:port` — the [`SERVICO_PORT_MIN`] structural floor;
7886    ///   - `:paths` — per-entry emptiness, leading-`/`, the Gateway API
7887    ///     path grammar, and set-not-multiset uniqueness.
7888    ///
7889    /// Lifted out of [`AplicacaoSpec::validate`]'s inline `if let
7890    /// Some(e) = self.entrada() { … }` block onto a named per-slot
7891    /// gate, the shape the three peer M3 mesh slots already carry
7892    /// ([`AplicacaoSpec::validate_membros`],
7893    /// [`AplicacaoSpec::validate_placement`],
7894    /// [`AplicacaoSpec::validate_politicas`]). Self-contained on
7895    /// `&self` — it resolves its own membership oracle through
7896    /// [`AplicacaoSpec::membro_names`] rather than borrowing one
7897    /// threaded down from `validate` — so a future consumer that
7898    /// re-validates *one* slot against a mutated spec (the M4 admission
7899    /// webhook re-checking `:entrada` after a gateway-host patch
7900    /// without re-walking the whole `:contratos` graph) reaches the
7901    /// axis through one call, exactly as `detect_sync_cycles` is
7902    /// already self-contained for the M4 per-edge policy resolver.
7903    fn validate_entrada(&self) -> Result<(), AplicacaoError> {
7904        let names = self.membro_names();
7905        if let Some(e) = self.entrada() {
7906            // Route the per-`:entrada` composite-reference read
7907            // through the lifted [`AplicacaoSpec::entrada`] accessor
7908            // rather than the raw `&self.entrada` field access — the
7909            // shape-and-membership gate's traversal head is now the
7910            // canonical read-side surface every per-Aplicacao entrada
7911            // consumer routes through, closing the fourth of four
7912            // open-coded outer-field accesses on the per-`:entrada`
7913            // outer-composite axis.
7914            //
7915            // Shape gate on `:entrada :para` runs ahead of the
7916            // membership lookup. Every `:membros :caixa` past
7917            // `validate_membro_caixa` is a valid DNS-1123 label
7918            // (3f9d7a0), so the `names` set structurally cannot
7919            // contain an empty / malformed string and the membership-
7920            // lookup diagnostic always misframed the root cause as
7921            // "this caixa is not in `:membros`". The shape gate
7922            // routes structurally-impossible-to-match inputs through
7923            // the narrower self-locating diagnostic, preserving the
7924            // legitimate "well-shaped phantom reference" arm — the
7925            // same trajectory the peer `:membros :caixa` (3f9d7a0),
7926            // `:placement :clusters` (6c8c00b), and `:contratos :de`
7927            // / `:para` (8d5af6b) axes already follow. This closes
7928            // the fourth and last Aplicacao-level Servico-name
7929            // reference axis on the canonical DNS-1123 floor.
7930            // Route the per-`:entrada :para` byte-string reads through
7931            // the lifted [`Entrada::destination`] accessor rather than
7932            // the raw `e.para` field access — the three
7933            // per-`AplicacaoSpec::validate` `:entrada :para` consumers
7934            // (shape-gate `validate_entrada_para` arg, membership
7935            // lookup, `EntradaMemberMissing` diagnostic carry) now key
7936            // off exactly one typed dispatch on the substrate
7937            // primitive, closing the last unlifted per-`:entrada :para`
7938            // raw-field-access axis on the M3 mesh-slot validator.
7939            // The `.destination().to_string()` at the diagnostic site
7940            // is byte-identical to `.para.clone()` — pinned by the
7941            // sibling `destination_returns_entrada_para_byte_equal` +
7942            // `destination_borrows_from_entrada_para_storage` accessor
7943            // tests — so a future rebrand of the underlying `:para`
7944            // storage (a lift from `String` to a typed
7945            // `ServicoName(String)` newtype, a per-Aplicacao interning
7946            // arena the M4 CR materializer authors, a
7947            // `smol_str::SmolStr` inline-buffer swap) flows through
7948            // the accessor's one body without a coordinated
7949            // per-consumer rewrite across the M3 mesh validator.
7950            validate_entrada_para(e.destination())?;
7951            if !names.contains(e.destination()) {
7952                return Err(AplicacaoError::entrada_member_missing(e));
7953            }
7954            // Route the per-`:entrada :host` byte-string reads through
7955            // the lifted [`Entrada::hostname`] accessor rather than
7956            // the raw `e.host` field access — the emptiness gate and
7957            // the shape-gate `validate_entrada_host` arg now key off
7958            // exactly one typed dispatch on the substrate primitive,
7959            // closing the last unlifted per-`:entrada :host` raw-
7960            // field-access axis on the M3 mesh-slot validator. Peer
7961            // of the sibling per-`:entrada :para` convergence above
7962            // and pinned by the existing
7963            // `hostname_returns_entrada_host_byte_equal` +
7964            // `hostnames_returns_singleton_of_hostname_accessor`
7965            // accessor tests, so any future
7966            // Gateway-API-shaped host renormalization (a wildcard-
7967            // label lift, a trailing-`.` FQDN substitution, an IDNA
7968            // Punycode round-trip the SNI fan-out overlay authors)
7969            // flows through the accessor's one body without a
7970            // coordinated per-consumer rewrite across the M3 mesh
7971            // validator.
7972            if e.hostname().is_empty() {
7973                return Err(AplicacaoError::EmptyEntradaHost);
7974            }
7975            // The `:host` lands verbatim as a K8s Gateway API v1
7976            // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
7977            // both apiserver-validated against the same restrictive
7978            // pattern: lowercase RFC 1123 DNS subdomain, optional
7979            // single leading wildcard label (`*.`), max length 253,
7980            // per-label max length 63, no IP literals, no scheme,
7981            // no port. Until this gate landed `validate()` only
7982            // refused the empty string (`EmptyEntradaHost`); a
7983            // structurally invalid hostname (`"https://example.com"`,
7984            // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
7985            // `"_underscored.example.com"`, `"FOO.example.com"`,
7986            // `"checkout.quero.cloud."`) silently passed validate
7987            // and the apiserver `field is invalid` error surfaced at
7988            // `kubectl apply` time, far from the source caixa.lisp.
7989            // Lifting the gate to caixa-build time mirrors the
7990            // `:entrada :paths` value-shape trajectory (eb3456d) and
7991            // closes the last unstructured `:entrada` axis.
7992            validate_entrada_host(e.hostname())?;
7993            // Structural-floor gate on `:entrada :port`: every
7994            // validated `Entrada::port` past this gate lies in
7995            // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
7996            // type-inferred ceiling closes the top edge, so no companion
7997            // upper-cap arm is needed here — unlike the peer capped-
7998            // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
7999            // `require_positive_bounded_u32` bracket covers both edges).
8000            // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
8001            // accept-set-floor const rather than the prior inline
8002            // `if e.port == 0` byte-check so a future rebrand of the
8003            // accept-set floor (a hypothetical unprivileged-only
8004            // migration lifting the floor to `1024`, a per-cluster
8005            // scoping the operator pins through a future
8006            // `:placement :port-floor` slot as the M4 typed-slot
8007            // trajectory adds it, the future
8008            // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
8009            // per-Aplicacao gateway resolver reaching for the same
8010            // floor) is a one-line edit on the canonical
8011            // [`SERVICO_PORT_MIN`] declaration, not a coordinated
8012            // rewrite across the emit site + the pin test + every
8013            // future per-target renderer the substrate adds.
8014            if e.port() < SERVICO_PORT_MIN {
8015                return Err(AplicacaoError::EntradaPortZero);
8016            }
8017            // Each `:entrada :paths` entry becomes a K8s Gateway API
8018            // HTTPRoute `matches[].path.value`. The Gateway API rejects
8019            // values that don't start with `/` for `type: PathPrefix`,
8020            // and an empty value is meaningless. Surface those as build
8021            // errors (MESH-COMPOSITION §III.3) rather than apply-time
8022            // failures. Empty `:paths` itself is fine — caixa-mesh
8023            // falls back to a single `/` catch-all.
8024            let mut seen = std::collections::HashSet::new();
8025            // Route the per-entry value-shape gate's traversal head
8026            // through the lifted [`Entrada::paths`] slice accessor
8027            // rather than the raw `&e.paths` field access — the
8028            // per-Aplicacao `:entrada :paths` validate loop now keys
8029            // off the canonical raw-slot surface every downstream
8030            // per-`:entrada` path-list consumer (the sibling
8031            // [`Entrada::resolved_paths`] fallback-applying resolver
8032            // internal reads, `feira app graph`'s per-Aplicacao entrada
8033            // summary line's `{:?}` Debug print) routes through, so any
8034            // future rebrand on the typed slot's raw-slot reader lands
8035            // at exactly one place. Same convergence discipline as the
8036            // sibling [`Placement::clusters`] (a6e18d7) reader-site
8037            // convergences on the peer M3 mesh-slot `Vec<String>`-carry
8038            // axis.
8039            for p in e.paths() {
8040                if p.is_empty() {
8041                    return Err(AplicacaoError::EntradaPathEmpty);
8042                }
8043                if !p.starts_with('/') {
8044                    return Err(AplicacaoError::entrada_path_not_absolute(p));
8045                }
8046                // Per-entry value-shape gate: the path lands verbatim
8047                // as a K8s Gateway API HTTPRoute `matches[].path.value`
8048                // (caixa-mesh/src/lib.rs:498), apiserver-validated
8049                // against `maxLength: 1024` + the Gateway API webhook's
8050                // path-grammar rules (no `//`, no `/./`, no `/../`, no
8051                // query/fragment separators, no whitespace, no control
8052                // characters, no non-ASCII bytes). Until this gate
8053                // landed `validate` only refused the empty string and
8054                // missing-leading-slash (eb3456d); a structurally
8055                // invalid path (`"/api?q=1"`, `"/api#frag"`,
8056                // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
8057                // 1025-byte URL-shaped slug) silently passed validate
8058                // and the failure surfaced at `kubectl apply` time as
8059                // a Gateway API webhook rejection, far from the source
8060                // caixa.lisp, with no field naming the offending
8061                // `:paths` entry. Lifting the gate to caixa-build time
8062                // mirrors the `:entrada :host` value-shape trajectory
8063                // (c7d05ec) on the sibling axis — every author surface
8064                // that emits a Gateway API field now matches the
8065                // apiserver's accepted set at validate time.
8066                validate_entrada_path(p)?;
8067                crate::render::insert_first_seen(&mut seen, p.as_str(), || {
8068                    AplicacaoError::entrada_path_duplicate(p)
8069                })?;
8070            }
8071        }
8072
8073        Ok(())
8074    }
8075
8076    /// Reject `:membros` values that are operationally meaningless. The
8077    /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
8078    /// every entry names a Servico that participates in the Aplicacao,
8079    /// and the rendered programs.yaml fan-out emits one entry per
8080    /// `:membros`. Three authoring footguns are closed here:
8081    ///
8082    ///   - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
8083    ///     a `programs:` entry whose `name:` is the empty string, which
8084    ///     downstream `lareira-fleet-programs` rejects at template time
8085    ///     with a non-localized error;
8086    ///   - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
8087    ///     an empty semver constraint, so the failure surfaces far from
8088    ///     the source caixa.lisp;
8089    ///   - duplicate `:caixa` names — two entries with the same name
8090    ///     produce duplicate programs.yaml entries (one silently
8091    ///     overwrites the other in the cluster's HelmRelease values), and
8092    ///     contract membership lookups against `:contratos` collapse the
8093    ///     two onto one node, masking authoring mistakes.
8094    ///
8095    /// Same value-shape discipline as `:placement :clusters` (where empty
8096    /// + duplicate cluster names are rejected) and `:entrada :paths`
8097    /// (where empty + duplicate path entries are rejected). Lifting these
8098    /// invariants to the typed surface mirrors the MESH-COMPOSITION
8099    /// §III.3 promise that the `:membros` set — the load-bearing identity
8100    /// of the application graph — is well-formed by construction.
8101    fn validate_membros(&self) -> Result<(), AplicacaoError> {
8102        if self.membros().is_empty() {
8103            return Err(AplicacaoError::NoMembros);
8104        }
8105        let mut seen = std::collections::HashSet::new();
8106        for m in self.membros() {
8107            // Every emitted cluster artifact's `metadata.name` derives
8108            // from a `:membros :caixa` value verbatim — the rendered
8109            // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
8110            // the [`crate::LABEL_PROGRAM`] label value on every CNP
8111            // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
8112            // 272), the composed `CiliumNetworkPolicy` `metadata.name`
8113            // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
8114            // `metadata.name` when the member is the `:entrada :para`
8115            // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
8116            // schema enforces the DNS-1123 label rule on admission;
8117            // a structurally invalid member name (`"Cart"`, `"my_cart"`,
8118            // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
8119            // mistaken-identity slug) silently passes the prior empty-/
8120            // duplicate-only gate and the failure surfaces at `kubectl
8121            // apply` time as a `metadata.name: Invalid value` rejection,
8122            // far from the source caixa.lisp, with no field naming the
8123            // offending `:membros` entry. Lifting the gate to caixa-build
8124            // time mirrors the `:entrada :host` value-shape trajectory
8125            // (c7d05ec) on the peer axis — every author surface that
8126            // emits a K8s name now matches the apiserver's accepted set
8127            // at validate time.
8128            validate_membro_caixa(m.nome())?;
8129            // The author surface for `:versao` is the same Cargo-shaped
8130            // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
8131            // `"*"`) every `:deps` entry carries — and the lacre pipeline
8132            // resolves both axes through the same
8133            // [`crate::version::parse_requirement`] entry-point. The
8134            // shared [`crate::render::require_valid_versao_requirement`]
8135            // helper brackets the empty-first + parse cascade both peer
8136            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
8137            // [`crate::SupervisorSpec::validate`] on `:children :versao`)
8138            // route through, so drift between the three axes' accepted
8139            // requirement sets is structurally impossible and the parse-
8140            // side no-op the empty-first arm closes (semver's empty
8141            // parse yields an implicit `*`) lives in exactly one
8142            // predicate.
8143            crate::render::require_valid_versao_requirement(
8144                m.versao_requirement(),
8145                || AplicacaoError::membro_versao_empty(m.nome()),
8146                |reason| {
8147                    AplicacaoError::membro_versao_invalid(m.nome(), m.versao_requirement(), reason)
8148                },
8149            )?;
8150            crate::render::insert_first_seen(&mut seen, m.nome(), || {
8151                AplicacaoError::membro_duplicate(m.nome())
8152            })?;
8153        }
8154        Ok(())
8155    }
8156
8157    /// Reject `:placement` values that are operationally meaningless or
8158    /// internally contradictory. Each strategy variant has the same
8159    /// invariants on `:clusters` (non-empty list, non-empty unique
8160    /// entries) — the §III.1 author surface is uniform on this axis,
8161    /// even though the *meaning* of the list differs by strategy
8162    /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
8163    /// shard pool).
8164    ///
8165    /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
8166    /// are the same authoring footgun closed for `:politicas` zero
8167    /// values and `:entrada` empty paths: the field is *declared* but
8168    /// carries no meaning, so downstream renderers either skip it
8169    /// silently (cluster-fanout drops the empty entry, no diagnostic)
8170    /// or apply it literally and fail at admission time. Lifting both
8171    /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
8172    /// violation is a build error" promise.
8173    ///
8174    /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
8175    /// is required exactly when `:estrategia Sharded` (hash-keyed
8176    /// distribution, Akka cluster-sharding convention, §II.4) and
8177    /// refused on `:estrategia Replicated`/`SingleNode` (where no
8178    /// hash-keyed routing axis consumes it). The partition closes the
8179    /// "I think I configured sharding" footgun where an author writes
8180    /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
8181    /// the typed slot's value silently vanishes at the renderer layer
8182    /// — every validated `Placement` past this call satisfies
8183    /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
8184    fn validate_placement(&self) -> Result<(), AplicacaoError> {
8185        // Every strategy needs at least one named cluster: `Replicated`
8186        // and `SingleNode` use the list as hosting/takeover candidates
8187        // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
8188        // §II.1), while `Sharded` uses it as the shard pool
8189        // (Akka cluster-sharding convention — §II.4). An empty list is
8190        // meaningless under any of the three.
8191        //
8192        // Route the paired pre-flight `.is_empty()` refusal probe and
8193        // the per-cluster validate loop's traversal head through the
8194        // lifted [`Placement::clusters`] slice-return accessor rather
8195        // than the raw `self.placement.clusters` field access — the
8196        // two production consumers of the per-`:placement` cluster-
8197        // pool `Vec`-carry now key off exactly one typed dispatch on
8198        // the substrate primitive, so any future rebrand on the axis
8199        // (a per-tenant cluster-pool overlay the operator pins through
8200        // a future `:placement :clusters-overrides` slot, a per-
8201        // Aplicacao dynamic cluster-pool derivation the future M5
8202        // adaptive-placement engine computes from `:affinity` weights)
8203        // migrates as a single caixa-core edit rather than a
8204        // coordinated rewrite of the paired arms — sibling of the
8205        // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
8206        // arm migration on the per-`:supervisor` static-child-list
8207        // `Vec`-carry axis.
8208        //
8209        // Route the per-`:placement` outer-composite reference read
8210        // through the lifted [`AplicacaoSpec::placement`] outer accessor
8211        // rather than the raw `&self.placement` field access — the
8212        // per-axis bracket-dispatch fan-out below (`p.clusters()`,
8213        // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
8214        // axis-level lifted accessor family) now routes through the
8215        // substrate-primitive typed dispatch at the outer composition
8216        // altitude, the same shape the peer caixa-mesh
8217        // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
8218        // and the sibling `feira app graph` per-Aplicacao print line
8219        // now key off after this accessor lift.
8220        let p = self.placement();
8221        if p.clusters().is_empty() {
8222            // Route the per-`:placement` empty-clusters diagnostic
8223            // through the substrate-primitive
8224            // [`AplicacaoError::placement_without_clusters`] ctor rather
8225            // than the pre-lift three-line open-coded
8226            // `AplicacaoError::PlacementWithoutClusters { estrategia:
8227            // p.estrategia() }` struct-literal — folds the sole in-crate
8228            // wire-up on this variant onto one dispatch matching the
8229            // sibling per-`:placement :clusters` dedup /
8230            // per-`:contratos` self-edge / per-`:upgrade-from :from`
8231            // duplicate substrate-primitive-projection ctors on the
8232            // same `AplicacaoError` / `UpgradeError` envelopes.
8233            return Err(AplicacaoError::placement_without_clusters(p));
8234        }
8235        let mut seen = std::collections::HashSet::new();
8236        for c in p.clusters() {
8237            // Per-entry value-shape gate: the cluster name lands in
8238            // every K8s context / `lareira-fleet-programs` aggregator
8239            // filter / future M4 CR materializer's per-cluster axis
8240            // a validated `:clusters` entry passes through, each
8241            // enforcing the DNS-1123 label rule on admission. Same
8242            // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
8243            // on the peer name axis — both axes' validated values
8244            // are guaranteed-accepted by the apiserver without
8245            // re-validation at any downstream renderer or admission
8246            // layer.
8247            validate_placement_cluster(c)?;
8248            crate::render::insert_first_seen(&mut seen, c.as_str(), || {
8249                // Route the per-`:placement :clusters` dedup diagnostic
8250                // through the substrate-primitive
8251                // [`AplicacaoError::placement_cluster_duplicate`] ctor
8252                // rather than the pre-lift three-line open-coded
8253                // `AplicacaoError::PlacementClusterDuplicate { cluster:
8254                // c.clone() }` struct-literal — folds the sole in-crate
8255                // wire-up on this variant onto one dispatch matching the
8256                // sibling per-`:membros :caixa` / per-`:entrada :paths` /
8257                // per-`:politicas <scalar>` single-slot ctor families on
8258                // the same [`AplicacaoError`] envelope.
8259                AplicacaoError::placement_cluster_duplicate(c)
8260            })?;
8261        }
8262        // Route the per-`:placement :affinity` per-hint value-shape
8263        // gate through the typed [`Placement::affinity`] accessor rather
8264        // than the raw `&self.placement.affinity` field access — the
8265        // sole open-coded field-access site on the per-`:placement`
8266        // M3-Adaptive-compression-hint axis the accessor lift now owns.
8267        // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
8268        // the accessor's `Option<&str>` return type;
8269        // [`validate_placement_affinity`]'s `&str` parameter accepts
8270        // the narrower borrow without a re-allocation, so the routing
8271        // change is byte-for-byte in the pass arm and remains
8272        // byte-for-byte in every failure diagnostic
8273        // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
8274        // String` field is populated inside
8275        // [`validate_placement_affinity`] via the peer `.to_string()`
8276        // path on the same borrowed slice). Peer of the sibling
8277        // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
8278        // routing through [`Placement::shard_key`] at the caixa-core
8279        // site above — extends the "read `:placement` optional-scalars
8280        // through the typed accessor" discipline to the second
8281        // `Option<String>`-shape slot on the M3 mesh-slot family.
8282        //
8283        // Per-hint value-shape gate: the `:affinity` value lands
8284        // verbatim in the M3 Adaptive compression overlay
8285        // (caixa-mesh's `placement.affinity` emission) and every
8286        // future M4 placement-engine routing axis keying off the
8287        // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
8288        // selector — each enforces the DNS-1123 label rule on
8289        // admission. Same typed-shape trajectory as `:placement
8290        // :clusters` (6c8c00b) on the sibling slot and the four
8291        // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
8292        // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
8293        // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
8294        // on the Aplicacao surface to land on the canonical
8295        // [`crate::render::is_dns_1123_label`] floor.
8296        if let Some(a) = p.affinity() {
8297            validate_placement_affinity(a)?;
8298        }
8299        match p.estrategia() {
8300            // Route the `Sharded`-arm shape-gate cascade through the
8301            // typed [`Placement::shard_key`] accessor rather than the
8302            // raw `&self.placement.shard_key` field access — one of the
8303            // two open-coded field-access sites on the per-`:placement`
8304            // Akka-cluster-sharding-key axis the accessor lift now
8305            // owns. The `Some(k)`-bound `k` narrows from `&String` to
8306            // `&str` under the accessor's `Option<&str>` return type;
8307            // `str::is_empty` and [`validate_placement_shard_key`]'s
8308            // `&str` parameter both accept the narrower borrow without
8309            // a re-allocation.
8310            PlacementStrategy::Sharded => match p.shard_key() {
8311                None => return Err(AplicacaoError::ShardedWithoutKey),
8312                Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
8313                // Per-axis value-shape gate on the Akka-cluster-sharding
8314                // `:shard-key` extractor expression. The shape gate runs
8315                // after the more self-locating `ShardedKeyEmpty` arm so
8316                // a `:shard-key ""` surfaces the narrower empty
8317                // diagnostic first; every non-empty `:shard-key` past
8318                // this call is guaranteed to be a printable-ASCII
8319                // single-token reference the future M4 Akka-style
8320                // cluster-sharding reconciler can hash without
8321                // re-validating at the runtime layer. Mirrors the
8322                // payload-axis shape gates on the peer `:contratos`
8323                // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
8324                // 63e18a0 / c4213a4) — each lifts the runtime parser's
8325                // intersection-floor to a caixa-build-time gate.
8326                Some(k) => validate_placement_shard_key(k)?,
8327            },
8328            // `:shard-key` is the Akka-cluster-sharding axis
8329            // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
8330            // across the cluster pool. `Replicated` (active-active across
8331            // every named cluster) and `SingleNode` (Erlang/OTP
8332            // distributed-app takeover/failover, §II.1) have no hash-keyed
8333            // routing axis to consume the slot; downstream renderers
8334            // (caixa-mesh's `placement.shardKey` overlay at
8335            // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
8336            // sharding reconciler) ignore `:shard-key` outside the
8337            // `Sharded` arm by construction. Until this gate landed an
8338            // author who wrote `:placement (:estrategia Replicated
8339            // :shard-key "tenantId")` (an off-by-one strategy typo, a
8340            // copy-paste from a Sharded sibling caixa, the "I think I
8341            // configured sharding" footgun) silently passed validate and
8342            // the typed slot's value vanished at the renderer layer with
8343            // no diagnostic — the canonical "declared-but-inert" footgun
8344            // the empty-:affinity / empty-shard-key / zero-:politicas /
8345            // empty-:contratos-target gates already close on every other
8346            // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
8347            // Lifting the rejection to a build-time gate closes the
8348            // Sharded ↔ non-Sharded partition over the typed
8349            // `:placement` slot: every validated `Placement` past this
8350            // call has `shard_key.is_some()` iff `estrategia ==
8351            // Sharded`, structurally — the future Akka reconciler can
8352            // reach for `placement.shard_key` knowing it's `Some` exactly
8353            // when the strategy consumes it, without re-deriving the
8354            // partition from inline strategy probes.
8355            PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
8356                // Route the non-`Sharded`-arm declared-but-inert refusal
8357                // through the typed [`Placement::shard_key`] accessor —
8358                // the second of the two open-coded field-access sites the
8359                // accessor lift now owns. The `Some(k)`-bound `k` narrows
8360                // from `&String` to `&str`; the `AplicacaoError::
8361                // ShardKeyOnNonSharded { shard_key: String }` diagnostic
8362                // materializes the owned `String` via `k.to_string()`
8363                // (peer to the sibling per-Membro `String`-carry sites
8364                // 4127bb6 routed through `m.nome().to_string()` /
8365                // `m.versao_requirement().to_string()`), so the whole
8366                // `Sharded` ↔ non-`Sharded` partition on the
8367                // `:shard-key` axis now flows through the same typed
8368                // dispatch as the sibling `Sharded`-arm shape gate.
8369                if let Some(k) = p.shard_key() {
8370                    return Err(AplicacaoError::shard_key_on_non_sharded(p, k));
8371                }
8372            }
8373        }
8374        Ok(())
8375    }
8376
8377    /// Reject `:politicas` values that are operationally meaningless.
8378    /// Each axis is optional — omitting it expresses "no policy on this
8379    /// axis". Carrying a *zero* value for a declared axis is the bug
8380    /// this function rejects: zero is either
8381    ///
8382    ///   - re-interpreted as "infinite" by downstream proxies (Envoy's
8383    ///     `RouteAction.timeout = 0s` disables the timeout entirely),
8384    ///     directly contradicting MESH-COMPOSITION §V CSE invariant
8385    ///     "every Aplicacao declares :politicas :timeout (no infinite
8386    ///     blocking)", or
8387    ///   - a renderer footgun (a 0-failure circuit breaker trips on the
8388    ///     first call; a 0-rate rate-limit denies every request).
8389    ///
8390    /// Lifting these "0 means the opposite of what you think" idioms to
8391    /// the typed Aplicacao surface as build errors mirrors the §III.3
8392    /// promise that contract drift, capability leaks, and cycles are all
8393    /// build errors — not runtime surprises.
8394    fn validate_politicas(&self) -> Result<(), AplicacaoError> {
8395        // Route the whole per-axis + cross-axis `:politicas` cascade
8396        // through the substrate primitive [`MeshPolicy::validate`],
8397        // which folds all six per-axis brackets (`:timeout`,
8398        // `:retries`, `:circuit-breaker :max-failures`,
8399        // `:circuit-breaker :window`, `:rate-limit` rate, `:rate-limit`
8400        // window-canonical-form) plus the compound cross-axis fold
8401        // [`MeshPolicy::first_cross_axis_violation`] into one
8402        // `Result<(), AplicacaoError>` return. The whole per-axis-
8403        // brackets + cross-axis-fold cascade collapses to one call, and
8404        // every future [`MeshPolicy`] consumer (the future M4
8405        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
8406        // admission webhook, the per-`:contratos`-edge `:politicas`
8407        // override MESH-COMPOSITION §III.2 #3 acknowledges — the last
8408        // of which resolves an *effective* per-edge [`MeshPolicy`] and
8409        // must emit *the same* diagnostic on the same input as `feira
8410        // build`) reaches through the same substrate-primitive dispatch
8411        // rather than re-inlining the four-per-axis + one-cross-axis
8412        // cascade in lockstep with this validate gate. Same trajectory
8413        // the peer per-kind compound entry gates
8414        // [`crate::render::require_aplicacao_view`] (7242d45 / 3aefefb),
8415        // [`crate::render::require_supervisor_view`] (8d8a5c3),
8416        // [`crate::render::require_v0_servico_shape`] (per-Caixa
8417        // layout axis) and the sibling compound cross-axis fold
8418        // [`MeshPolicy::first_cross_axis_violation`] (90a6f87) carry —
8419        // extended here onto the per-slot compound entry gate that
8420        // folds both per-axis + cross-axis surfaces on the M3
8421        // mesh-slot family.
8422        self.politicas().validate()
8423    }
8424
8425    /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
8426    /// A synchronous edge is any contract whose typed [`WitTarget`] is
8427    /// `Http`, `Store`, or `Capability` — the caller blocks on the
8428    /// callee, so a cycle would deadlock at runtime. Pub-sub edges
8429    /// (`WitTarget::PubSub`) are skipped: an event publisher does not
8430    /// block on its subscribers, so they can never close a sync loop.
8431    ///
8432    /// Iterative DFS with three-coloring; the reported cycle is the
8433    /// path of caixa names traversed from the back-edge target around
8434    /// to itself, in declaration order. Adjacency lists and DFS roots
8435    /// are visited in `BTreeMap` key order so the diagnostic is
8436    /// deterministic across runs.
8437    ///
8438    /// Now the cross-edge axis of the per-slot compound gate
8439    /// [`AplicacaoSpec::validate_contratos`] — invoked at the tail of
8440    /// the per-entry cascade rather than at the outer
8441    /// [`AplicacaoSpec::validate`] dispatch, so both structural axes on
8442    /// `:contratos` (per-entry shape + membership + dedup; cross-edge
8443    /// sync-cycle) reach every consumer through one call. Kept
8444    /// standalone (rather than inlined) so consumers that want only the
8445    /// cross-edge axis (the M4 per-edge policy resolver
8446    /// MESH-COMPOSITION §III.2 #3 acknowledges, whose per-edge patch
8447    /// mutates one `:contratos` entry and needs to re-probe *just* the
8448    /// cycle invariant against the post-patch adjacency without
8449    /// re-running the per-entry shape/membership/dedup cascade the
8450    /// per-entry-only [M4 admission] fast path already covered) still
8451    /// have a self-contained entry point on the cycle axis.
8452    fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
8453        use std::collections::{BTreeMap, BTreeSet};
8454
8455        #[derive(Clone, Copy, PartialEq, Eq)]
8456        enum Mark {
8457            White,
8458            Gray,
8459            Black,
8460        }
8461
8462        let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
8463        for m in self.membros() {
8464            adj.entry(m.nome()).or_default();
8465        }
8466        for c in self.contratos() {
8467            // target() was already called by validate(); re-running here
8468            // keeps detect_sync_cycles self-contained for callers that
8469            // reuse it (M4 per-edge policy resolver) without revalidating.
8470            //
8471            // The pub-sub-arm check routes through the lifted
8472            // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
8473            // arm-discriminator predicate rather than a raw `matches!(…,
8474            // WitTarget::PubSub { .. })` on the variant so a future
8475            // rebrand on the axis (an M4 per-edge WIT registry split of
8476            // [`WitTarget::PubSub`] into shape-specific peers, a
8477            // per-consumer rename that the accept-set already carries)
8478            // reaches this call site through the derive rather than a
8479            // scattered per-arm `matches!` rewrite — same
8480            // `IsVariant`-derived-arm-discriminator discipline the
8481            // peer closed-set typed enums ([`crate::CaixaKind`] via
8482            // f5bba80, [`PlacementStrategy`] via 766ec63,
8483            // [`crate::supervisor::RestartStrategy`] +
8484            // [`crate::supervisor::RestartPolicy`],
8485            // [`crate::upgrade::UpgradeInstruction`] via 915a934)
8486            // already route through on the substrate's other typed-enum
8487            // arm-discriminator axes.
8488            if c.target()?.is_pubsub() {
8489                continue;
8490            }
8491            adj.entry(c.source()).or_default().insert(c.destination());
8492        }
8493
8494        let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
8495        let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
8496
8497        // Stable DFS root order — BTreeMap iteration is sorted by key.
8498        let roots: Vec<&str> = adj.keys().copied().collect();
8499
8500        // Frame: (node, sorted-neighbours snapshot, next-edge index).
8501        for root in roots {
8502            if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
8503                continue;
8504            }
8505            let root_neighbors: Vec<&str> = adj
8506                .get(root)
8507                .map(|s| s.iter().copied().collect())
8508                .unwrap_or_default();
8509            let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
8510            color.insert(root, Mark::Gray);
8511
8512            loop {
8513                // Read+advance the top frame in one borrow scope so we
8514                // can later mutate the stack (push/pop) without holding
8515                // a borrow across.
8516                let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
8517                    let node = top.0;
8518                    if top.2 >= top.1.len() {
8519                        (node, None)
8520                    } else {
8521                        let nxt = top.1[top.2];
8522                        top.2 += 1;
8523                        (node, Some(nxt))
8524                    }
8525                });
8526                let Some((node, nxt_opt)) = step else { break };
8527                let Some(nxt) = nxt_opt else {
8528                    color.insert(node, Mark::Black);
8529                    stack.pop();
8530                    continue;
8531                };
8532                let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
8533                match nxt_color {
8534                    Mark::Gray => {
8535                        // Reconstruct the cycle from `node` back through
8536                        // the parent chain to `nxt`, then close.
8537                        let mut cycle = Vec::new();
8538                        let mut cur = node;
8539                        cycle.push(cur.to_string());
8540                        while cur != nxt {
8541                            match parent.get(cur).copied() {
8542                                Some(p) => {
8543                                    cur = p;
8544                                    cycle.push(cur.to_string());
8545                                }
8546                                None => break,
8547                            }
8548                        }
8549                        cycle.reverse();
8550                        cycle.push(nxt.to_string());
8551                        return Err(AplicacaoError::contrato_cycle(cycle));
8552                    }
8553                    Mark::White => {
8554                        parent.insert(nxt, node);
8555                        color.insert(nxt, Mark::Gray);
8556                        let nxt_neighbors: Vec<&str> = adj
8557                            .get(nxt)
8558                            .map(|s| s.iter().copied().collect())
8559                            .unwrap_or_default();
8560                        stack.push((nxt, nxt_neighbors, 0));
8561                    }
8562                    Mark::Black => {}
8563                }
8564            }
8565        }
8566        Ok(())
8567    }
8568
8569    /// Substrate-canonical destination-facing TCP port every emitted
8570    /// per-Aplicacao artifact must key `destination`-shaped port axes
8571    /// off. Returns the typed `:entrada :port` scalar when this
8572    /// Aplicacao's `:entrada` block names `destination` under its
8573    /// `:para` axis (the destination Servico *is* the ingress apex, so
8574    /// the substrate honors the author-declared listener port
8575    /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
8576    /// fallback otherwise (every non-apex destination — the internal
8577    /// mesh Servicos `:contratos` reach across, the future per-edge
8578    /// policy resolver's per-destination probe targets, the
8579    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
8580    /// L4 port resolver — reads the same substrate-canonical port floor
8581    /// by construction).
8582    ///
8583    /// Prior to this lift the "if :entrada matches this destination use
8584    /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
8585    /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
8586    /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
8587    /// prior to this lift), with no typed method on the substrate primitive
8588    /// that named the rule. A future per-destination port axis addition
8589    /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
8590    /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
8591    /// per-Servico listener ports land, a per-cluster override the operator
8592    /// pins through a future `:placement :default-port` slot — would have
8593    /// to be threaded through every renderer's inline cascade in lockstep
8594    /// or one consumer would silently disagree on which port a given
8595    /// destination Servico's ingress lands at. Lifting the rule to a
8596    /// typed method on the substrate primitive means the M4 CR
8597    /// materializer, the future per-edge policy resolver, and every
8598    /// downstream test-fixture navigator reach for exactly one typed
8599    /// dispatch — the resolver's accept-set moves as a unit on any
8600    /// future axis addition.
8601    ///
8602    /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
8603    /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
8604    /// the typed primitive, thin projections at each consumer"
8605    /// discipline lifts on the sibling `:contratos` payload / `:politicas
8606    /// :rate-limit` unit-suffix axes; extends the discipline onto the
8607    /// destination-facing port-resolution axis every per-Aplicacao
8608    /// L4-fallback renderer consumes.
8609    #[must_use]
8610    pub fn port_for_destination(&self, destination: &str) -> u16 {
8611        // Route the per-`:entrada` composite-reference read through
8612        // the lifted [`AplicacaoSpec::entrada`] accessor rather than
8613        // the raw `self.entrada.as_ref()` field access — the
8614        // per-destination L4-port fallback resolver's composite-
8615        // projection seed is now the canonical read-side surface
8616        // every per-Aplicacao entrada consumer routes through, peer
8617        // of the sibling `validate` per-`:entrada` shape-and-
8618        // membership gate migration on the same outer-composite
8619        // axis.
8620        // Route the per-`:entrada` apex-destination membership probe
8621        // through the lifted [`Entrada::destination`] accessor rather
8622        // than the raw `e.para == destination` field access — the last
8623        // un-lifted `.para` production-code read site on the per-
8624        // `:entrada` `:para` axis, sibling to the four caixa-core
8625        // consumer sites the peer 15ddd8c converge already routed
8626        // through the accessor (the three
8627        // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
8628        // membership gate sites: the `validate_entrada_para` DNS-1123
8629        // shape gate, the per-`:membros` membership lookup, and the
8630        // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
8631        // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
8632        // `entrada.para`-projection converge at
8633        // caixa-core/src/render.rs (the `gateway_api_http_route_name`
8634        // route-name projection site). Prior to this converge the
8635        // `port_for_destination` resolver was the solitary consumer
8636        // bypassing the typed dispatch on the `.para` axis — the two
8637        // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
8638        // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
8639        // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
8640        // reach through the same accessor family compose with this
8641        // resolver at the emit boundary via the apex-identity
8642        // invariant `spec.port_for_destination(entrada.destination())
8643        // == entrada.port` the sibling
8644        // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
8645        // pin pins across four permutations. A future extension of the
8646        // `:entrada :para` axis to a richer author surface (a per-
8647        // cluster alias overlay the operator pins through a future
8648        // `:placement`-scoped slot, a namespace-qualified rewrite the
8649        // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
8650        // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
8651        // §III.2 acknowledges) that lands on the accessor would silently
8652        // disagree between this resolver and the two `caixa-mesh` emit
8653        // sites — an author-declared `:para "cart"` value the accessor
8654        // rewrote to `"cart-v2"` under a future canary arm would leave
8655        // the resolver's membership arm falling through to
8656        // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
8657        // `.para`) while the peer emit-site consumers landed on the
8658        // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
8659        // silently disagreed on which destination port a given typed
8660        // `:entrada` resolves to at cluster-apply time. Pinned by the
8661        // drift-detection test
8662        // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
8663        // below.
8664        self.entrada()
8665            .filter(|e| e.destination() == destination)
8666            .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
8667    }
8668}
8669
8670/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
8671/// entry may name the Aplicacao's own `:nome`.
8672///
8673/// An Aplicacao that lists itself as a member is a degenerate self-edge in
8674/// the typed graph — the application graph is a DAG rooted at the Aplicacao
8675/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
8676/// Servicos that compose the app; an Aplicacao is never its own constituent),
8677/// and the lacre pipeline's closure-resolution would otherwise be handed a
8678/// node that is its own parent: a one-node cycle it either rejects far from
8679/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
8680/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
8681/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
8682/// label + lacre closure root), a member whose `:caixa` equals the
8683/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
8684/// peer.
8685///
8686/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
8687/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
8688/// gate `validate_upgrade_from_against_versao` and the supervision-tree
8689/// self-parent gate `crate::supervisor::validate_no_self_supervision`
8690/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
8691/// not a tree/mesh edge" discipline, here on the second typed-graph axis
8692/// (the Aplicacao :membros set; the supervision-tree :children list was the
8693/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
8694/// every validated Supervisor's children are distinct from its `:nome`,
8695/// every validated Aplicacao's membros are distinct from its `:nome`. The
8696/// transitive consequence is that `:entrada :para` and `:contratos`
8697/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
8698/// name the Aplicacao itself, without re-deriving the partition.
8699pub fn validate_no_self_membership(
8700    membros: &[Membro],
8701    parent_nome: &str,
8702) -> Result<(), AplicacaoError> {
8703    for m in membros {
8704        if m.nome() == parent_nome {
8705            return Err(AplicacaoError::membro_is_self_aplicacao(parent_nome));
8706        }
8707    }
8708    Ok(())
8709}
8710
8711#[derive(Debug, Error, PartialEq, Eq)]
8712pub enum AplicacaoError {
8713    #[error("Aplicacao must declare at least one :membros entry")]
8714    NoMembros,
8715    #[error(
8716        ":membros entry has empty :caixa (every member must name a Servico; \
8717         omit the entry instead of carrying an empty name)"
8718    )]
8719    MembroCaixaEmpty,
8720    #[error(
8721        ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
8722         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
8723         name / label value the member name lands in; use a lowercase \
8724         alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
8725    )]
8726    MembroCaixaInvalid { caixa: String, reason: String },
8727    #[error(
8728        ":membros entry {caixa:?} has empty :versao (every member must pin a \
8729         semver constraint that resolves through the lacre pipeline)"
8730    )]
8731    MembroVersaoEmpty { caixa: String },
8732    #[error(
8733        ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
8734         requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
8735         `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
8736         carries; the lacre pipeline resolves both through the same parser)"
8737    )]
8738    MembroVersaoInvalid {
8739        caixa: String,
8740        versao: String,
8741        reason: String,
8742    },
8743    #[error(
8744        ":membros entry {caixa:?} appears more than once (the graph node set \
8745         is a set, not a multiset; duplicate members produce duplicate \
8746         programs.yaml entries and ambiguous :contratos membership lookups)"
8747    )]
8748    MembroDuplicate { caixa: String },
8749    #[error(
8750        "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
8751         never its own constituent Servico (the application graph is a DAG rooted \
8752         at the Aplicacao; :membros names the *other* caixas that compose the \
8753         app, not the app itself). Since every :nome is a globally-unique \
8754         substrate identity, a member naming the Aplicacao's own :nome is a \
8755         one-node lacre-closure recursion, not a coincidentally-named peer; \
8756         drop the self-referential :membros entry or rename it to the actual \
8757         constituent caixa."
8758    )]
8759    MembroIsSelfAplicacao { caixa: String },
8760    #[error(
8761        "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
8762         caixa declared in :membros; omit the contract or fill the {slot} field with a \
8763         member name)"
8764    )]
8765    ContratoCaixaEmpty { slot: &'static str },
8766    #[error(
8767        "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
8768         :contratos {slot} value names a member of :membros, which is itself a \
8769         DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
8770         object the member name lands in — Service, Pod, identity-based Cilium \
8771         selector; use a lowercase alphanumeric + hyphen identifier like \
8772         `\"checkout\"` or `\"cart-v2\"`)"
8773    )]
8774    ContratoCaixaInvalid {
8775        slot: &'static str,
8776        caixa: String,
8777        reason: String,
8778    },
8779    #[error("contrato references caixa {caixa:?} not declared in :membros")]
8780    ContratoMemberMissing { caixa: String },
8781    #[error(
8782        "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
8783         entry is an inter-Servico contract whose :de and :para must name distinct \
8784         :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
8785         the contract, or point :para at the member it actually calls)"
8786    )]
8787    ContratoSelfLoop { caixa: String, wit: String },
8788    #[error("contrato {de:?} → {para:?} has empty :wit")]
8789    EmptyWit { de: String, para: String },
8790    #[error(
8791        "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
8792         {reason} (the substrate dispatches `:wit` values on the canonical \
8793         lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
8794         `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
8795         demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
8796         kebab-case identifier per segment)"
8797    )]
8798    ContratoWitInvalid {
8799        de: String,
8800        para: String,
8801        wit: String,
8802        reason: String,
8803    },
8804    #[error(
8805        ":entrada :para is empty (every :entrada must route to a caixa declared in \
8806         :membros; fill the :para field with a member name)"
8807    )]
8808    EntradaParaEmpty,
8809    #[error(
8810        ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
8811         :entrada :para value names a member of :membros, which is itself a DNS-1123 \
8812         label per the K8s apiserver's `metadata.name` rule on every object the \
8813         member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
8814         Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
8815         `\"checkout\"` or `\"cart-v2\"`)"
8816    )]
8817    EntradaParaInvalid { para: String, reason: String },
8818    #[error(":entrada routes to caixa {para:?} not declared in :membros")]
8819    EntradaMemberMissing { para: String },
8820    #[error(":entrada must declare a non-empty :host")]
8821    EmptyEntradaHost,
8822    #[error(
8823        ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
8824         (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
8825         `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
8826         like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
8827    )]
8828    EntradaHostInvalid { host: String, reason: String },
8829    #[error(":entrada :port must be in 1..=65535, got 0")]
8830    EntradaPortZero,
8831    #[error(":entrada :paths entry is empty (use the empty list to match all)")]
8832    EntradaPathEmpty,
8833    #[error(
8834        ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
8835    )]
8836    EntradaPathNotAbsolute { path: String },
8837    #[error(
8838        ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
8839         value: {reason} (the K8s apiserver enforces the same shape on \
8840         `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
8841         single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
8842         requires percent-encoding `%XX` for non-ASCII and whitespace)"
8843    )]
8844    EntradaPathInvalid { path: String, reason: String },
8845    #[error(":entrada :paths entry {path:?} appears more than once")]
8846    EntradaPathDuplicate { path: String },
8847    #[error(
8848        ":placement {estrategia} requires at least one :clusters entry \
8849         (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
8850    )]
8851    PlacementWithoutClusters { estrategia: PlacementStrategy },
8852    #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
8853    PlacementClusterEmpty,
8854    #[error(
8855        ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
8856         (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
8857         in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
8858         future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
8859         — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
8860         identifier like `\"rio\"` or `\"mar-east\"`)"
8861    )]
8862    PlacementClusterInvalid { cluster: String, reason: String },
8863    #[error(":placement :clusters entry {cluster:?} appears more than once")]
8864    PlacementClusterDuplicate { cluster: String },
8865    #[error(
8866        ":placement :affinity must be non-empty when set (omit :affinity to express \
8867         `no placement hint`)"
8868    )]
8869    PlacementAffinityEmpty,
8870    #[error(
8871        ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
8872         (placement hints land verbatim in the M3 Adaptive compression overlay's \
8873         `placement.affinity` field and in every future M4 placement-engine routing \
8874         axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
8875         selector — both enforce the DNS-1123 label rule on admission; use a \
8876         lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
8877         `\"low-latency\"`, or `\"anti-affinity\"`)"
8878    )]
8879    PlacementAffinityInvalid { affinity: String, reason: String },
8880    #[error(":placement Sharded requires :shard-key")]
8881    ShardedWithoutKey,
8882    #[error(
8883        ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
8884         hashes every entity onto the same shard, defeating sharding entirely)"
8885    )]
8886    ShardedKeyEmpty,
8887    #[error(
8888        ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
8889         entity-id extractor expression: {reason} (the future M4 Akka-style \
8890         cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
8891         as a single-token property reference and hashes the extracted entity ID \
8892         to compute shard placement; use a printable-ASCII extractor expression \
8893         like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
8894         `\"${{tenant}}\"`)"
8895    )]
8896    ShardKeyInvalid { shard_key: String, reason: String },
8897    #[error(
8898        ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
8899         Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
8900         convention); :estrategia Replicated runs every cluster active-active and \
8901         :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
8902         distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
8903         to :estrategia Sharded if hash-keyed routing is the intent"
8904    )]
8905    ShardKeyOnNonSharded {
8906        estrategia: PlacementStrategy,
8907        shard_key: String,
8908    },
8909    #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
8910    ContratoMissingTarget {
8911        de: String,
8912        para: String,
8913        wit: String,
8914        expected: &'static str,
8915    },
8916    #[error(
8917        "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
8918         expected `:{expected}` only"
8919    )]
8920    ContratoWrongTarget {
8921        de: String,
8922        para: String,
8923        wit: String,
8924        expected: &'static str,
8925    },
8926    #[error(
8927        "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
8928         like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
8929         that matches no traffic and silently drops every request)"
8930    )]
8931    ContratoEndpointEmpty { de: String, para: String },
8932    #[error(
8933        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
8934         (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
8935         :entrada :paths)"
8936    )]
8937    ContratoEndpointNotAbsolute {
8938        de: String,
8939        para: String,
8940        endpoint: String,
8941    },
8942    #[error(
8943        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
8944         Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
8945         emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
8946         caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
8947         shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
8948         like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
8949         and whitespace)"
8950    )]
8951    ContratoEndpointInvalid {
8952        de: String,
8953        para: String,
8954        endpoint: String,
8955        reason: String,
8956    },
8957    #[error(
8958        "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
8959         subject is a no-op subscribe; omit :subject only if the WIT world is not \
8960         pub-sub-shaped)"
8961    )]
8962    ContratoSubjectEmpty { de: String, para: String },
8963    #[error(
8964        "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
8965         NATS subject: {reason} (the NATS server's subject parser enforces the \
8966         same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
8967         single-token and `>` multi-token wildcards — at publish/subscribe time; \
8968         use a token-by-token form like `\"checkout.events.charge.failed\"` or \
8969         `\"orders.*.completed\"` — a malformed subject silently drops every \
8970         message at runtime far from the source caixa.lisp)"
8971    )]
8972    ContratoSubjectInvalid {
8973        de: String,
8974        para: String,
8975        subject: String,
8976        reason: String,
8977    },
8978    #[error(
8979        "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
8980         addresses the bucket root, defeating the per-key isolation the slot exists \
8981         for; omit :slot only if the WIT world is not store-shaped)"
8982    )]
8983    ContratoSlotEmpty { de: String, para: String },
8984    #[error(
8985        "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
8986         WASI keyvalue store slot template: {reason} (the substrate enforces \
8987         the printable-ASCII intersection-floor every kv backend admits — \
8988         use a single-token path / template expression like `\"checkout/$orderId\"`, \
8989         `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
8990         percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
8991         slot either gets rejected on write by strict backends or silently \
8992         corrupts the next read on permissive ones, far from the source caixa.lisp)"
8993    )]
8994    ContratoSlotInvalid {
8995        de: String,
8996        para: String,
8997        slot: String,
8998        reason: String,
8999    },
9000    #[error(
9001        "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
9002         or an event-sourced indirection (MESH-COMPOSITION §III.3)",
9003        cycle.join(" → ")
9004    )]
9005    ContratoCycle { cycle: Vec<String> },
9006    #[error(
9007        ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
9008         than once (the typed graph edges are a set, not a multiset; duplicate \
9009         contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
9010         values that K8s admission rejects far from the source caixa.lisp)"
9011    )]
9012    ContratoDuplicate {
9013        de: String,
9014        para: String,
9015        wit: String,
9016        target: String,
9017    },
9018    #[error(
9019        ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
9020         contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
9021         express `no per-call deadline on this axis`"
9022    )]
9023    PolicyTimeoutZero,
9024    #[error(
9025        ":politicas :retries must be > 0 when set; omit :retries to express \
9026         `no retries on transient failure`"
9027    )]
9028    PolicyRetriesZero,
9029    #[error(
9030        ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
9031         (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
9032         retry policy into a thundering-herd amplification vector on transient \
9033         failure (one caller request fans out to `(retries+1)^depth` server-side \
9034         calls across the synchronous-:contratos subgraph), exactly the failure \
9035         mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
9036         Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
9037         or omit :retries to disable retries entirely"
9038    )]
9039    PolicyRetriesExceedsCap { retries: u32 },
9040    #[error(
9041        ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
9042         breaker trips on the first call); omit :circuit-breaker to disable it"
9043    )]
9044    PolicyBreakerZeroFailures,
9045    #[error(
9046        ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
9047         mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
9048         above this cap turns the typed breaker policy into a no-op: the trip \
9049         threshold is structurally so high that no realistic failures-per-:window \
9050         traffic shape can reach it, so the breaker never trips and every typed-slot \
9051         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
9052         Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
9053         structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
9054         Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
9055         omit :circuit-breaker to disable the breaker entirely"
9056    )]
9057    PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
9058    #[error(
9059        ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
9060         tracks no failures); omit :circuit-breaker to disable it"
9061    )]
9062    PolicyBreakerZeroWindow,
9063    #[error(
9064        ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
9065         request); omit :rate-limit to disable rate limiting"
9066    )]
9067    PolicyRateLimitZero,
9068    #[error(
9069        ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
9070         (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
9071         rate-limit policy into a no-op limiter: the token-bucket capacity is \
9072         structurally so high that no realistic per-edge traffic shape can drain it, \
9073         so the limiter never trips and every typed-slot consumer (the future \
9074         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9075         local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
9076         that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
9077         Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
9078         Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
9079         Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
9080         to disable rate limiting entirely"
9081    )]
9082    PolicyRateLimitExceedsCap { rate: u32 },
9083    #[error(
9084        ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
9085         the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
9086         rate-limit codec round-trips losslessly; got {window:?} which renders to a \
9087         non-round-trippable form (omit :rate-limit to disable, or pick one of the \
9088         three canonical windows)"
9089    )]
9090    PolicyRateLimitWindowNotCanonical { window: Duration },
9091    #[error(
9092        ":politicas :timeout must be an integer number of milliseconds — the canonical \
9093         authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
9094         duration codec round-trips losslessly; got {timeout:?} which carries a \
9095         sub-millisecond residue that either truncates to a different `Duration` on \
9096         re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
9097         to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
9098         zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
9099         (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
9100    )]
9101    PolicyTimeoutNotCanonical { timeout: Duration },
9102    #[error(
9103        ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
9104         (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
9105         per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
9106         overlays carry a deadline so long no realistic synchronous-:contratos \
9107         traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
9108         CSE invariant degenerates to enforcement only at the per-Servico \
9109         `:limits :wall-clock` layer — far above the per-edge granularity the typed \
9110         `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
9111         (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
9112         ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
9113         maxes out at the same `3600s` ceiling) or omit :timeout to express \
9114         `no per-call deadline on this axis` (the synchronous-call deadline then \
9115         relies entirely on the per-Servico `:limits :wall-clock` axis)"
9116    )]
9117    PolicyTimeoutExceedsCap { timeout: Duration },
9118    #[error(
9119        ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
9120         the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
9121         the shared duration codec round-trips losslessly; got {window:?} which carries a \
9122         sub-millisecond residue that either truncates to a different `Duration` on \
9123         re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
9124         Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
9125    )]
9126    PolicyBreakerWindowNotCanonical { window: Duration },
9127    #[error(
9128        ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
9129         (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
9130         rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
9131         is structurally so long that transient failures are never forgotten, the breaker \
9132         trips once and stays tripped for the lifetime of the component, and every typed-slot \
9133         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9134         outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
9135         Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
9136         default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
9137         the breaker entirely"
9138    )]
9139    PolicyBreakerWindowExceedsCap { window: Duration },
9140    #[error(
9141        ":politicas :circuit-breaker :window ({window:?}) is shorter than :politicas \
9142         :timeout ({timeout:?}) — the rolling failure-observation interval closes before \
9143         a single timing-out call can be declared failed, so the dominant failure mode \
9144         the breaker exists to catch is structurally never counted: a call dispatched at \
9145         t=0 is only reported failed at t={timeout:?}, by which point the window that was \
9146         open at dispatch has already rolled, and every typed-slot consumer (the future \
9147         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9148         outlier_detection.interval paired against the per-route request timeout) emits a \
9149         breaker that cannot trip on timeouts however high the call volume. Pin :window \
9150         at or above :timeout (Hystrix defaults 10s rolling window against a 1s execution \
9151         timeout — a 10× ratio; Envoy / resilience4j production playbooks recommend the \
9152         same shape), lower :timeout, or omit one of the two axes"
9153    )]
9154    PolicyBreakerWindowBelowTimeout { window: Duration, timeout: Duration },
9155    #[error(
9156        ":politicas :rate-limit ({rate} per {rl_window:?}) starves :politicas \
9157         :circuit-breaker so :max-failures ({max_failures}) cannot be reached inside \
9158         :window ({cb_window:?}) — the token-bucket dispatches at most \
9159         `rate × cb_window / rl_window` calls per rolling breaker window, which is \
9160         structurally below the trip threshold, so the breaker cannot trip even under \
9161         100% failure and every typed-slot consumer (the future \
9162         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9163         outlier_detection.consecutive_5xx paired against \
9164         local_rate_limit.token_bucket.max_tokens) emits a protection that is \
9165         structurally never enforced. Raise :rate, shorten :rate-limit :window, lower \
9166         :max-failures, lengthen :circuit-breaker :window, or omit one of the two axes"
9167    )]
9168    PolicyBreakerCannotTripUnderRateLimit {
9169        rate: u32,
9170        rl_window: Duration,
9171        max_failures: u32,
9172        cb_window: Duration,
9173    },
9174    #[error(
9175        ":politicas :retries ({retries}) plus the initial attempt saturates :politicas \
9176         :circuit-breaker :max-failures ({max_failures}) mid-retry — one client's failing \
9177         attempts alone accumulate {retries}+1 failures, which reaches the trip threshold \
9178         at or before the last retry, so the breaker opens with declared retries still \
9179         unused and every typed-slot consumer (the future CiliumClusterwideEnvoyConfig \
9180         per-:politicas overlay, Envoy's retry_policy.num_retries paired against \
9181         outlier_detection.consecutive_5xx) emits a retry policy the substrate \
9182         structurally truncates. Pin :max-failures strictly above :retries (Hystrix / \
9183         Envoy / resilience4j production playbooks recommend the breaker's trip \
9184         threshold be observably larger than any single client's retry budget so the \
9185         breaker distinguishes one persistently-failing client from sustained \
9186         multi-client failure), lower :retries, or omit one of the two axes"
9187    )]
9188    PolicyBreakerTripsBeforeRetriesExhausted { retries: u32, max_failures: u32 },
9189    #[error(
9190        ":politicas :rate-limit ({rate} per window) cannot admit :politicas :retries \
9191         ({retries}) plus the initial attempt — one client's declared retry sequence is \
9192         {retries}+1 attempts, each of which consumes one token from the local rate-limit \
9193         bucket, but the bucket admits at most {rate} tokens per refill window, so the \
9194         retry policy is silently truncated by the same rate limiter it feeds through and \
9195         every typed-slot consumer (the future CiliumClusterwideEnvoyConfig per-:politicas \
9196         overlay, Envoy's retry_policy.num_retries paired against \
9197         local_rate_limit.token_bucket.max_tokens) emits a retry policy the substrate \
9198         structurally throttles. Raise :rate strictly above :retries (Envoy / Istio / \
9199         resilience4j / AWS App Mesh production playbooks recommend the local rate-limit \
9200         bucket capacity be observably larger than any single client's retry budget so the \
9201         limiter distinguishes one client's declared retries from sustained multi-client \
9202         load), lower :retries, or omit one of the two axes"
9203    )]
9204    PolicyRateLimitCannotAdmitRetryBurst { retries: u32, rate: u32 },
9205}
9206
9207// The `AplicacaoError::EntradaHostInvalid { host, reason }` variant's
9208// ctor `entrada_host_invalid` is folded onto the sibling
9209// [`aplicacao_field_reason_ctors!`] macro below alongside the six peer
9210// `{ <field>: String, reason: String }` variants
9211// (`MembroCaixaInvalid` / `EntradaParaInvalid` / `EntradaPathInvalid` /
9212// `PlacementClusterInvalid` / `PlacementAffinityInvalid` /
9213// `ShardKeyInvalid`), so every variant on the uniform two-slot
9214// `{ <field>: String, reason: String }` envelope on [`AplicacaoError`]
9215// reads through one substrate-primitive family rather than one macro
9216// closing six sites plus a hand-written seventh ctor closing the
9217// paired site alone. Prior separate-ctor rationale (17dd504) migrates
9218// verbatim to the macro's outer doc block.
9219
9220// Fold the seven `AplicacaoError::Contrato{Wrong,Missing}Target { de, para,
9221// wit, expected }` wire-up sites at [`WitContract::target`] onto one
9222// substrate-primitive family per typed variant — the paired sibling on
9223// [`AplicacaoError`] of the four `LayoutError` constructor families
9224// [`layout_violation_ctors!`] (131ca0d, 16 variants on `{ caixa, issue }`),
9225// [`layout_slot_kind_ctors!`] (0419438, 4 variants on
9226// `{ caixa, kind, slots }`), [`LayoutError::missing_entry`] (1b09f9d,
9227// 1 variant on `{ kind, path }`), and [`layout_nome_only_ctors!`] (3fe3dd7,
9228// 6 variants on `<Variant>(String)`) each carry on the sibling layout-side
9229// envelope. Every one of the seven wire-up sites in [`WitContract::target`]
9230// (four `ContratoWrongTarget` arms on the payload-field-mismatch axis —
9231// HTTP with subject/slot, PubSub with endpoint/slot, Store with
9232// endpoint/subject, Capability with any payload; three
9233// `ContratoMissingTarget` arms on the payload-field-absent axis — HTTP
9234// without `:endpoint`, PubSub without `:subject`, Store without `:slot`)
9235// opened the identical six-line
9236// `AplicacaoError::Contrato<Wrong|Missing>Target { de, para, wit, expected:
9237// WitTarget::<label> }` struct-literal against the local `edge()` closure
9238// returning `(de, para, wit) = self.edge_triple()` — the exact "same block
9239// re-inlined at every consumer" shape the PRIME DIRECTIVE names as a bug,
9240// on the same altitude the peer four `LayoutError` constructor families
9241// each closed on their sibling envelopes.
9242//
9243// The macro below generates one `#[must_use]` inherent constructor per
9244// variant of shape `fn <ctor>(edge: (String, String, String), expected:
9245// &'static str) -> AplicacaoError`, collapsing the seven sites onto one
9246// dispatch per arm: `return
9247// Err(AplicacaoError::contrato_wrong_target(edge(), <label>));` / `.ok_or_else(||
9248// AplicacaoError::contrato_missing_target(edge(), <label>))?`, byte-equal to
9249// the pre-lift struct-literal on the same edge fixture. The uniform four-
9250// field construction (`de, para, wit` triple-destructure onto same-named
9251// fields + `expected` verbatim) is spelled once — inside the macro —
9252// rather than at every wire-up site. `#[must_use]` fires a compile warning
9253// at any wire-up that mistakenly discards the constructed error.
9254//
9255// Every future consumer that wants to construct one of these two variants
9256// outside [`WitContract::target`] (a deferred
9257// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
9258// admission validator raising wrong-target / missing-target diagnostics
9259// on unrecognized shapes, a future `feira validate --contratos` per-caixa
9260// admission verb, a per-`WitContract` payload-axis pre-emitter probing
9261// the [`WitTarget`] arm against the declared `:endpoint`/`:subject`/`:slot`
9262// slots) reaches the variant through one call rather than re-inlining the
9263// six-line struct-literal block in lockstep with the seven in-crate
9264// wire-up sites.
9265macro_rules! contrato_target_ctors {
9266    ($($ctor:ident => $variant:ident),* $(,)?) => {
9267        impl AplicacaoError {
9268            $(
9269                #[doc = concat!(
9270                    "Construct an [`AplicacaoError::",
9271                    stringify!($variant),
9272                    "`] naming the offending edge `(de, para, wit)` triple ",
9273                    "under the given `expected` payload-field-name label. ",
9274                    "Folds the uniform `{ de, para, wit, expected }` four-",
9275                    "slot struct-literal onto one substrate primitive so ",
9276                    "every [`WitContract::target`] wire-up on this variant ",
9277                    "reads through one dispatch rather than the pre-lift ",
9278                    "six-line open-coded block. The `edge` triple threads ",
9279                    "verbatim from [`WitContract::edge_triple`] via the ",
9280                    "local `edge()` closure at the call site."
9281                )]
9282                #[must_use]
9283                pub fn $ctor(edge: (String, String, String), expected: &'static str) -> Self {
9284                    let (de, para, wit) = edge;
9285                    Self::$variant { de, para, wit, expected }
9286                }
9287            )*
9288        }
9289    };
9290}
9291
9292contrato_target_ctors! {
9293    contrato_wrong_target => ContratoWrongTarget,
9294    contrato_missing_target => ContratoMissingTarget,
9295}
9296
9297// Fold the four `AplicacaoError::{EmptyWit, ContratoEndpointEmpty,
9298// ContratoSubjectEmpty, ContratoSlotEmpty} { de, para }` wire-up sites
9299// onto one substrate-primitive family per typed variant — the paired
9300// `{ de: String, para: String }` two-slot sibling on [`AplicacaoError`]
9301// of the peer four-slot [`contrato_target_ctors!`] (14b81d5,
9302// `{ de, para, wit, expected }` on `ContratoWrongTarget` /
9303// `ContratoMissingTarget`) and of the two-slot
9304// [`AplicacaoError::entrada_host_invalid`] (17dd504, `{ host, reason }`)
9305// on the sibling per-`:entrada :host` envelope. Every one of the four
9306// wire-up sites — three under [`WitContract::target`] (the empty
9307// [`WitTarget::Http`] `:endpoint`, empty [`WitTarget::PubSub`]
9308// `:subject`, empty [`WitTarget::Store`] `:slot`) and one under
9309// [`AplicacaoSpec::validate`] (the empty `:contratos :wit` field the
9310// value-shape gate fires ahead of) — opened the identical two-line
9311// `let (de, para) = <contract>.edge_pair(); return Err(
9312// AplicacaoError::<Variant> { de, para });` block against the local
9313// [`WitContract::edge_pair`] composite-projection accessor, the exact
9314// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE
9315// names as a bug, on the same altitude the peer [`contrato_target_ctors!`]
9316// and [`AplicacaoError::entrada_host_invalid`] each closed on their
9317// sibling envelopes.
9318//
9319// The macro below generates one `#[must_use]` inherent constructor per
9320// variant of shape `fn <ctor>(edge: (String, String)) -> AplicacaoError`,
9321// collapsing the four sites onto one dispatch per arm:
9322// `return Err(AplicacaoError::<ctor>(<contract>.edge_pair()));`, byte-
9323// equal to the pre-lift struct-literal on the same edge pair. The
9324// uniform two-field construction (`de, para` pair-destructure onto
9325// same-named fields) is spelled once — inside the macro — rather than
9326// at every wire-up site. `#[must_use]` fires a compile warning at any
9327// wire-up that mistakenly discards the constructed error.
9328//
9329// Every future consumer that wants to construct one of these four
9330// variants outside the two in-crate wire-up sites (a deferred
9331// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
9332// admission validator raising empty-payload / empty-`:wit` diagnostics,
9333// a future `feira validate --contratos` per-caixa admission verb, an
9334// M4 typed WIT-registry-driven per-arm pre-emitter probing the
9335// [`WitContract`] payload slot against a canonical per-arm requirement
9336// table) reaches the variant through one call rather than re-inlining
9337// the two-line pair-destructure block in lockstep with the four
9338// in-crate wire-up sites.
9339macro_rules! contrato_empty_pair_ctors {
9340    ($($ctor:ident => $variant:ident),* $(,)?) => {
9341        impl AplicacaoError {
9342            $(
9343                #[doc = concat!(
9344                    "Construct an [`AplicacaoError::",
9345                    stringify!($variant),
9346                    "`] naming the offending edge `(de, para)` pair. ",
9347                    "Folds the uniform `{ de, para }` two-slot struct-",
9348                    "literal onto one substrate primitive so every ",
9349                    "wire-up on this variant reads through one dispatch ",
9350                    "rather than the pre-lift two-line open-coded ",
9351                    "`let (de, para) = <contract>.edge_pair(); return ",
9352                    "Err(<Variant> { de, para });` block. The `edge` ",
9353                    "pair threads verbatim from [`WitContract::edge_pair`] ",
9354                    "at the call site."
9355                )]
9356                #[must_use]
9357                pub fn $ctor(edge: (String, String)) -> Self {
9358                    let (de, para) = edge;
9359                    Self::$variant { de, para }
9360                }
9361            )*
9362        }
9363    };
9364}
9365
9366contrato_empty_pair_ctors! {
9367    empty_wit => EmptyWit,
9368    contrato_endpoint_empty => ContratoEndpointEmpty,
9369    contrato_subject_empty => ContratoSubjectEmpty,
9370    contrato_slot_empty => ContratoSlotEmpty,
9371}
9372
9373// Fold the last open-coded `AplicacaoError::ContratoEndpointNotAbsolute
9374// { de, para, endpoint: <val>.to_string() }` three-slot struct-literal
9375// wire-up site at [`WitContract::target`]'s HTTP-arm leading-slash gate
9376// onto one substrate primitive on [`AplicacaoError`] — sibling on the
9377// `{ de: String, para: String, <field>: String }` three-slot envelope of
9378// the peer [`contrato_empty_pair_ctors!`] macro just above (8580068, four
9379// variants on the paired `{ de, para }` two-slot envelope carrying the
9380// same `let (de, para) = <contract>.edge_pair(); return Err(<Variant>
9381// { de, para });` pair-destructure prelude), the peer four-slot
9382// [`contrato_pair_value_reason_ctors!`] macro (14e13f1, four variants on
9383// the paired `{ de, para, <field>: String, reason: String }` envelope
9384// carrying the parser-shaped `reason` trailer), and the peer four-slot
9385// [`contrato_target_ctors!`] macro (14b81d5, two variants on the paired
9386// `{ de, para, wit, expected: &'static str }` envelope carrying the
9387// canonical target-field-name label). The `ContratoEndpointNotAbsolute`
9388// variant is the sole occupant of the three-slot `{ de, para, <field>:
9389// String }` shape on [`AplicacaoError`] (no sibling
9390// `ContratoSubjectNotAbsolute` / `ContratoSlotNotAbsolute` — the `:subject`
9391// and `:slot` axes carry no "must start with /" invariant, since the
9392// NATS subject grammar and the WASI keyvalue slot template grammar don't
9393// share the Gateway-API-HTTPPathMatch leading-slash prelude the
9394// `:endpoint` axis does), so a full macro isn't warranted; a single
9395// `#[must_use]` inherent ctor matching the ambient
9396// `fn <ctor>(edge: (String, String), <field>: &str) -> Self` shape the
9397// peer per-`:contratos` ctor families each carry closes the last
9398// open-coded three-slot struct-literal on the envelope, matching the
9399// same standalone-ctor discipline the sibling
9400// [`crate::LayoutError::missing_entry`] (1b09f9d, one variant on the
9401// `{ kind: &'static str, path: PathBuf }` two-slot envelope),
9402// [`crate::SupervisorError::child_caixa_invalid`] /
9403// [`::child_versao_invalid`] (d2ef2ec, two variants on the paired
9404// `{ caixa: String, [versao: String,] reason: String }` two- and three-
9405// slot envelopes), and [`AplicacaoError::entrada_host_invalid`] (17dd504,
9406// one variant on the `{ host: String, reason: String }` two-slot
9407// envelope) apply on their sibling one-off variants.
9408//
9409// The one wire-up site on this variant — [`WitContract::target`]'s
9410// HTTP-arm leading-slash gate at `if !ep.starts_with('/')`, one of the
9411// six per-`:contratos` value-shape gates inside the same method body,
9412// where the other five (`ContratoWrongTarget`, `ContratoMissingTarget`,
9413// `ContratoEndpointEmpty`, `ContratoEndpointInvalid`,
9414// `ContratoWitInvalid`) each already reach through one of the three
9415// peer macro-generated ctor families above — opened the same five-line
9416// `let (de, para) = self.edge_pair(); return
9417// Err(AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint:
9418// ep.to_string() });` struct-literal against the local
9419// [`WitContract::edge_pair`] composite-projection accessor and the
9420// caller-side `&str` endpoint — the exact "same block re-inlined at
9421// every consumer" shape the PRIME DIRECTIVE names as a bug, on the same
9422// altitude the six peer `AplicacaoError` constructor families each
9423// closed on their sibling envelopes. Every guarantee in MESH-COMPOSITION
9424// §III.3 (a `:contratos :endpoint` value that doesn't start with `/`
9425// becomes a caixa-build error, not a Cilium L7 policy-side path-match
9426// silent traffic drop far from the source caixa.lisp) now routes through
9427// one substrate primitive on the envelope.
9428//
9429// The ctor below folds the site onto one dispatch:
9430// `return Err(AplicacaoError::contrato_endpoint_not_absolute(
9431// self.edge_pair(), ep));`, byte-equal to the pre-lift struct-literal
9432// on the same `(edge_pair, endpoint)` pair. The uniform three-field
9433// construction (`de, para` pair-destructure onto same-named fields +
9434// `endpoint: endpoint.to_string()`) is spelled once — inside the ctor
9435// body — rather than at the wire-up site. `#[must_use]` fires a compile
9436// warning at any future wire-up that mistakenly discards the constructed
9437// error.
9438//
9439// Every future consumer that wants to construct this variant outside
9440// [`WitContract::target`] (a deferred `mesh.pleme.io/v1alpha1/Aplicacao`
9441// CR materializer's per-`:contratos` admission validator raising the
9442// leading-slash diagnostic on unrecognized `:endpoint` shapes, a future
9443// `feira validate --contratos` per-caixa admission verb re-running the
9444// leading-slash arm on demand, an M4 typed Cilium L7 rule pre-emitter
9445// probing each declared `:endpoint` against the same shared
9446// HTTPPathMatch grammar prelude, a per-tenant per-`Aplicacao` overlay
9447// resolver rejecting a leading-slash-missing `:endpoint` against a
9448// cluster-local Cilium snapshot the M4 CR materializer projects) now
9449// reaches this variant through one call rather than re-inlining the
9450// five-line pair-destructure + struct-literal block in lockstep with
9451// the sole in-crate wire-up site.
9452impl AplicacaoError {
9453    /// Construct an [`AplicacaoError::ContratoEndpointNotAbsolute`]
9454    /// naming the offending edge `(de, para)` pair and the per-payload
9455    /// `endpoint` value. Folds the uniform `{ de, para, endpoint:
9456    /// endpoint.to_string() }` three-slot struct-literal onto one
9457    /// substrate primitive so every wire-up on this variant reads
9458    /// through one dispatch rather than the pre-lift five-line
9459    /// pair-destructure + struct-literal block. The `edge` pair threads
9460    /// verbatim from [`WitContract::edge_pair`] at the call site,
9461    /// matching the sibling [`AplicacaoError::contrato_endpoint_empty`] /
9462    /// [`AplicacaoError::contrato_endpoint_invalid`] ctors' shape on the
9463    /// paired two-slot and four-slot per-`:contratos :endpoint`
9464    /// envelopes on the same [`AplicacaoError`] type.
9465    #[must_use]
9466    pub fn contrato_endpoint_not_absolute(edge: (String, String), endpoint: &str) -> Self {
9467        let (de, para) = edge;
9468        Self::ContratoEndpointNotAbsolute {
9469            de,
9470            para,
9471            endpoint: endpoint.to_string(),
9472        }
9473    }
9474
9475    /// Construct an [`AplicacaoError::ContratoSelfLoop`] naming the
9476    /// offending self-edge's owning `caixa` and its `:wit` world
9477    /// reference, projecting both slots through the [`WitContract`]'s
9478    /// own [`WitContract::source`] and [`WitContract::world_ref`]
9479    /// scalar accessors on the substrate primitive.
9480    ///
9481    /// Folds the uniform `{ caixa: contract.source().to_string(), wit:
9482    /// contract.world_ref().to_string() }` two-slot struct-literal onto
9483    /// one substrate primitive so every wire-up on this variant reads
9484    /// through one dispatch rather than the pre-lift four-line
9485    /// twin-`.to_string()` struct-literal block. The `contract` borrow
9486    /// threads verbatim from the caller-side `for c in
9487    /// self.contratos()` iteration at the sole in-crate wire-up site
9488    /// [`AplicacaoSpec::validate_contratos`], matching the sibling
9489    /// per-`:contratos` `WitContract`-projection ctor discipline the
9490    /// peer [`AplicacaoError::empty_wit`] /
9491    /// [`AplicacaoError::contrato_endpoint_empty`] /
9492    /// [`AplicacaoError::contrato_subject_empty`] /
9493    /// [`AplicacaoError::contrato_slot_empty`] ctors carry through
9494    /// [`WitContract::edge_pair`] on the sibling two-slot `{ de, para }`
9495    /// envelope.
9496    ///
9497    /// The `caixa` slot is projected through [`WitContract::source`]
9498    /// rather than [`WitContract::destination`] to preserve byte-equal
9499    /// diagnostic ordering with the pre-lift open-coded body — a
9500    /// [`WitContract::is_self_loop`]-gated call site has
9501    /// `source() == destination()` by that predicate's own contract, so
9502    /// the two accessors are exchange-symmetric at this call site, but
9503    /// naming `source` at the ctor definition matches the pre-lift
9504    /// site's field selection and pins the discipline for any future
9505    /// consumer that constructs the variant against a not-yet-gated
9506    /// candidate contract (e.g. an M4
9507    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
9508    /// webhook re-checking a per-`(:de, :para)` patched contract, a
9509    /// future `feira validate --contratos` per-caixa verb re-running
9510    /// the self-loop diagnostic on demand, a per-tenant per-Aplicacao
9511    /// overlay resolver rejecting a self-edge introduced by a
9512    /// cluster-local `:contratos` override the M4 CR materializer
9513    /// projects).
9514    ///
9515    /// Peer of the sibling `WitContract`-projection ctors on the
9516    /// per-`:contratos` envelopes on the same [`AplicacaoError`] type —
9517    /// same "one typed dispatch on the substrate primitive, projecting
9518    /// through the paired [`WitContract`] accessors, thin projections
9519    /// at each consumer" discipline extended here onto the last unlifted
9520    /// two-slot `{ caixa: String, wit: String }` per-self-edge envelope
9521    /// inside [`AplicacaoSpec::validate_contratos`].
9522    #[must_use]
9523    pub fn contrato_self_loop(contract: &WitContract) -> Self {
9524        Self::ContratoSelfLoop {
9525            caixa: contract.source().to_string(),
9526            wit: contract.world_ref().to_string(),
9527        }
9528    }
9529
9530    /// Construct an [`AplicacaoError::ContratoDuplicate`] naming the
9531    /// offending duplicate edge's `(:de, :para, :wit)` triple and the
9532    /// per-payload `:target` byte-string, projecting the first three slots
9533    /// through the paired [`WitContract::edge_triple`] typed-accessor and
9534    /// the trailing `target:` slot through [`WitTarget::label`] on the
9535    /// substrate primitive.
9536    ///
9537    /// Folds the uniform `let (de, para, wit) = contract.edge_triple();
9538    /// Self::ContratoDuplicate { de, para, wit, target: target.label() }`
9539    /// six-line pair-destructure + struct-literal onto one substrate
9540    /// primitive so every wire-up on this variant reads through one
9541    /// dispatch rather than the pre-lift open-coded block inside the
9542    /// [`AplicacaoSpec::validate_contratos`] whole-edge dedup closure
9543    /// passed to [`crate::render::insert_first_seen`]. Peer of the sibling
9544    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting through
9545    /// [`WitContract::source`] / [`WitContract::world_ref`] on the paired
9546    /// per-`:contratos` self-edge two-slot envelope) and the sibling
9547    /// [`AplicacaoError::empty_wit`] (projecting through
9548    /// [`WitContract::edge_pair`] on the sibling per-`:contratos` empty-
9549    /// `:wit` two-slot envelope) `WitContract`-projection ctors on the
9550    /// same [`AplicacaoError`] type — extended here onto the last unlifted
9551    /// four-slot `{ de: String, para: String, wit: String, target: String }`
9552    /// per-`:contratos` whole-edge-dedup envelope inside
9553    /// [`AplicacaoSpec::validate_contratos`], closing the paired
9554    /// duplicate-gate diagnostic constructor site the peer
9555    /// [`WitContract::edge_triple`] (5dbcfaf) lift's doc-block flagged as
9556    /// the last unlifted composite-projection wire-up.
9557    ///
9558    /// The `contract` borrow threads verbatim from the caller-side `for c
9559    /// in self.contratos()` iteration at the sole in-crate wire-up site
9560    /// [`AplicacaoSpec::validate_contratos`], and `target` threads
9561    /// verbatim from the paired `let target_view = c.target()?` local
9562    /// materialized upstream of the [`crate::render::insert_first_seen`]
9563    /// dedup dispatch — both project onto their respective substrate-
9564    /// primitive accessors ([`WitContract::edge_triple`] +
9565    /// [`WitTarget::label`]) inside the ctor body, matching the sibling
9566    /// [`AplicacaoError::contrato_self_loop`] `WitContract`-projection
9567    /// posture verbatim on the paired self-edge envelope.
9568    ///
9569    /// Every future consumer that wants to construct this variant outside
9570    /// [`AplicacaoSpec::validate_contratos`] — a deferred
9571    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
9572    /// webhook re-checking a per-`(:de, :para, :wit, :target)`-patched
9573    /// candidate against a per-tenant `:contratos` overlay before the
9574    /// whole-edge dedup gate re-fires, a future `feira validate
9575    /// --contratos` per-caixa admission verb re-running the dedup check on
9576    /// demand, an M4 per-cluster contrato-cap resolver rejecting a
9577    /// cross-tenant duplicate-edge collision introduced by a fleet-local
9578    /// overlay the M4 CR materializer projects — now reaches this variant
9579    /// through one call rather than re-inlining the six-line pair-
9580    /// destructure + struct-literal block in lockstep with the existing
9581    /// wire-up.
9582    #[must_use]
9583    pub fn contrato_duplicate(contract: &WitContract, target: &WitTarget<'_>) -> Self {
9584        let (de, para, wit) = contract.edge_triple();
9585        Self::ContratoDuplicate {
9586            de,
9587            para,
9588            wit,
9589            target: target.label(),
9590        }
9591    }
9592
9593    /// Construct an [`AplicacaoError::MembroVersaoInvalid`] naming the
9594    /// offending `:membros :caixa` and its `:versao` requirement under
9595    /// the given `reason`. Folds the uniform `Self::MembroVersaoInvalid {
9596    /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
9597    /// reason.into() }` three-slot struct-literal onto one substrate
9598    /// primitive so every wire-up on this variant reads through one
9599    /// dispatch, matching the peer
9600    /// [`crate::SupervisorError::child_versao_invalid`] (d2ef2ec) ctor's
9601    /// shape verbatim on the sibling `SupervisorError { caixa: String,
9602    /// versao: String, reason: String }` envelope's per-`:children :versao`
9603    /// axis. `reason` accepts both `&str` literals and `format!(…)`
9604    /// outputs through the `impl Into<String>` bound so the sole
9605    /// [`AplicacaoSpec::validate_membros`] wire-up's per-`:membros`
9606    /// requirement-cascade closure (routing the shared
9607    /// [`crate::render::require_valid_versao_requirement`]-delivered
9608    /// `reason` verbatim) picks the ctor up without a per-arm wrapper
9609    /// transformation on the caller-side `reason` axis. The
9610    /// [`Membro::nome`] / [`Membro::versao_requirement`] typed-accessor
9611    /// routing the sole wire-up already threads through remains verbatim
9612    /// — the ctor's two `&str` parameters accept the two accessors'
9613    /// returns as-is with no re-allocation at the call site.
9614    #[must_use]
9615    pub fn membro_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
9616        Self::MembroVersaoInvalid {
9617            caixa: caixa.to_string(),
9618            versao: versao.to_string(),
9619            reason: reason.into(),
9620        }
9621    }
9622
9623    /// Construct an [`AplicacaoError::PlacementClusterDuplicate`] naming
9624    /// the offending `:placement :clusters` entry.
9625    ///
9626    /// Folds the uniform `Self::PlacementClusterDuplicate { cluster:
9627    /// cluster.to_string() }` one-field struct-literal onto one substrate
9628    /// primitive so every wire-up on this variant reads through one
9629    /// dispatch rather than the pre-lift three-line open-coded
9630    /// struct-literal block. The `cluster` slot threads verbatim from the
9631    /// caller-side `for c in p.clusters()` iteration at the sole in-crate
9632    /// wire-up site [`AplicacaoSpec::validate_placement_shape`], via the
9633    /// per-entry dedup closure passed to
9634    /// [`crate::render::insert_first_seen`] whose `FnOnce`-shaped ctor
9635    /// bracket accepts the free function pointer as-is.
9636    ///
9637    /// Sibling of the per-`:membros :caixa` / per-`:entrada :paths` /
9638    /// per-`:politicas <scalar>` single-slot ctor families
9639    /// ([`aplicacao_caixa_only_ctors!`] on `{ caixa: String }` at the
9640    /// peer per-membership envelope, [`aplicacao_path_only_ctors!`] on
9641    /// `{ path: String }` at the peer per-gateway envelope,
9642    /// [`aplicacao_policy_scalar_ctors!`] on `{ <field>: Copy-scalar }`
9643    /// at the peer per-`:politicas` cap-scalar envelope) on the same
9644    /// [`AplicacaoError`] type — extends the "one typed dispatch per
9645    /// substrate primitive on every single-slot per-M3-slot envelope"
9646    /// discipline onto the last unlifted `{ cluster: String }` one-slot
9647    /// per-`:placement :clusters` dedup-envelope inside
9648    /// [`AplicacaoSpec::validate_placement_shape`].
9649    ///
9650    /// Every future consumer that wants to construct this variant outside
9651    /// [`AplicacaoSpec::validate_placement_shape`] — a deferred
9652    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
9653    /// webhook re-checking a `:placement :clusters` overlay against a
9654    /// per-tenant cluster-topology snapshot, a future `feira validate
9655    /// --placement` per-caixa admission verb re-running the dedup check
9656    /// on demand, an M4 per-cluster placement resolver rejecting a
9657    /// duplicate cluster-name entry introduced by a fleet-local overlay
9658    /// the M4 CR materializer projects — now reaches this variant through
9659    /// one call rather than re-inlining the three-line struct-literal.
9660    #[must_use]
9661    pub fn placement_cluster_duplicate(cluster: &str) -> Self {
9662        Self::PlacementClusterDuplicate {
9663            cluster: cluster.to_string(),
9664        }
9665    }
9666
9667    /// Construct an [`AplicacaoError::PlacementWithoutClusters`] naming
9668    /// the offending `:placement :estrategia` scalar the empty `:clusters`
9669    /// list was declared against, projecting through the paired
9670    /// [`Placement::estrategia`] `Copy`-scalar accessor on the substrate
9671    /// primitive.
9672    ///
9673    /// Folds the uniform `Self::PlacementWithoutClusters { estrategia:
9674    /// placement.estrategia() }` one-field struct-literal onto one
9675    /// substrate primitive so every wire-up on this variant reads through
9676    /// one dispatch rather than the pre-lift three-line open-coded
9677    /// `AplicacaoError::PlacementWithoutClusters { estrategia:
9678    /// p.estrategia() }` block inside
9679    /// [`AplicacaoSpec::validate_placement`]. Same substrate-primitive-
9680    /// projection posture as the sibling
9681    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting through
9682    /// [`WitContract::source`] / [`WitContract::world_ref`] on the paired
9683    /// per-`:contratos` self-edge envelope) and the peer
9684    /// [`crate::UpgradeError::duplicate_from`] (7e52aec, projecting through
9685    /// [`crate::UpgradeFromEntry::prior_versao`] on the sibling
9686    /// per-`:upgrade-from :from` envelope) ctors — extended here onto the
9687    /// last unlifted `{ estrategia: PlacementStrategy }` one-slot
9688    /// per-`:placement` empty-clusters envelope inside
9689    /// [`AplicacaoSpec::validate_placement`].
9690    ///
9691    /// `#[must_use]` and `const fn` alike: the ctor threads the paired
9692    /// [`Placement::estrategia`] `Copy`-scalar return through one
9693    /// zero-runtime-work construction — no allocation, no owned-string
9694    /// materialization — so the pre-lift `Copy`-pass-through property the
9695    /// open-coded `p.estrategia()` field expression carried survives
9696    /// verbatim through the substrate primitive. The sibling
9697    /// [`AplicacaoError::placement_cluster_duplicate`] (92b1c92) ctor
9698    /// carries the paired `.to_string()`-owned-String allocation on the
9699    /// `{ cluster: String }` envelope; this ctor's `Copy`-scalar envelope
9700    /// preserves the zero-alloc posture at the substrate-primitive
9701    /// dispatch, matching the peer
9702    /// [`aplicacao_policy_scalar_ctors!`] (7ef425e, eight variants on
9703    /// `{ <scalar>: Copy }`) family's `const fn` posture on the sibling
9704    /// per-`:politicas` cap-scalar envelopes.
9705    ///
9706    /// Every future consumer that wants to construct this variant outside
9707    /// [`AplicacaoSpec::validate_placement`] — a deferred
9708    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
9709    /// webhook re-checking a `:placement :clusters` overlay against a
9710    /// per-tenant cluster-topology snapshot when the overlay resolves to
9711    /// an empty list, a future `feira validate --placement` per-caixa
9712    /// admission verb re-running the empty-clusters check on demand, an
9713    /// M4 per-cluster placement resolver rejecting an empty cluster pool
9714    /// after a fleet-local overlay strips every declared cluster — now
9715    /// reaches this variant through one call rather than re-inlining the
9716    /// three-line struct-literal in lockstep with the one in-crate
9717    /// wire-up site.
9718    #[must_use]
9719    pub const fn placement_without_clusters(placement: &Placement) -> Self {
9720        Self::PlacementWithoutClusters {
9721            estrategia: placement.estrategia(),
9722        }
9723    }
9724
9725    /// Construct an [`AplicacaoError::ShardKeyOnNonSharded`] naming the
9726    /// offending `:placement :estrategia` scalar and the declared-but-
9727    /// inert `:shard-key` value the non-`Sharded` arm refused, projecting
9728    /// the strategy through the paired [`Placement::estrategia`]
9729    /// `Copy`-scalar accessor on the substrate primitive.
9730    ///
9731    /// Folds the uniform `Self::ShardKeyOnNonSharded { estrategia:
9732    /// placement.estrategia(), shard_key: shard_key.to_string() }`
9733    /// two-slot struct-literal onto one substrate primitive so every
9734    /// wire-up on this variant reads through one dispatch rather than
9735    /// the pre-lift four-line open-coded struct-literal block inside
9736    /// [`AplicacaoSpec::validate_placement`]'s
9737    /// `PlacementStrategy::Replicated | PlacementStrategy::SingleNode`
9738    /// arm. Same substrate-primitive-projection posture as the sibling
9739    /// [`AplicacaoError::placement_without_clusters`] (b0d24ba,
9740    /// projecting through [`Placement::estrategia`] on the peer
9741    /// `{ estrategia: PlacementStrategy }` one-slot per-`:placement`
9742    /// empty-clusters envelope) and the peer
9743    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting
9744    /// through [`WitContract::source`] / [`WitContract::world_ref`] on
9745    /// the paired per-`:contratos` self-edge envelope) ctors — extended
9746    /// here onto the last unlifted `{ estrategia: PlacementStrategy,
9747    /// shard_key: String }` two-slot per-`:placement :shard-key`
9748    /// declared-but-inert envelope on the sibling non-`Sharded`-arm
9749    /// partition.
9750    ///
9751    /// The `shard_key: &str` parameter accepts both the `Some(k)`-bound
9752    /// `&str` from the sole in-crate wire-up site (narrowed from
9753    /// `Option<&str>` via [`Placement::shard_key`]) and any future
9754    /// `&String` deref from a downstream consumer that reaches for the
9755    /// slot through the paired accessor, materializing the owned
9756    /// [`String`] via one `.to_string()` at the substrate primitive so
9757    /// no per-arm `.to_string()` allocation lives at the caller. The
9758    /// `estrategia` slot threads through [`Placement::estrategia`]'s
9759    /// `Copy`-scalar return rather than accepting a bare
9760    /// [`PlacementStrategy`] argument, matching the peer
9761    /// [`AplicacaoError::placement_without_clusters`] discipline —
9762    /// carrying the [`Placement`] borrow through one accessor call at
9763    /// the substrate primitive is strictly stronger than accepting the
9764    /// scalar as a separate argument (a future caller that constructs
9765    /// the error against a candidate [`Placement`] whose
9766    /// [`Placement::estrategia`] value the caller re-derives from
9767    /// another source can silently disagree with the storage the
9768    /// [`Placement`] carries; the accessor-projected primitive cannot).
9769    ///
9770    /// Peer of the sibling per-`:placement` single-slot / two-slot ctor
9771    /// families on the same [`AplicacaoError`] type — same "one typed
9772    /// dispatch on the substrate primitive, projecting through the
9773    /// paired [`Placement`] accessors, thin projections at each
9774    /// consumer" discipline extended here onto the last unlifted
9775    /// per-`:placement :shard-key` non-`Sharded`-arm envelope inside
9776    /// [`AplicacaoSpec::validate_placement`].
9777    ///
9778    /// Every future consumer that wants to construct this variant
9779    /// outside [`AplicacaoSpec::validate_placement`] — a deferred
9780    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
9781    /// webhook re-checking a `:placement (:estrategia Replicated
9782    /// :shard-key …)` overlay against a per-tenant cluster-topology
9783    /// snapshot, a future `feira validate --placement` per-caixa
9784    /// admission verb re-running the non-`Sharded`-arm refusal on
9785    /// demand, an M4 per-cluster placement resolver rejecting a
9786    /// declared-but-inert `:shard-key` introduced by a fleet-local
9787    /// overlay the M4 CR materializer projects — now reaches this
9788    /// variant through one call rather than re-inlining the four-line
9789    /// struct-literal in lockstep with the one in-crate wire-up site.
9790    #[must_use]
9791    pub fn shard_key_on_non_sharded(placement: &Placement, shard_key: &str) -> Self {
9792        Self::ShardKeyOnNonSharded {
9793            estrategia: placement.estrategia(),
9794            shard_key: shard_key.to_string(),
9795        }
9796    }
9797
9798    /// Construct an [`AplicacaoError::EntradaMemberMissing`] naming the
9799    /// offending `:entrada :para` value the membership lookup against the
9800    /// [`AplicacaoSpec::membro_names`] oracle refused, projecting the
9801    /// slot through the paired [`Entrada::destination`] byte-string
9802    /// accessor on the substrate primitive.
9803    ///
9804    /// Folds the uniform `Self::EntradaMemberMissing { para:
9805    /// entrada.destination().to_string() }` one-field struct-literal onto
9806    /// one substrate primitive so every wire-up on this variant reads
9807    /// through one dispatch rather than the pre-lift three-line
9808    /// open-coded `AplicacaoError::EntradaMemberMissing { para:
9809    /// e.destination().to_string() }` block inside
9810    /// [`AplicacaoSpec::validate_entrada`]. Same substrate-primitive-
9811    /// projection posture as the sibling
9812    /// [`AplicacaoError::placement_without_clusters`] (b0d24ba,
9813    /// projecting through [`Placement::estrategia`] on the peer
9814    /// `{ estrategia: PlacementStrategy }` one-slot per-`:placement`
9815    /// empty-clusters envelope) and the sibling
9816    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting
9817    /// through [`WitContract::source`] / [`WitContract::world_ref`] on
9818    /// the paired per-`:contratos` self-edge envelope) ctors — extended
9819    /// here onto the last unlifted `{ para: String }` one-slot
9820    /// per-`:entrada :para` phantom-reference envelope on the sibling
9821    /// per-`:entrada` slot.
9822    ///
9823    /// The `entrada: &Entrada` parameter threads verbatim from the
9824    /// caller-side `if let Some(e) = self.entrada() { … }` traversal at
9825    /// the sole in-crate wire-up site
9826    /// [`AplicacaoSpec::validate_entrada`], matching the sibling
9827    /// per-`:entrada` byte-string reads that already route through
9828    /// [`Entrada::destination`] one accessor call earlier in the same
9829    /// gate (`validate_entrada_para(e.destination())?;` +
9830    /// `if !names.contains(e.destination()) …`). Carrying the [`Entrada`]
9831    /// borrow through one accessor call at the substrate primitive is
9832    /// strictly stronger than accepting the bare `&str` as a separate
9833    /// argument — a future consumer that constructs the error against a
9834    /// candidate [`Entrada`] whose [`Entrada::destination`] value the
9835    /// caller re-derives from another source (a raw `e.para` field
9836    /// access that skipped the accessor, a stale snapshot of the
9837    /// pre-normalization storage) can silently disagree with the
9838    /// storage the [`Entrada`] carries; the accessor-projected primitive
9839    /// cannot. Matches the peer
9840    /// [`AplicacaoError::placement_without_clusters`] and
9841    /// [`AplicacaoError::shard_key_on_non_sharded`]
9842    /// [`Placement`]-borrow-projection discipline on the sibling
9843    /// per-`:placement` envelope, and matches the peer
9844    /// [`AplicacaoError::contrato_self_loop`] and
9845    /// [`AplicacaoError::contrato_endpoint_not_absolute`]
9846    /// [`WitContract`]-borrow-projection discipline on the sibling
9847    /// per-`:contratos` envelope.
9848    ///
9849    /// Every future consumer that wants to construct this variant
9850    /// outside [`AplicacaoSpec::validate_entrada`] — a deferred
9851    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
9852    /// webhook re-checking a `:entrada :para` overlay against a
9853    /// per-tenant `:membros` snapshot after a fleet-local overlay
9854    /// renames a member, a future `feira validate --entrada` per-caixa
9855    /// admission verb re-running the phantom-reference lookup on
9856    /// demand, an M4 per-cluster Gateway API pre-emitter rejecting a
9857    /// `:entrada :para` whose target Servico was stripped from the
9858    /// cluster-local `:membros` overlay, a future authoring-surface
9859    /// widening the field into a `(String, Vec<Suggestion>)` pair
9860    /// carrying a "did-you-mean-<nearest-member>" hint — now reaches
9861    /// this variant through one call rather than re-inlining the
9862    /// three-line struct-literal in lockstep with the one in-crate
9863    /// wire-up site.
9864    #[must_use]
9865    pub fn entrada_member_missing(entrada: &Entrada) -> Self {
9866        Self::EntradaMemberMissing {
9867            para: entrada.destination().to_string(),
9868        }
9869    }
9870
9871    /// Construct an [`AplicacaoError::ContratoCycle`] naming the
9872    /// synchronous-`:contratos` cycle path the DFS-with-three-coloring
9873    /// sync-only-subgraph gate at
9874    /// [`AplicacaoSpec::detect_sync_cycles`] reconstructed from the
9875    /// gray-arm's back-edge target through the parent chain, folding the
9876    /// uniform `Self::ContratoCycle { cycle }` one-field struct-literal
9877    /// onto one substrate primitive so every wire-up on this variant
9878    /// reads through one dispatch rather than the pre-lift open-coded
9879    /// `AplicacaoError::ContratoCycle { cycle }` block at the sole
9880    /// in-crate wire-up site inside
9881    /// [`AplicacaoSpec::detect_sync_cycles`]'s gray-arm cycle-close
9882    /// return. Same substrate-primitive-projection posture as the
9883    /// sibling [`AplicacaoError::entrada_member_missing`] (deeae5c,
9884    /// projecting through [`Entrada::destination`] on the peer `{ para:
9885    /// String }` one-slot per-`:entrada :para` phantom-reference
9886    /// envelope) and [`AplicacaoError::placement_without_clusters`]
9887    /// (b0d24ba, projecting through [`Placement::estrategia`] on the
9888    /// sibling `{ estrategia: PlacementStrategy }` one-slot
9889    /// per-`:placement` empty-clusters envelope) ctors — extended here
9890    /// onto the last unlifted `{ cycle: Vec<String> }` one-slot
9891    /// per-`:contratos` cross-edge sync-cycle envelope on the same
9892    /// [`AplicacaoError`] type. Closes the last unlifted `AplicacaoError`
9893    /// struct-literal wire-up under
9894    /// [`AplicacaoSpec::detect_sync_cycles`].
9895    ///
9896    /// The `cycle: Vec<String>` parameter threads verbatim from the
9897    /// caller-side DFS traversal's reconstructed cycle path (built up by
9898    /// walking `parent` from the gray-back-edge's source node back to
9899    /// its target, reversing, then appending the target once more so the
9900    /// first and last elements coincide by construction and the
9901    /// `Display` rendering under the [`AplicacaoError::ContratoCycle`]
9902    /// `cycle.join(" → ")` formatter reads as a closed loop), matching
9903    /// the pre-lift open-coded body's field selection exactly. Taking
9904    /// the owned [`Vec<String>`] rather than a borrowed slice + collect
9905    /// on the ctor side keeps the pre-lift wire-up byte-identical (the
9906    /// caller already owns the reconstructed [`Vec<String>`] at the
9907    /// gray-arm return, so no per-arm re-allocation lands on the ctor
9908    /// path).
9909    ///
9910    /// Peer of the sibling per-`:contratos` single-slot / two-slot ctor
9911    /// families on the same [`AplicacaoError`] type — same "one typed
9912    /// dispatch on the substrate primitive, thin projections at each
9913    /// consumer" discipline extended here onto the last unlifted
9914    /// per-`:contratos` cross-edge cycle envelope inside
9915    /// [`AplicacaoSpec::detect_sync_cycles`].
9916    ///
9917    /// Every future consumer that wants to construct this variant
9918    /// outside [`AplicacaoSpec::detect_sync_cycles`] — a deferred
9919    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
9920    /// webhook re-checking a per-tenant `:contratos` overlay's
9921    /// sync-cycle invariant after a fleet-local overlay adds or removes
9922    /// a synchronous edge, a future `feira validate --contratos`
9923    /// per-caixa admission verb re-running the cross-edge cycle detector
9924    /// on demand, the M4 per-edge policy resolver MESH-COMPOSITION §III.2
9925    /// #3 acknowledges (whose per-edge patch mutates one `:contratos`
9926    /// entry and needs to re-probe *just* the cycle invariant against
9927    /// the post-patch adjacency), a future authoring-surface widening
9928    /// the field into a `(Vec<String>, Vec<WitTarget>)` pair carrying
9929    /// the per-hop WIT shape for a richer "break here" hint — now
9930    /// reaches this variant through one call rather than re-inlining the
9931    /// open-coded struct-literal in lockstep with the one in-crate
9932    /// wire-up site.
9933    #[must_use]
9934    pub fn contrato_cycle(cycle: Vec<String>) -> Self {
9935        Self::ContratoCycle { cycle }
9936    }
9937
9938    /// Construct an [`AplicacaoError::PolicyBreakerWindowBelowTimeout`]
9939    /// naming the offending `:politicas :circuit-breaker :window` and
9940    /// the paired `:politicas :timeout` scalars under the first-firing
9941    /// cross-axis-violation gate at
9942    /// [`MeshPolicy::first_cross_axis_violation`], projecting the
9943    /// `window` slot through the [`CircuitBreaker::window`] scalar
9944    /// accessor on the substrate primitive.
9945    ///
9946    /// Folds the uniform `{ window: cb.window(), timeout: t }`
9947    /// two-slot `Copy`-`Duration` struct-literal onto one substrate
9948    /// primitive so every wire-up on this variant reads through one
9949    /// dispatch rather than the pre-lift four-line struct-literal
9950    /// block. The `cb` borrow threads verbatim from the caller-side
9951    /// `if let (Some(t), Some(cb)) = (self.timeout(),
9952    /// self.circuit_breaker())` pair-destructure at the sole in-crate
9953    /// wire-up site inside [`MeshPolicy::first_cross_axis_violation`]'s
9954    /// window-below-timeout arm; `timeout` threads verbatim from the
9955    /// paired [`MeshPolicy::timeout`] accessor return already
9956    /// destructured out of the same `if let` pair. `const fn`
9957    /// preserves the pre-lift `Copy`-pass-through's zero-runtime-work
9958    /// property verbatim (both fields are [`Duration`], the
9959    /// [`CircuitBreaker::window`] accessor is itself `const fn`, and
9960    /// no `.to_string()` / `.into()` allocation lands on the ctor
9961    /// path).
9962    ///
9963    /// The `window` slot is projected through [`CircuitBreaker::window`]
9964    /// (not spelled out as a bare `Duration` parameter) so a future
9965    /// widening of the `:circuit-breaker :window` axis — a
9966    /// per-`:contratos`-edge `:circuit-breaker :window` override the
9967    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a promotion of
9968    /// the plain [`Duration`] window to a richer per-status-class
9969    /// window tuple once Envoy's `outlier_detection.interval` peers
9970    /// come into scope — reaches the diagnostic through one accessor
9971    /// swap rather than every wire-up in lockstep, matching the peer
9972    /// substrate-primitive-projection posture of
9973    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting
9974    /// through [`WitContract::source`] / [`WitContract::world_ref`] on
9975    /// the sibling `{ caixa: String, wit: String }` two-slot
9976    /// per-`:contratos` self-edge envelope),
9977    /// [`AplicacaoError::entrada_member_missing`] (deeae5c, projecting
9978    /// through [`Entrada::destination`] on the sibling `{ para: String }`
9979    /// one-slot per-`:entrada :para` phantom-reference envelope), and
9980    /// [`AplicacaoError::shard_key_on_non_sharded`] (14bafca, projecting
9981    /// through [`Placement::estrategia`] on the sibling `{ estrategia:
9982    /// PlacementStrategy, shard_key: String }` two-slot per-`:placement`
9983    /// envelope) ctors carry on the sibling `:contratos` / `:entrada`
9984    /// / `:placement` envelopes.
9985    ///
9986    /// Peer of the sibling per-axis [`aplicacao_policy_scalar_ctors!`]
9987    /// (7ef425e) macro that folds the eight one-slot per-`:politicas`
9988    /// `{ <field>: Copy-scalar }` envelopes on the per-axis
9989    /// [`MeshPolicy::validate`] gate — extended here onto the
9990    /// first-firing cross-axis compound variant, whose multi-slot
9991    /// `{ window: Duration, timeout: Duration }` shape does not fit
9992    /// that macro's one-`Copy`-scalar-per-variant arity. The three
9993    /// remaining cross-axis variants
9994    /// ([`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`] on
9995    /// the four-slot `{ rate, rl_window, max_failures, cb_window }`
9996    /// envelope, [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
9997    /// on the two-slot `{ retries, max_failures }` envelope, and
9998    /// [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] on the
9999    /// two-slot `{ retries, rate }` envelope) each carry a distinct
10000    /// substrate-primitive-projection shape and are folded on their
10001    /// own axis by their own per-variant ctors as those wire-ups are
10002    /// lifted.
10003    ///
10004    /// Every future consumer that wants to construct this variant
10005    /// outside [`MeshPolicy::first_cross_axis_violation`] — a deferred
10006    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
10007    /// webhook re-checking a per-tenant `:politicas` overlay's
10008    /// window-vs-timeout cross-axis invariant after a cluster-local
10009    /// `:politicas` override the MESH-COMPOSITION §III.2 #3 roadmap
10010    /// acknowledges resolves an *effective* per-edge [`MeshPolicy`], a
10011    /// future per-`:contratos`-edge `:politicas` override the M4 CR
10012    /// resolver projects, an M4 per-cluster `:politicas`-cap resolver
10013    /// projecting a per-tenant per-axis ceiling into the same
10014    /// diagnostic shape — now reaches this variant through one call
10015    /// rather than re-inlining the open-coded struct-literal in
10016    /// lockstep with the one in-crate wire-up site.
10017    #[must_use]
10018    pub const fn policy_breaker_window_below_timeout(
10019        cb: &CircuitBreaker,
10020        timeout: Duration,
10021    ) -> Self {
10022        Self::PolicyBreakerWindowBelowTimeout {
10023            window: cb.window(),
10024            timeout,
10025        }
10026    }
10027
10028    /// Construct an [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`]
10029    /// naming the `(:politicas :rate-limit, :politicas :circuit-breaker)`
10030    /// cross-axis pair whose token-bucket window structurally starves the
10031    /// breaker so `:max-failures` cannot be reached inside `:circuit-breaker
10032    /// :window`.
10033    ///
10034    /// Folds the uniform `{ rate: rl.rate(), rl_window: rl.window(),
10035    /// max_failures: cb.max_failures(), cb_window: cb.window() }`
10036    /// four-slot `Copy`-`(u32 | Duration)` struct-literal onto one substrate
10037    /// primitive so every wire-up on this variant reads through one dispatch
10038    /// rather than the pre-lift six-line struct-literal block. Both `rl` and
10039    /// `cb` borrows thread verbatim from the caller-side `if let (Some(rl),
10040    /// Some(cb)) = (self.rate_limit(), self.circuit_breaker())`
10041    /// pair-destructure at the sole in-crate wire-up site inside
10042    /// [`MeshPolicy::first_cross_axis_violation`]'s starve-under-rate-limit
10043    /// arm. `const fn` preserves the pre-lift `Copy`-pass-through's
10044    /// zero-runtime-work property verbatim (all four fields are `u32` /
10045    /// [`Duration`], every projected accessor is itself `const fn`, and no
10046    /// `.to_string()` / `.into()` allocation lands on the ctor path).
10047    ///
10048    /// Every slot is projected through its paired substrate-primitive
10049    /// accessor ([`RateLimit::rate`], [`RateLimit::window`],
10050    /// [`CircuitBreaker::max_failures`], [`CircuitBreaker::window`]) rather
10051    /// than spelled out as bare `u32` / [`Duration`] parameters so a future
10052    /// widening of either axis — a per-`:contratos`-edge `:rate-limit` or
10053    /// `:circuit-breaker` override the MESH-COMPOSITION §III.2 #3 roadmap
10054    /// acknowledges, a promotion of the plain scalar rate to a richer
10055    /// per-status-class token bucket once Envoy's per-descriptor
10056    /// `local_rate_limit` peers come into scope — reaches the diagnostic
10057    /// through one accessor swap rather than every wire-up in lockstep.
10058    /// Matches the peer substrate-primitive-projection posture of
10059    /// [`AplicacaoError::policy_breaker_window_below_timeout`] (9b30c07,
10060    /// projecting through [`CircuitBreaker::window`] on the sibling
10061    /// two-slot `{ window, timeout }` cross-axis
10062    /// `(:timeout, :circuit-breaker)` envelope) on the sibling
10063    /// first-firing cross-axis compound variant.
10064    ///
10065    /// Second cross-axis Policy* variant folded onto its own per-variant
10066    /// substrate primitive — extending the peer
10067    /// [`AplicacaoError::policy_breaker_window_below_timeout`] discipline
10068    /// onto the second-firing cross-axis compound variant, whose four-slot
10069    /// `{ rate, rl_window, max_failures, cb_window }` shape does not fit
10070    /// the sibling two-slot ctor's arity. The two remaining cross-axis
10071    /// variants ([`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
10072    /// on the two-slot `{ retries, max_failures }` envelope and
10073    /// [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] on the
10074    /// two-slot `{ retries, rate }` envelope) each carry a distinct
10075    /// substrate-primitive-projection shape and are folded on their own
10076    /// axis by their own per-variant ctors as those wire-ups are lifted.
10077    ///
10078    /// Every future consumer that wants to construct this variant outside
10079    /// [`MeshPolicy::first_cross_axis_violation`] — a deferred
10080    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
10081    /// webhook re-checking a per-tenant `:politicas` overlay's
10082    /// starve-under-rate-limit cross-axis invariant after a cluster-local
10083    /// `:politicas` override the MESH-COMPOSITION §III.2 #3 roadmap
10084    /// acknowledges resolves an *effective* per-edge [`MeshPolicy`], a
10085    /// future per-`:contratos`-edge `:politicas` override the M4 CR
10086    /// resolver projects, an M4 per-cluster `:politicas`-cap resolver
10087    /// projecting a per-tenant per-axis ceiling into the same diagnostic
10088    /// shape — now reaches this variant through one call rather than
10089    /// re-inlining the open-coded struct-literal in lockstep with the one
10090    /// in-crate wire-up site.
10091    #[must_use]
10092    pub const fn policy_breaker_cannot_trip_under_rate_limit(
10093        rl: &RateLimit,
10094        cb: &CircuitBreaker,
10095    ) -> Self {
10096        Self::PolicyBreakerCannotTripUnderRateLimit {
10097            rate: rl.rate(),
10098            rl_window: rl.window(),
10099            max_failures: cb.max_failures(),
10100            cb_window: cb.window(),
10101        }
10102    }
10103
10104    /// Construct an
10105    /// [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
10106    /// naming the offending `:politicas :retries` and the paired
10107    /// `:politicas :circuit-breaker :max-failures` scalars under the
10108    /// third-firing cross-axis-violation gate at
10109    /// [`MeshPolicy::first_cross_axis_violation`], projecting the
10110    /// `max_failures` slot through the [`CircuitBreaker::max_failures`]
10111    /// scalar accessor on the substrate primitive.
10112    ///
10113    /// Folds the uniform `{ retries, max_failures: cb.max_failures() }`
10114    /// two-slot `Copy`-`u32` struct-literal onto one substrate
10115    /// primitive so every wire-up on this variant reads through one
10116    /// dispatch rather than the pre-lift four-line struct-literal
10117    /// block. The `cb` borrow threads verbatim from the caller-side
10118    /// `if let (Some(retries), Some(cb)) = (self.retries(),
10119    /// self.circuit_breaker())` pair-destructure at the sole in-crate
10120    /// wire-up site inside [`MeshPolicy::first_cross_axis_violation`]'s
10121    /// retries-saturate arm; `retries` threads verbatim from the paired
10122    /// [`MeshPolicy::retries`] accessor return already destructured out
10123    /// of the same `if let` pair. `const fn` preserves the pre-lift
10124    /// `Copy`-pass-through's zero-runtime-work property verbatim (both
10125    /// fields are `u32`, the [`CircuitBreaker::max_failures`] accessor
10126    /// is itself `const fn`, and no `.to_string()` / `.into()`
10127    /// allocation lands on the ctor path).
10128    ///
10129    /// The `max_failures` slot is projected through
10130    /// [`CircuitBreaker::max_failures`] (not spelled out as a bare
10131    /// `u32` parameter) so a future widening of the
10132    /// `:circuit-breaker :max-failures` axis — a
10133    /// per-`:contratos`-edge `:circuit-breaker :max-failures` override
10134    /// the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-tenant
10135    /// `:max-failures` ceiling the M4 per-cluster `:politicas`-cap
10136    /// resolver projects, a promotion of the plain `u32` count to a
10137    /// richer per-status-class trip counter once Envoy's
10138    /// `outlier_detection.consecutive_5xx` peers come into scope —
10139    /// reaches the diagnostic through one accessor swap rather than
10140    /// every wire-up in lockstep, matching the peer
10141    /// substrate-primitive-projection posture of
10142    /// [`AplicacaoError::policy_breaker_window_below_timeout`]
10143    /// (9b30c07, projecting through [`CircuitBreaker::window`] on the
10144    /// sibling two-slot `{ window, timeout }` first cross-axis
10145    /// envelope) and
10146    /// [`AplicacaoError::policy_breaker_cannot_trip_under_rate_limit`]
10147    /// (6bb4e46, projecting through [`RateLimit::rate`] /
10148    /// [`RateLimit::window`] / [`CircuitBreaker::max_failures`] /
10149    /// [`CircuitBreaker::window`] on the sibling four-slot second
10150    /// cross-axis envelope). `retries` remains a bare `u32` parameter,
10151    /// matching the sibling first-arm ctor's bare `timeout: Duration`
10152    /// parameter discipline: [`MeshPolicy::retries`] returns
10153    /// `Option<u32>` and the caller-side `if let` already destructures
10154    /// the inner `u32` out, so the ctor takes the destructured scalar
10155    /// verbatim rather than re-wrapping it into an accessor call.
10156    ///
10157    /// Peer of the sibling per-axis [`aplicacao_policy_scalar_ctors!`]
10158    /// (7ef425e) macro that folds the eight one-slot per-`:politicas`
10159    /// `{ <field>: Copy-scalar }` envelopes on the per-axis
10160    /// [`MeshPolicy::validate`] gate — extended here onto the
10161    /// third-firing cross-axis compound variant, whose multi-slot
10162    /// `{ retries: u32, max_failures: u32 }` shape does not fit that
10163    /// macro's one-`Copy`-scalar-per-variant arity. The one remaining
10164    /// cross-axis variant
10165    /// ([`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] on the
10166    /// two-slot `{ retries, rate }` envelope) carries a distinct
10167    /// substrate-primitive-projection shape (projecting through
10168    /// [`RateLimit::rate`] rather than
10169    /// [`CircuitBreaker::max_failures`]) and is folded on its own axis
10170    /// by its own per-variant ctor as that wire-up is lifted in a
10171    /// follow-up run.
10172    ///
10173    /// Every future consumer that wants to construct this variant
10174    /// outside [`MeshPolicy::first_cross_axis_violation`] — a deferred
10175    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
10176    /// webhook re-checking a per-tenant `:politicas` overlay's
10177    /// retries-vs-max-failures cross-axis invariant after a
10178    /// cluster-local `:politicas` override the MESH-COMPOSITION §III.2
10179    /// #3 roadmap acknowledges resolves an *effective* per-edge
10180    /// [`MeshPolicy`], a future per-`:contratos`-edge `:politicas`
10181    /// override the M4 CR resolver projects, an M4 per-cluster
10182    /// `:politicas`-cap resolver projecting a per-tenant per-axis
10183    /// ceiling into the same diagnostic shape — now reaches this
10184    /// variant through one call rather than re-inlining the open-coded
10185    /// struct-literal in lockstep with the one in-crate wire-up site.
10186    #[must_use]
10187    pub const fn policy_breaker_trips_before_retries_exhausted(
10188        retries: u32,
10189        cb: &CircuitBreaker,
10190    ) -> Self {
10191        Self::PolicyBreakerTripsBeforeRetriesExhausted {
10192            retries,
10193            max_failures: cb.max_failures(),
10194        }
10195    }
10196
10197    /// Construct an
10198    /// [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] naming
10199    /// the offending `:politicas :retries` and the paired `:politicas
10200    /// :rate-limit` `:rate` scalars under the fourth-firing (and last-
10201    /// remaining) cross-axis-violation gate at
10202    /// [`MeshPolicy::first_cross_axis_violation`], projecting the `rate`
10203    /// slot through the [`RateLimit::rate`] scalar accessor on the
10204    /// substrate primitive.
10205    ///
10206    /// Folds the uniform `{ retries, rate: rl.rate() }` two-slot
10207    /// `Copy`-`u32` struct-literal onto one substrate primitive so every
10208    /// wire-up on this variant reads through one dispatch rather than
10209    /// the pre-lift four-line struct-literal block. The `rl` borrow
10210    /// threads verbatim from the caller-side `if let (Some(retries),
10211    /// Some(rl)) = (self.retries(), self.rate_limit())` pair-destructure
10212    /// at the sole in-crate wire-up site inside
10213    /// [`MeshPolicy::first_cross_axis_violation`]'s starve-under-rate-
10214    /// limit arm; `retries` threads verbatim from the paired
10215    /// [`MeshPolicy::retries`] accessor return already destructured out
10216    /// of the same `if let` pair. `const fn` preserves the pre-lift
10217    /// `Copy`-pass-through's zero-runtime-work property verbatim (both
10218    /// fields are `u32`, the [`RateLimit::rate`] accessor is itself
10219    /// `const fn`, and no `.to_string()` / `.into()` allocation lands on
10220    /// the ctor path).
10221    ///
10222    /// The `rate` slot is projected through [`RateLimit::rate`] (not
10223    /// spelled out as a bare `u32` parameter) so a future widening of
10224    /// the `:rate-limit` `:rate` axis — a per-`:contratos`-edge
10225    /// `:rate-limit` `:rate` override the MESH-COMPOSITION §III.2 #3
10226    /// roadmap acknowledges, a per-tenant `:rate` ceiling the M4
10227    /// per-cluster `:politicas`-cap resolver projects, a promotion of
10228    /// the plain `u32` token capacity to a richer
10229    /// `{max_tokens, tokens_per_fill}` tuple once Envoy's
10230    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
10231    /// axis comes into scope — reaches the diagnostic through one
10232    /// accessor swap rather than every wire-up in lockstep, matching
10233    /// the peer substrate-primitive-projection posture of
10234    /// [`AplicacaoError::policy_breaker_window_below_timeout`] (9b30c07,
10235    /// projecting through [`CircuitBreaker::window`] on the sibling
10236    /// two-slot `{ window, timeout }` first cross-axis envelope),
10237    /// [`AplicacaoError::policy_breaker_cannot_trip_under_rate_limit`]
10238    /// (6bb4e46, projecting through [`RateLimit::rate`] /
10239    /// [`RateLimit::window`] / [`CircuitBreaker::max_failures`] /
10240    /// [`CircuitBreaker::window`] on the sibling four-slot second
10241    /// cross-axis envelope), and
10242    /// [`AplicacaoError::policy_breaker_trips_before_retries_exhausted`]
10243    /// (f54c539, projecting through [`CircuitBreaker::max_failures`] on
10244    /// the sibling two-slot `{ retries, max_failures }` third cross-axis
10245    /// envelope). `retries` remains a bare `u32` parameter, matching
10246    /// the sibling third-arm ctor's bare `retries: u32` parameter
10247    /// discipline: [`MeshPolicy::retries`] returns `Option<u32>` and the
10248    /// caller-side `if let` already destructures the inner `u32` out, so
10249    /// the ctor takes the destructured scalar verbatim rather than
10250    /// re-wrapping it into an accessor call.
10251    ///
10252    /// Peer of the sibling per-axis [`aplicacao_policy_scalar_ctors!`]
10253    /// (7ef425e) macro that folds the eight one-slot per-`:politicas`
10254    /// `{ <field>: Copy-scalar }` envelopes on the per-axis
10255    /// [`MeshPolicy::validate`] gate — extended here onto the
10256    /// fourth-firing (and final) cross-axis compound variant, whose
10257    /// multi-slot `{ retries: u32, rate: u32 }` shape does not fit that
10258    /// macro's one-`Copy`-scalar-per-variant arity. After this lift all
10259    /// four cross-axis [`MeshPolicy::first_cross_axis_violation`] arms
10260    /// read through one substrate-primitive ctor dispatch each; the
10261    /// per-envelope compound cross-axis Policy* family closes on this
10262    /// variant.
10263    ///
10264    /// Every future consumer that wants to construct this variant
10265    /// outside [`MeshPolicy::first_cross_axis_violation`] — a deferred
10266    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
10267    /// webhook re-checking a per-tenant `:politicas` overlay's
10268    /// retries-vs-rate cross-axis invariant after a cluster-local
10269    /// `:politicas` override the MESH-COMPOSITION §III.2 #3 roadmap
10270    /// acknowledges resolves an *effective* per-edge [`MeshPolicy`], a
10271    /// future per-`:contratos`-edge `:politicas` override the M4 CR
10272    /// resolver projects, an M4 per-cluster `:politicas`-cap resolver
10273    /// projecting a per-tenant per-axis ceiling into the same diagnostic
10274    /// shape — now reaches this variant through one call rather than
10275    /// re-inlining the open-coded struct-literal in lockstep with the
10276    /// one in-crate wire-up site.
10277    #[must_use]
10278    pub const fn policy_rate_limit_cannot_admit_retry_burst(retries: u32, rl: &RateLimit) -> Self {
10279        Self::PolicyRateLimitCannotAdmitRetryBurst {
10280            retries,
10281            rate: rl.rate(),
10282        }
10283    }
10284
10285    /// Construct an [`AplicacaoError::ContratoCaixaInvalid`] naming the
10286    /// offending `:contratos <slot>` (`:de` / `:para`) and the value
10287    /// that broke the shared DNS-1123-label floor under the given
10288    /// `reason`. Folds the uniform `Self::ContratoCaixaInvalid { slot,
10289    /// caixa: caixa.to_string(), reason: reason.into() }` three-slot
10290    /// struct-literal onto one substrate primitive so every wire-up on
10291    /// this variant reads through one dispatch rather than the pre-lift
10292    /// six-line struct-literal block inside
10293    /// [`validate_contrato_caixa`]'s
10294    /// [`crate::render::require_valid_dns_1123_label`]
10295    /// `|reason| …` closure.
10296    ///
10297    /// Sibling of the per-axis [`aplicacao_field_reason_ctors!`]
10298    /// (981060b) macro-generated ctor family
10299    /// ([`AplicacaoError::membro_caixa_invalid`],
10300    /// [`AplicacaoError::entrada_para_invalid`],
10301    /// [`AplicacaoError::entrada_host_invalid`],
10302    /// [`AplicacaoError::entrada_path_invalid`],
10303    /// [`AplicacaoError::placement_cluster_invalid`],
10304    /// [`AplicacaoError::placement_affinity_invalid`],
10305    /// [`AplicacaoError::shard_key_invalid`]) — extends the "one typed
10306    /// dispatch per substrate primitive on every `{ <field>: String,
10307    /// reason: String }` per-axis parser-shaped envelope" discipline
10308    /// onto the sole unlifted three-slot `{ slot: &'static str, caixa:
10309    /// String, reason: String }` sibling whose extra `slot: &'static
10310    /// str` axis-tag distinguishes the two-arm `:de` / `:para` cascade
10311    /// on the per-`:contratos`-edge value axis and so does not fit the
10312    /// two-slot macro's arity.
10313    ///
10314    /// `slot` carries the kebab-case `:de` / `:para` tag verbatim
10315    /// (`&'static str` is `Copy`, no allocation), matching the caller-
10316    /// side [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
10317    /// [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] `const` strings the
10318    /// sole in-crate wire-up threads through. `reason: impl
10319    /// Into<String>` accepts both `&str` literals and the shared
10320    /// [`crate::render::require_valid_dns_1123_label`]-delivered
10321    /// owned-`String` return verbatim so the closure picks the ctor up
10322    /// without a per-arm wrapper transformation, matching the peer
10323    /// [`aplicacao_field_reason_ctors!`] family's `reason: impl
10324    /// Into<String>` bound. `#[must_use]` fires a compile warning at
10325    /// any wire-up that mistakenly discards the constructed error
10326    /// rather than routing it through `return Err(…)` / `.map_err(…)`
10327    /// / a closure return.
10328    ///
10329    /// Every future consumer that wants to construct this variant
10330    /// outside the current in-crate wire-up (the deferred
10331    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
10332    /// per-`:contratos`-edge admission validator projecting the same
10333    /// diagnostic through the caller-facing `slot: &'static str` tag,
10334    /// a future `feira validate --contratos` per-caixa admission verb,
10335    /// an M4 per-`:contratos`-edge pre-emitter running the same
10336    /// DNS-1123-label floor against a caller-supplied `:de` / `:para`
10337    /// pair before hitting the apiserver-side selector, an M4
10338    /// per-cluster contrato-cap resolver rejecting a cross-tenant
10339    /// selector projection into the same diagnostic shape) — now
10340    /// reaches this variant through one call rather than re-inlining
10341    /// the six-line struct-literal block in lockstep with the one
10342    /// in-crate wire-up site.
10343    #[must_use]
10344    pub fn contrato_caixa_invalid(
10345        slot: &'static str,
10346        caixa: &str,
10347        reason: impl Into<String>,
10348    ) -> Self {
10349        Self::ContratoCaixaInvalid {
10350            slot,
10351            caixa: caixa.to_string(),
10352            reason: reason.into(),
10353        }
10354    }
10355
10356    /// Construct an [`AplicacaoError::ContratoCaixaEmpty`] naming the
10357    /// offending `:contratos <slot>` (`:de` / `:para`) at which the
10358    /// caixa-reference value is the empty string. Folds the uniform
10359    /// `Self::ContratoCaixaEmpty { slot }` one-slot struct-literal onto
10360    /// one substrate primitive so the sole in-crate closure passed to
10361    /// [`crate::render::require_valid_dns_1123_label`] at
10362    /// [`validate_contrato_caixa`] on this variant reads through one
10363    /// dispatch rather than the pre-lift open-coded block. The `slot`
10364    /// label threads verbatim from the caller-side
10365    /// [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
10366    /// [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] `const` strings the
10367    /// wire-up feeds through [`validate_contrato_caixa`]'s
10368    /// `slot: &'static str` parameter.
10369    ///
10370    /// Sibling of the paired three-slot [`Self::contrato_caixa_invalid`]
10371    /// substrate primitive on the same
10372    /// [`crate::render::require_valid_dns_1123_label`] two-closure
10373    /// cascade — the empty-arm and invalid-arm now both reach the
10374    /// `AplicacaoError` envelope through one substrate primitive per
10375    /// typed variant, closing the pair. Same shape discipline as the
10376    /// peer [`crate::behavior::BehaviorError::empty_path`] one-slot
10377    /// `{ slot: &'static str }` sibling on the `BehaviorError`
10378    /// envelope's four-arm sandboxed-lisp-path cascade
10379    /// ([`crate::render::require_sandboxed_lisp_path`]) — extended here
10380    /// onto the sibling `AplicacaoError` envelope's two-arm
10381    /// DNS-1123-label cascade at the `:contratos <slot>` per-edge axis.
10382    ///
10383    /// `slot` stays `&'static str` (not `&str`) — every `:contratos
10384    /// <slot>` tag comes from the [`crate::render::CONTRATO_AUTHOR_KEY_*`]
10385    /// `const` roster carrying program-lifetime storage, matching the
10386    /// enum-field type and the [`validate_contrato_caixa`] wire-up's
10387    /// per-axis dispatch. A runtime-borrowed `&str` would silently
10388    /// downgrade the label lifetime and let a caller stash a
10389    /// non-`'static` borrow into the returned error. `#[must_use]` fires
10390    /// a compile warning at any wire-up that mistakenly discards the
10391    /// constructed error rather than routing it through `return Err(…)`
10392    /// / `.map_err(…)` / a closure return. `pub const fn` matches the
10393    /// peer per-envelope one-slot `Copy`-scalar ctor family discipline
10394    /// (`aplicacao_placement_scalar_ctors!`, `layout_nome_only_ctors!`,
10395    /// `dep_nome_only_ctors!`) so the ctor is usable in `const` position
10396    /// at every wire-up site.
10397    ///
10398    /// Every future consumer that wants to construct this variant
10399    /// outside the current in-crate wire-up (the deferred
10400    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
10401    /// per-`:contratos`-edge admission validator projecting the same
10402    /// diagnostic through the caller-facing `slot: &'static str` tag,
10403    /// a future `feira validate --contratos` per-caixa admission verb,
10404    /// an M4 per-`:contratos`-edge pre-emitter running the same
10405    /// DNS-1123-label floor's empty-arm against a caller-supplied
10406    /// `:de` / `:para` pair before hitting the apiserver-side selector,
10407    /// a per-`Caixa` overlay resolver rejecting an author-supplied
10408    /// `:contratos` overlay's empty `:de` / `:para` against a
10409    /// cluster-local snapshot) — now reaches this variant through one
10410    /// call rather than re-inlining the open-coded closure block in
10411    /// lockstep with the one in-crate wire-up site.
10412    #[must_use]
10413    pub const fn contrato_caixa_empty(slot: &'static str) -> Self {
10414        Self::ContratoCaixaEmpty { slot }
10415    }
10416}
10417
10418// Fold the seven `AplicacaoError::{MembroCaixa, EntradaPara, EntradaHost,
10419// EntradaPath, PlacementCluster, PlacementAffinity, ShardKey}Invalid
10420// { <field>: <val>.to_string(), reason: <expr> }` wire-up sites onto one
10421// substrate-primitive family per typed variant — the paired
10422// `{ <field>: String, reason: String }` two-slot sibling on
10423// [`AplicacaoError`] of the peer four-slot [`contrato_target_ctors!`]
10424// (14b81d5, `{ de, para, wit, expected }` on `ContratoWrongTarget` /
10425// `ContratoMissingTarget`) and the peer two-slot
10426// [`contrato_empty_pair_ctors!`] (8580068, `{ de, para }` on `EmptyWit` /
10427// `ContratoEndpointEmpty` / `ContratoSubjectEmpty` / `ContratoSlotEmpty`)
10428// on the sibling per-`:contratos` envelopes, plus the peer four-family
10429// `LayoutError` ctor set ([`layout_violation_ctors!`] 131ca0d — 16
10430// variants on `{ caixa, issue }`, [`layout_slot_kind_ctors!`] 0419438 —
10431// 4 variants on `{ caixa, kind, slots }`, [`LayoutError::missing_entry`]
10432// 1b09f9d — 1 variant on `{ kind, path }`, [`layout_nome_only_ctors!`]
10433// 3fe3dd7 — 6 variants on `<Variant>(String)`) each carry on the
10434// sibling layout-side envelope.
10435//
10436// Every one of the seven wire-up sites — six under the per-axis
10437// `validate_*` wrappers around [`crate::render::require_valid_dns_1123_label`]
10438// (`validate_membro_caixa` on `MembroCaixaInvalid`, `validate_entrada_para`
10439// on `EntradaParaInvalid`, `validate_placement_cluster` on
10440// `PlacementClusterInvalid`, `validate_placement_affinity` on
10441// `PlacementAffinityInvalid`) plus [`crate::render::is_gateway_api_http_path`]
10442// (`validate_entrada_path` on `EntradaPathInvalid`), and two under
10443// [`validate_placement_shard_key`] (the length-cap arm and the per-byte
10444// printable-ASCII arm on `ShardKeyInvalid`) — plus the fourteen wire-up
10445// sites at [`validate_entrada_host`] (17dd504 already folded onto the
10446// pre-macro standalone `entrada_host_invalid` ctor, now converged onto
10447// the macro-generated ctor of the same name), opened the identical
10448// four-line `AplicacaoError::<Variant>Invalid
10449// { <field>: <val>.to_string(), reason: <expr> }` struct-literal against
10450// the local `<field>: &str` argument — the exact "same block re-inlined
10451// at every consumer" shape the PRIME DIRECTIVE names as a bug, on the
10452// same altitude the peer three `AplicacaoError` constructor families
10453// and the four peer `LayoutError` constructor families each closed on
10454// their sibling envelopes.
10455//
10456// The macro below generates one `#[must_use]` inherent constructor per
10457// variant of shape `fn <ctor>(<field>: &str, reason: impl Into<String>)
10458// -> AplicacaoError`, collapsing every site onto one dispatch per arm:
10459// `return Err(AplicacaoError::<ctor>(<val>, <reason>));` /
10460// `|reason| AplicacaoError::<ctor>(<val>, reason)`, byte-equal to the
10461// pre-lift struct-literal on the same `(<field>, reason)` pair. The
10462// uniform two-field construction (`<field>: <val>.to_string()`,
10463// `reason: reason.into()`) is spelled once — inside the macro — rather
10464// than at every wire-up site. The `reason: impl Into<String>` bound
10465// accepts both `&str` literals (with or without a trailing
10466// `.to_string()` at the caller) and `format!(…)` outputs verbatim so no
10467// wire-up site changes its per-arm diagnostic shape at the lift.
10468// `#[must_use]` fires a compile warning at any wire-up that mistakenly
10469// discards the constructed error rather than routing it through
10470// `return Err(…)` / `.map_err(…)` / a closure return.
10471//
10472// Every future consumer that wants to construct one of these seven
10473// variants outside the current in-crate wire-up sites (the deferred
10474// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-slot
10475// admission validators, a future `feira validate --<axis>` per-caixa
10476// admission verb, a per-`Certificate` SAN pre-emitter for cert-manager
10477// on `:entrada :host`, an M4 typed placement-engine per-cluster /
10478// per-affinity / per-shard-key pre-emitter, an M4 typed Gateway API
10479// per-path pre-emitter) reaches the variant through one call rather
10480// than re-inlining the four-line struct-literal block in lockstep with
10481// the current in-crate wire-up sites.
10482macro_rules! aplicacao_field_reason_ctors {
10483    ($($ctor:ident => $variant:ident { $field:ident }),* $(,)?) => {
10484        impl AplicacaoError {
10485            $(
10486                #[doc = concat!(
10487                    "Construct an [`AplicacaoError::",
10488                    stringify!($variant),
10489                    "`] naming the offending `",
10490                    stringify!($field),
10491                    "` under the given `reason`. Folds the uniform ",
10492                    "`{ ",
10493                    stringify!($field),
10494                    ": ",
10495                    stringify!($field),
10496                    ".to_string(), reason: reason.into() }` two-slot ",
10497                    "construction onto one substrate primitive so every ",
10498                    "wire-up on this variant reads through one dispatch ",
10499                    "rather than the pre-lift four-line struct-literal ",
10500                    "block. `reason` accepts both `&str` literals and ",
10501                    "`format!(…)` outputs through the `impl Into<String>` ",
10502                    "bound."
10503                )]
10504                #[must_use]
10505                pub fn $ctor($field: &str, reason: impl Into<String>) -> Self {
10506                    Self::$variant {
10507                        $field: $field.to_string(),
10508                        reason: reason.into(),
10509                    }
10510                }
10511            )*
10512        }
10513    };
10514}
10515
10516aplicacao_field_reason_ctors! {
10517    membro_caixa_invalid => MembroCaixaInvalid { caixa },
10518    entrada_para_invalid => EntradaParaInvalid { para },
10519    entrada_host_invalid => EntradaHostInvalid { host },
10520    entrada_path_invalid => EntradaPathInvalid { path },
10521    placement_cluster_invalid => PlacementClusterInvalid { cluster },
10522    placement_affinity_invalid => PlacementAffinityInvalid { affinity },
10523    shard_key_invalid => ShardKeyInvalid { shard_key },
10524}
10525
10526// Fold the four `AplicacaoError::Contrato{Endpoint,Subject,Slot,Wit}Invalid
10527// { de, para, <field>: <val>.to_string(), reason }` wire-up sites at
10528// [`WitContract::target`] onto one substrate-primitive family per typed
10529// variant — the paired `{ de: String, para: String, <field>: String,
10530// reason: String }` four-slot sibling on [`AplicacaoError`] of the peer
10531// four-slot [`contrato_target_ctors!`] (14b81d5, `{ de, para, wit,
10532// expected }` on `ContratoWrongTarget` / `ContratoMissingTarget`), the
10533// peer two-slot [`contrato_empty_pair_ctors!`] (8580068, `{ de, para }`
10534// on `EmptyWit` / `ContratoEndpointEmpty` / `ContratoSubjectEmpty` /
10535// `ContratoSlotEmpty`), and the peer two-slot
10536// [`aplicacao_field_reason_ctors!`] (981060b, `{ <field>: String,
10537// reason: String }` on `MembroCaixaInvalid` / `EntradaParaInvalid` /
10538// `EntradaHostInvalid` / `EntradaPathInvalid` / `PlacementClusterInvalid`
10539// / `PlacementAffinityInvalid` / `ShardKeyInvalid`) each carry on the
10540// sibling `AplicacaoError` envelopes, plus the peer four-family
10541// `LayoutError` ctor set on the sibling layout-side envelope.
10542//
10543// Every one of the four wire-up sites — four per-`:contratos` value-
10544// shape gates inside [`WitContract::target`] (the world-ref prefix
10545// [`crate::render::is_wit_world_ref`] failure on `:wit`, the HTTP arm's
10546// [`crate::render::is_gateway_api_http_path`] failure on `:endpoint`,
10547// the pub-sub arm's [`crate::render::is_nats_subject`] failure on
10548// `:subject`, the store arm's [`crate::render::is_wasi_keyvalue_slot`]
10549// failure on `:slot`) — opened the identical five-line
10550// `let (de, para) = self.edge_pair();
10551// return Err(AplicacaoError::Contrato<Field>Invalid { de, para,
10552// <field>: <val>.to_string(), reason });` block against the local
10553// [`WitContract::edge_pair`] composite-projection accessor and the
10554// per-arm `<val>: &str` argument — the exact "same block re-inlined at
10555// every consumer" shape the PRIME DIRECTIVE names as a bug, on the same
10556// altitude the peer three `AplicacaoError` constructor families and the
10557// four peer `LayoutError` constructor families each closed on their
10558// sibling envelopes. Absorbing `ContratoWitInvalid` onto the same
10559// macro closes the last unlifted `{ de, para, <field>: String, reason:
10560// String }` four-slot envelope inside `impl WitContract`, so every
10561// per-`:contratos` value-shape diagnostic on [`AplicacaoError`] now
10562// reads through this one substrate primitive.
10563//
10564// The macro below generates one `#[must_use]` inherent constructor per
10565// variant of shape `fn <ctor>(edge: (String, String), <field>: &str,
10566// reason: impl Into<String>) -> AplicacaoError`, collapsing the four
10567// sites onto one dispatch per arm:
10568// `return Err(AplicacaoError::<ctor>(self.edge_pair(), <val>, reason));`,
10569// byte-equal to the pre-lift struct-literal on the same
10570// `(edge_pair, <val>, reason)` triple. The uniform four-field
10571// construction (`de, para` pair-destructure onto same-named fields +
10572// `<field>: <val>.to_string()` + `reason: reason.into()`) is spelled
10573// once — inside the macro — rather than at every wire-up site. The
10574// `reason: impl Into<String>` bound accepts both `&str` literals and
10575// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
10576// diagnostic shape at the lift, matching the peer
10577// [`aplicacao_field_reason_ctors!`] bound on the sibling two-slot
10578// envelope. `#[must_use]` fires a compile warning at any wire-up that
10579// mistakenly discards the constructed error.
10580//
10581// Every future consumer that wants to construct one of these four
10582// variants outside [`WitContract::target`] (a deferred
10583// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
10584// admission validator raising per-payload value-shape diagnostics on
10585// unrecognized `:wit` / `:endpoint` / `:subject` / `:slot` shapes, a
10586// future `feira validate --contratos` per-caixa admission verb, an M4
10587// typed WIT-registry-driven per-arm pre-emitter probing each declared
10588// `:endpoint` / `:subject` / `:slot` payload against a canonical
10589// per-arm shape gate, a per-`Certificate` SAN pre-emitter for
10590// cert-manager on the `:endpoint` axis, an M4 typed Cilium L7 rule
10591// pre-emitter probing each `:endpoint` against the same shared
10592// HTTPPathMatch grammar) reaches the variant through one call rather
10593// than re-inlining the five-line pair-destructure + struct-literal
10594// block in lockstep with the four in-crate wire-up sites.
10595macro_rules! contrato_pair_value_reason_ctors {
10596    ($($ctor:ident => $variant:ident { $field:ident }),* $(,)?) => {
10597        impl AplicacaoError {
10598            $(
10599                #[doc = concat!(
10600                    "Construct an [`AplicacaoError::",
10601                    stringify!($variant),
10602                    "`] naming the offending edge `(de, para)` pair, the ",
10603                    "per-payload `",
10604                    stringify!($field),
10605                    "` value, and the parser-shaped `reason`. Folds the ",
10606                    "uniform `{ de, para, ",
10607                    stringify!($field),
10608                    ": ",
10609                    stringify!($field),
10610                    ".to_string(), reason: reason.into() }` four-slot ",
10611                    "construction onto one substrate primitive so every ",
10612                    "wire-up on this variant reads through one dispatch ",
10613                    "rather than the pre-lift five-line pair-destructure ",
10614                    "+ struct-literal block. The `edge` pair threads ",
10615                    "verbatim from [`WitContract::edge_pair`] at the ",
10616                    "call site; `reason` accepts both `&str` literals ",
10617                    "and `format!(…)` outputs through the `impl ",
10618                    "Into<String>` bound."
10619                )]
10620                #[must_use]
10621                pub fn $ctor(edge: (String, String), $field: &str, reason: impl Into<String>) -> Self {
10622                    let (de, para) = edge;
10623                    Self::$variant {
10624                        de,
10625                        para,
10626                        $field: $field.to_string(),
10627                        reason: reason.into(),
10628                    }
10629                }
10630            )*
10631        }
10632    };
10633}
10634
10635contrato_pair_value_reason_ctors! {
10636    contrato_endpoint_invalid => ContratoEndpointInvalid { endpoint },
10637    contrato_subject_invalid => ContratoSubjectInvalid { subject },
10638    contrato_slot_invalid => ContratoSlotInvalid { slot },
10639    contrato_wit_invalid => ContratoWitInvalid { wit },
10640}
10641
10642// Fold the five `AplicacaoError::{ContratoMemberMissing, MembroVersaoEmpty,
10643// MembroDuplicate, MembroIsSelfAplicacao} { caixa: <&str>.to_string() }`
10644// caixa-only struct-variant wire-up sites at
10645// [`WitContract::require_endpoints_in`] (two sites, the `:contratos :de` and
10646// `:contratos :para` arms of `ContratoMemberMissing`),
10647// [`AplicacaoSpec::validate_membros`] (two sites, the empty-`:versao` arm of
10648// `MembroVersaoEmpty` and the per-`:membros` dedup arm of `MembroDuplicate`),
10649// and [`validate_no_self_membership`] (one site, the parent-`:nome`
10650// self-membership arm of `MembroIsSelfAplicacao`) onto one substrate primitive
10651// per typed variant — the sibling on the M3 mesh `AplicacaoError` envelope of
10652// the peer [`crate::supervisor::supervisor_caixa_only_ctors!`] macro (db09650,
10653// three variants on `{ caixa: String }` at
10654// [`crate::SupervisorSpec::validate_children`] and
10655// [`crate::supervisor::validate_no_self_supervision`]) on the sibling M2
10656// `SupervisorError` envelope, extending the same "one substrate primitive per
10657// typed variant on the single-slot `{ <ident>: String }` envelope shape" fold
10658// discipline onto the M3 mesh side. Peers on peer envelopes: the M2 sibling
10659// [`crate::behavior::behavior_slot_path_ctors!`] (67c31ec, 3 variants on
10660// `{ slot: &'static str, path: PathBuf }`) two-slot fold on the `:behavior`
10661// envelope; the M2 sibling [`crate::upgrade::upgrade_from_script_ctors!`]
10662// (8e67041, 3 variants on `{ from: String, script: PathBuf }`) and
10663// [`crate::upgrade::upgrade_script_only_ctors!`] (7468ca9, 3 variants on
10664// `{ script: PathBuf }`) two folds on the sibling `:upgrade-from` envelope;
10665// the sibling [`crate::dep::dep_nome_only_ctors!`] (792aa92, 5 variants on
10666// `{ nome: String }`), [`crate::dep::fonte_caminho_ctors!`] (f85f145, 11
10667// variants on `{ nome, caminho }`), and
10668// [`crate::dep::fonte_caminho_byte_ctors!`] (0e35793, 12 variants on
10669// `{ nome, caminho, byte }`) folds on the sibling `DepError` envelope; the
10670// peer three `AplicacaoError` sub-family folds already lifted here
10671// ([`contrato_target_ctors!`] 14b81d5, [`contrato_empty_pair_ctors!`] 8580068,
10672// [`aplicacao_field_reason_ctors!`] 981060b,
10673// [`contrato_pair_value_reason_ctors!`] 14e13f1); the peer four `LayoutError`
10674// families ([`crate::layout::layout_violation_ctors!`] 131ca0d,
10675// [`crate::layout::layout_slot_kind_ctors!`] 0419438,
10676// [`crate::LayoutError::missing_entry`] 1b09f9d,
10677// [`crate::layout::layout_nome_only_ctors!`] 3fe3dd7); and the three
10678// [`crate::limits::limits_codec_value_*_ctors!`] codec families (81c856c).
10679//
10680// Each of the five wire-up sites on this shape (two on `ContratoMemberMissing`
10681// at the per-`:contratos :de`/`:para` unknown-member arms, one on
10682// `MembroVersaoEmpty` at the per-`:membros` empty-semver-requirement arm, one
10683// on `MembroDuplicate` at the per-`:membros` dedup arm, one on
10684// `MembroIsSelfAplicacao` at the parent-`:nome` self-membership arm) opened
10685// the identical `AplicacaoError::<Variant> { caixa: <&str>.to_string() }`
10686// three-line struct-literal against a caller-side `&str` — the exact "same
10687// block re-inlined at every consumer" shape the PRIME DIRECTIVE names as a
10688// bug, on the same altitude the peer `SupervisorError` /
10689// `AplicacaoError` (three prior sub-families) / `DepError` / `LayoutError` /
10690// `UpgradeError` / `BehaviorError` / `LimitsError` families each closed on
10691// their sibling envelopes. The four variants share one `{ caixa: String }`
10692// shape, so the fold routes each wire-up site through one dispatch per typed
10693// variant.
10694//
10695// The macro below generates one `#[must_use]` inherent constructor per
10696// variant of shape `fn <ctor>(caixa: &str) -> AplicacaoError`, so every
10697// wire-up site collapses onto one dispatch:
10698// `AplicacaoError::<ctor>(<&str>)`, byte-equal to the pre-lift struct-literal
10699// on the same `&str` fixture. The uniform one-field construction
10700// (`caixa: caixa.to_string()`) is spelled once — inside the macro — rather
10701// than at every wire-up site. Every constructor is `#[must_use]` so a caller
10702// who mistakenly discards the constructed error trips a compile warning at
10703// the wire-up site.
10704//
10705// Every future consumer that wants to construct one of these four variants
10706// outside the current in-crate wire-up sites — a deferred
10707// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook
10708// re-checking one added/renamed `:membros` entry against the sibling
10709// `:contratos` graph, a future `feira validate --membros` per-caixa admission
10710// verb re-checking each declared `:membros` entry's `:caixa` name against the
10711// same axes, a per-tenant per-`Aplicacao` overlay resolver rejecting a
10712// duplicate / self-referencing / unknown-membered `:contratos` entry against
10713// a cluster-local snapshot the M4 CR materializer projects — now reaches each
10714// variant through one call rather than re-inlining the three-line
10715// struct-literal in lockstep with the five in-crate wire-up sites.
10716macro_rules! aplicacao_caixa_only_ctors {
10717    ($($ctor:ident => $variant:ident),* $(,)?) => {
10718        impl AplicacaoError {
10719            $(
10720                #[doc = concat!(
10721                    "Construct an [`AplicacaoError::",
10722                    stringify!($variant),
10723                    "`] naming the offending `:membros :caixa` (or ",
10724                    "parent `:nome`, on the self-membership arm; or ",
10725                    "`:contratos :de`/`:para`, on the unknown-member ",
10726                    "arm). Folds the uniform `Self::",
10727                    stringify!($variant),
10728                    " { caixa: caixa.to_string() }` one-field ",
10729                    "struct-literal onto one substrate primitive so ",
10730                    "every wire-up on this variant reads through one ",
10731                    "dispatch rather than the pre-lift three-line ",
10732                    "open-coded struct-literal block."
10733                )]
10734                #[must_use]
10735                pub fn $ctor(caixa: &str) -> Self {
10736                    Self::$variant { caixa: caixa.to_string() }
10737                }
10738            )*
10739        }
10740    };
10741}
10742
10743aplicacao_caixa_only_ctors! {
10744    contrato_member_missing => ContratoMemberMissing,
10745    membro_versao_empty => MembroVersaoEmpty,
10746    membro_duplicate => MembroDuplicate,
10747    membro_is_self_aplicacao => MembroIsSelfAplicacao,
10748}
10749
10750// Fold the three `AplicacaoError::{EntradaPathNotAbsolute,
10751// EntradaPathDuplicate} { path: <val>.to_string() | <val>.clone() }` wire-up
10752// sites onto one substrate-primitive family per typed variant — the direct
10753// per-`:entrada :paths` value-shape sibling of the peer
10754// `aplicacao_caixa_only_ctors!` (d9f6867, `{ caixa: String }` on
10755// `ContratoMemberMissing` / `MembroVersaoEmpty` / `MembroDuplicate` /
10756// `MembroIsSelfAplicacao`) on the sibling per-`:membros :caixa` envelope, and
10757// per-`:entrada :para` sibling of the peer `contrato_empty_pair_ctors!`
10758// (8580068, `{ de, para }` on `EmptyWit` / `ContratoEndpointEmpty` /
10759// `ContratoSubjectEmpty` / `ContratoSlotEmpty`) on the per-`:contratos` edge
10760// envelope. Same shape family as the [`crate::dep::dep_nome_only_ctors!`]
10761// (792aa92, `{ nome: String }` on five `DepError` variants) fold on the peer
10762// `:deps` envelope — every single-`String`-slot error family in caixa-core
10763// now reaches through one substrate primitive per typed variant.
10764//
10765// The three wire-up sites — one under [`validate_entrada_path`]'s
10766// leading-slash grammar arm (`EntradaPathNotAbsolute` against
10767// `path: &str`), one under the per-`:entrada :paths` loop's identical
10768// arm (`EntradaPathNotAbsolute` against a `&String` head via `.clone()`),
10769// and one under the per-`:entrada :paths` loop's dedup arm
10770// (`EntradaPathDuplicate` against the same `&String` via
10771// [`crate::render::insert_first_seen`]'s ctor closure) — opened the identical
10772// `AplicacaoError::EntradaPath<Variant> { path: <val>.to_string() | .clone() }`
10773// three-line struct-literal against a caller-side `&str` / `&String`, the
10774// exact "same block re-inlined at every consumer" shape the PRIME DIRECTIVE
10775// names as a bug. Every one of the compile-time guarantees in
10776// MESH-COMPOSITION.md §III.3 (a `:entrada :paths` entry whose value doesn't
10777// start with `/` becomes a caixa-build error, not a Gateway API webhook
10778// rejection at `kubectl apply` time; a duplicated `:entrada :paths` entry
10779// becomes a caixa-build error, not a silent last-writer-wins render) now
10780// routes through one dispatch per typed variant at every emit site.
10781//
10782// The macro below generates one `#[must_use]` inherent constructor per
10783// variant of shape `fn <ctor>(path: &str) -> AplicacaoError`, collapsing
10784// every wire-up site onto one dispatch:
10785// `AplicacaoError::<ctor>(<path>)` (byte-equal to the pre-lift struct-literal
10786// on the same `&str` fixture) or the `&String` sites through
10787// `p.as_str()` (byte-equal on the same slice-view). The uniform one-field
10788// construction (`path: path.to_string()`) is spelled once — inside the
10789// macro — rather than at every wire-up site. Every ctor is `#[must_use]` so
10790// a caller who mistakenly discards the constructed error trips a compile
10791// warning at the wire-up site.
10792//
10793// Every future consumer that wants to construct one of these two variants
10794// outside the current in-crate wire-up sites — a deferred
10795// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook
10796// per-`:entrada :paths` re-check against a cluster-local Gateway API
10797// snapshot, a future `feira validate --entrada` per-caixa admission verb
10798// re-checking each declared `:paths` entry against the same axes, a
10799// per-tenant per-`Aplicacao` overlay resolver rejecting a
10800// duplicate / non-absolute `:paths` entry against a cluster-local Gateway
10801// snapshot the M4 CR materializer projects — now reaches each variant
10802// through one call rather than re-inlining the three-line struct-literal in
10803// lockstep with the three in-crate wire-up sites.
10804macro_rules! aplicacao_path_only_ctors {
10805    ($($ctor:ident => $variant:ident),* $(,)?) => {
10806        impl AplicacaoError {
10807            $(
10808                #[doc = concat!(
10809                    "Construct an [`AplicacaoError::",
10810                    stringify!($variant),
10811                    "`] naming the offending `:entrada :paths` entry. ",
10812                    "Folds the uniform `Self::",
10813                    stringify!($variant),
10814                    " { path: path.to_string() }` one-field ",
10815                    "struct-literal onto one substrate primitive so ",
10816                    "every wire-up on this variant reads through one ",
10817                    "dispatch rather than the pre-lift three-line ",
10818                    "open-coded struct-literal block."
10819                )]
10820                #[must_use]
10821                pub fn $ctor(path: &str) -> Self {
10822                    Self::$variant { path: path.to_string() }
10823                }
10824            )*
10825        }
10826    };
10827}
10828
10829aplicacao_path_only_ctors! {
10830    entrada_path_not_absolute => EntradaPathNotAbsolute,
10831    entrada_path_duplicate => EntradaPathDuplicate,
10832}
10833
10834// Fold the eight `AplicacaoError::Policy<Slot><Axis> { <field>: <val> }`
10835// one-slot `Copy`-scalar wire-up sites at [`MeshPolicy::validate`] onto one
10836// substrate-primitive family per typed variant — the per-`:politicas` copy-
10837// scalar `{ timeout | retries | max_failures | window | rate: Duration | u32 }`
10838// sibling of the peer per-`:membros :caixa` [`aplicacao_caixa_only_ctors!`]
10839// (d9f6867, `{ caixa: String }` on `ContratoMemberMissing` /
10840// `MembroVersaoEmpty` / `MembroDuplicate` / `MembroIsSelfAplicacao`) and the
10841// peer per-`:entrada :paths` [`aplicacao_path_only_ctors!`] (3ba8de6,
10842// `{ path: String }` on `EntradaPathNotAbsolute` / `EntradaPathDuplicate`) on
10843// the `String`-slot axis, and the peer per-`:politicas` cross-axis
10844// [`AplicacaoError::Policy*`] cascade [`MeshPolicy::first_cross_axis_violation`]
10845// carries at line 3064 on the same M3 mesh envelope.
10846//
10847// The eight wire-up sites inside [`MeshPolicy::validate`] at lines 3170-3218
10848// each opened the identical `|<slot>| AplicacaoError::Policy<Slot><Axis>
10849// { <slot> }` one-line struct-literal closure against the caller-side
10850// `<slot>: <ty>` argument that the shared
10851// [`crate::render::require_positive_bounded_u32`] /
10852// [`crate::render::require_positive_canonical_bounded_duration`] gate rebinds
10853// verbatim under the `impl FnOnce(u32) -> AplicacaoError` /
10854// `impl FnOnce(Duration) -> AplicacaoError` bracket-closure slots (plus one
10855// direct `return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical
10856// { window: rl.window() })` at the `:rate-limit :window` canonical-form arm
10857// on line 3211) — the exact "same one-line struct-literal re-inlined at every
10858// consumer" shape the PRIME DIRECTIVE names as a bug, on the last remaining
10859// per-`:politicas` per-axis `AplicacaoError` variant family that had not yet
10860// been folded onto a substrate primitive.
10861//
10862// The macro below generates one `#[must_use] pub const fn <ctor>(<field>: <ty>)
10863// -> AplicacaoError` per variant of shape `Self::<variant> { <field> }`,
10864// collapsing every wire-up onto either one direct dispatch
10865// (`return Err(AplicacaoError::<ctor>(<val>))`, byte-equal to the pre-lift
10866// struct-literal on the same `Copy`-`<ty>` fixture) or one bare function
10867// pointer at the `impl FnOnce(<ty>) -> AplicacaoError` bracket-closure slot
10868// (`AplicacaoError::<ctor>` in the position where every pre-lift site spelled
10869// `|<slot>| AplicacaoError::<Variant> { <slot> }`) — Rust's function-pointer-
10870// to-`FnOnce` coercion on any `fn(<ty>) -> AplicacaoError` inherent
10871// constructor with matching arity and signature. The `const fn` qualifier
10872// preserves the pre-lift `Copy`-pass-through's zero-runtime-work property
10873// verbatim (no `.to_string()` / `.into()` allocation, no branching); the
10874// per-variant `$field:ident` axis re-uses the enum's canonical field name so
10875// the generated ctor's parameter name matches every wire-up's local binding
10876// (`|timeout|` calls `policy_timeout_not_canonical(timeout)`, etc.), matching
10877// the peer [`aplicacao_field_reason_ctors!`] / [`aplicacao_caixa_only_ctors!`]
10878// / [`aplicacao_path_only_ctors!`] convention. `#[must_use]` fires a compile
10879// warning at any wire-up that mistakenly discards the constructed error, on
10880// the same footing as every sibling `AplicacaoError` / `DepError` /
10881// `SupervisorError` / `LayoutError` / `LimitsError` / `BehaviorError` /
10882// `UpgradeError` ctor macro (14b81d5 / 8580068 / 981060b / 14e13f1 / 81c856c
10883// / 8e67041 / 7468ca9 / 67c31ec / d2ef2ec / f85f145 / 0e35793 / 792aa92 /
10884// 6f5e0cd / 3fe3dd7 / 1b09f9d / 131ca0d / 0419438).
10885//
10886// Every future consumer that wants to construct one of these eight variants
10887// outside [`MeshPolicy::validate`] — a deferred
10888// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook re-
10889// checking each `:politicas` axis against a cluster-local `:politicas` cap
10890// overlay, a future per-`:contratos`-edge `:politicas` override the
10891// MESH-COMPOSITION §III.2 #3 roadmap acknowledges resolving an *effective*
10892// per-edge [`MeshPolicy`] and emitting the same per-axis diagnostic on the
10893// same input as `feira build`, an M4 per-cluster `:politicas`-cap resolver
10894// projecting a per-tenant per-axis ceiling into the same diagnostic shape,
10895// a future `feira validate --politicas` per-caixa admission verb re-checking
10896// each declared per-axis value against the same bounds — now reaches each
10897// variant through one call rather than re-inlining the one-line struct-
10898// literal in lockstep with the seven `MeshPolicy::validate` wire-up sites,
10899// which is exactly the invariant every prior ctor-macro lift already closed
10900// on its sibling envelope. Closes the last remaining per-`:politicas`
10901// per-axis `AplicacaoError` variant family that had not yet been folded onto
10902// a substrate primitive; the compound cross-axis variants
10903// ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`] / `*RateLimit` /
10904// `*RetriesBurst`) each carry a distinct multi-slot field shape and are folded
10905// on a separate axis by [`MeshPolicy::first_cross_axis_violation`].
10906macro_rules! aplicacao_policy_scalar_ctors {
10907    ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
10908        impl AplicacaoError {
10909            $(
10910                #[doc = concat!(
10911                    "Construct an [`AplicacaoError::",
10912                    stringify!($variant),
10913                    "`] naming the offending per-`:politicas` `",
10914                    stringify!($field),
10915                    "` scalar. Folds the uniform `Self::",
10916                    stringify!($variant),
10917                    " { ",
10918                    stringify!($field),
10919                    " }` one-field `Copy`-pass-through struct-literal onto ",
10920                    "one substrate primitive so every per-axis wire-up on ",
10921                    "this variant reads through one dispatch — as a direct ",
10922                    "call (`AplicacaoError::",
10923                    stringify!($ctor),
10924                    "(<val>)`, byte-equal to the pre-lift struct-literal on ",
10925                    "the same `Copy`-`",
10926                    stringify!($ty),
10927                    "` fixture) or as a bare function pointer in the ",
10928                    "`impl FnOnce(",
10929                    stringify!($ty),
10930                    ") -> AplicacaoError` bracket-closure slot every ",
10931                    "`crate::render::require_positive_bounded_*` / ",
10932                    "`crate::render::require_positive_canonical_bounded_*` ",
10933                    "gate carries — rather than the pre-lift open-coded ",
10934                    "one-line closure over the same one-field struct-",
10935                    "literal. `const fn` preserves the `Copy`-pass-through's ",
10936                    "zero-runtime-work property verbatim."
10937                )]
10938                #[must_use]
10939                pub const fn $ctor($field: $ty) -> Self {
10940                    Self::$variant { $field }
10941                }
10942            )*
10943        }
10944    };
10945}
10946
10947aplicacao_policy_scalar_ctors! {
10948    policy_timeout_not_canonical => PolicyTimeoutNotCanonical { timeout: Duration },
10949    policy_timeout_exceeds_cap => PolicyTimeoutExceedsCap { timeout: Duration },
10950    policy_retries_exceeds_cap => PolicyRetriesExceedsCap { retries: u32 },
10951    policy_breaker_max_failures_exceeds_cap =>
10952        PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
10953    policy_breaker_window_not_canonical =>
10954        PolicyBreakerWindowNotCanonical { window: Duration },
10955    policy_breaker_window_exceeds_cap =>
10956        PolicyBreakerWindowExceedsCap { window: Duration },
10957    policy_rate_limit_exceeds_cap => PolicyRateLimitExceedsCap { rate: u32 },
10958    policy_rate_limit_window_not_canonical =>
10959        PolicyRateLimitWindowNotCanonical { window: Duration },
10960}
10961
10962#[cfg(test)]
10963mod tests {
10964    use super::*;
10965
10966    fn membro(name: &str, ver: &str) -> Membro {
10967        Membro {
10968            caixa: name.into(),
10969            versao: ver.into(),
10970        }
10971    }
10972
10973    fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
10974        WitContract {
10975            de: de.into(),
10976            para: para.into(),
10977            wit: "wasi:http/proxy".into(),
10978            endpoint: Some(ep.into()),
10979            subject: None,
10980            slot: None,
10981        }
10982    }
10983
10984    fn three_member_spec() -> AplicacaoSpec {
10985        AplicacaoSpec {
10986            membros: vec![
10987                membro("catalog", "^0.1"),
10988                membro("cart", "^0.1"),
10989                membro("payment", "^0.2"),
10990            ],
10991            contratos: vec![
10992                contract_http("cart", "catalog", "/products/:id"),
10993                contract_http("cart", "payment", "/charge"),
10994            ],
10995            politicas: MeshPolicy {
10996                timeout: Some(Duration::from_secs(30)),
10997                retries: Some(3),
10998                mtls_required: Some(true),
10999                ..Default::default()
11000            },
11001            placement: Placement {
11002                estrategia: PlacementStrategy::Replicated,
11003                clusters: vec!["rio".into(), "mar".into()],
11004                affinity: Some("data-locality".into()),
11005                shard_key: None,
11006            },
11007            entrada: Some(Entrada {
11008                host: "checkout.quero.cloud".into(),
11009                para: "cart".into(),
11010                paths: vec!["/api/cart".into(), "/api/products".into()],
11011                port: 8080,
11012            }),
11013        }
11014    }
11015
11016    #[test]
11017    fn happy_path_validates() {
11018        three_member_spec().validate().unwrap();
11019    }
11020
11021    #[test]
11022    fn rejects_empty_membros() {
11023        let mut s = three_member_spec();
11024        s.membros = vec![];
11025        assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
11026    }
11027
11028    #[test]
11029    fn rejects_empty_membro_caixa() {
11030        // A `:caixa ""` entry has no name to render into programs.yaml
11031        // and no caixa.lisp to resolve at lacre time.
11032        let mut s = three_member_spec();
11033        s.membros[1].caixa = String::new();
11034        assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
11035    }
11036
11037    #[test]
11038    fn rejects_empty_membro_versao() {
11039        // A `:versao ""` entry can't pin a semver constraint, so the
11040        // lacre pipeline fails far from the source.
11041        let mut s = three_member_spec();
11042        s.membros[2].versao = String::new();
11043        let err = s.validate().unwrap_err();
11044        assert!(
11045            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
11046            "got {err:?}"
11047        );
11048    }
11049
11050    #[test]
11051    fn rejects_duplicate_membro_caixa() {
11052        // Two `:membros` entries with the same `:caixa` collapse to one
11053        // node in the membership HashSet, which masks `:contratos`
11054        // membership errors and produces duplicate programs.yaml entries.
11055        let mut s = three_member_spec();
11056        s.membros.push(membro("cart", "^0.2"));
11057        let err = s.validate().unwrap_err();
11058        assert!(
11059            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
11060            "got {err:?}"
11061        );
11062    }
11063
11064    #[test]
11065    fn rejects_invalid_membro_versao_requirement() {
11066        // The fail-before-pass-after pin: a non-empty but malformed
11067        // semver requirement (`"^bad-version"`) silently passed
11068        // `validate()` on every pre-gate codebase because the prior
11069        // shape only refused the empty string. The parse failure
11070        // surfaced far downstream at lacre-resolve time with a
11071        // `semver::Error` that didn't name which `:membros` entry
11072        // carried the typo. The new gate moves the check to caixa-build
11073        // time at the source caixa.lisp.
11074        let mut s = three_member_spec();
11075        s.membros[2].versao = "^bad-version".into();
11076        let err = s.validate().unwrap_err();
11077        assert!(
11078            matches!(
11079                err,
11080                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
11081                    if caixa == "payment" && versao == "^bad-version"
11082            ),
11083            "got {err:?}"
11084        );
11085    }
11086
11087    #[test]
11088    fn rejects_membro_versao_with_double_caret_typo() {
11089        // `"^^0.1"` is the canonical doubled-caret typo — looks like a
11090        // Cargo-shaped requirement on first glance but fails the parser
11091        // because semver doesn't accept stacked operators. Pin this
11092        // adjacent-shape footgun explicitly so a future relaxation that
11093        // accepts "looks-canonical-but-isn't" forms surfaces here.
11094        let mut s = three_member_spec();
11095        s.membros[0].versao = "^^0.1".into();
11096        let err = s.validate().unwrap_err();
11097        assert!(
11098            matches!(
11099                err,
11100                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
11101                    if caixa == "catalog" && versao == "^^0.1"
11102            ),
11103            "got {err:?}"
11104        );
11105    }
11106
11107    #[test]
11108    fn rejects_membro_versao_with_v_prefixed_tag() {
11109        // `"v0.1"` is the canonical "git-tag-shape leaking into the
11110        // semver requirement slot" typo — an author copies the
11111        // publish-side git-tag string verbatim into `:versao`, but
11112        // Cargo's semver parser rejects the leading `v` (only digits +
11113        // canonical operators are valid in the major-version
11114        // position). The gate's diagnostic names which member entry
11115        // carried the v-prefix so the fix is one edit, not a grep
11116        // through every member's `:versao`. (Note: bare `x`-glob
11117        // shorthands like `^0.1.x` are *accepted* by the semver crate
11118        // as an `*` wildcard on the patch axis — they're a Cargo-side
11119        // valid shape, not a typo, so the gate intentionally lets them
11120        // through.)
11121        let mut s = three_member_spec();
11122        s.membros[1].versao = "v0.1".into();
11123        let err = s.validate().unwrap_err();
11124        assert!(
11125            matches!(
11126                err,
11127                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
11128                    if caixa == "cart" && versao == "v0.1"
11129            ),
11130            "got {err:?}"
11131        );
11132    }
11133
11134    #[test]
11135    fn accepts_canonical_membro_versao_forms() {
11136        // The four Cargo-shaped requirement forms `:deps :versao`
11137        // already accepts via `crate::parse_requirement` must pass the
11138        // membros gate without re-validating at the resolver layer.
11139        // Pin every leg so a future tightening of the canonical set
11140        // surfaces here as a test failure.
11141        for form in [
11142            "^0.1",      // caret — minor-range pin (the most common shape)
11143            "~0.1.2",    // tilde — patch-range pin
11144            "0.1.0",     // exact — single-version pin
11145            "*",         // wildcard — explicitly any-version (semver::VersionReq::STAR)
11146            ">=0.1, <2", // multi-range — comma-separated comparators
11147        ] {
11148            let mut s = three_member_spec();
11149            for m in &mut s.membros {
11150                m.versao = form.into();
11151            }
11152            s.validate()
11153                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
11154        }
11155    }
11156
11157    #[test]
11158    fn membro_versao_empty_takes_precedence_over_invalid() {
11159        // Order pin: the existing `MembroVersaoEmpty` diagnostic
11160        // (which doesn't try to parse) fires before the new
11161        // `MembroVersaoInvalid` parse-side diagnostic, so an empty
11162        // `:versao` keeps its narrower error message — `parse_requirement`
11163        // would also reject `""`, but the empty-string arm is the more
11164        // self-locating diagnostic for the author.
11165        let mut s = three_member_spec();
11166        s.membros[1].versao = String::new();
11167        let err = s.validate().unwrap_err();
11168        assert!(
11169            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
11170            "got {err:?}"
11171        );
11172    }
11173
11174    #[test]
11175    fn membro_versao_invalid_fires_before_duplicate_check() {
11176        // Order pin: a malformed requirement on a non-duplicate entry
11177        // surfaces *its own* diagnostic (which names the offending
11178        // `:versao` string), even when a later entry would otherwise
11179        // collapse onto an earlier name. The per-entry shape gate runs
11180        // inline before the duplicate-key insert, parallel to
11181        // `membros_validation_runs_before_contratos_membership_check`
11182        // and `duplicate_contrato_gate_runs_after_target_shape_check`.
11183        let mut s = three_member_spec();
11184        s.membros[0].versao = "^bad".into();
11185        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
11186        let err = s.validate().unwrap_err();
11187        assert!(
11188            matches!(
11189                err,
11190                AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
11191            ),
11192            "got {err:?}"
11193        );
11194    }
11195
11196    #[test]
11197    fn membro_versao_invalid_diagnostic_carries_offending_versao() {
11198        // The diagnostic-shape pin: the error names the offending
11199        // `:versao` value verbatim so the author can grep their
11200        // caixa.lisp without re-running the build, and carries a
11201        // non-empty `reason` from `semver::VersionReq::parse` so the
11202        // parser's own wording flows through to the diagnostic.
11203        let mut s = three_member_spec();
11204        s.membros[2].versao = "not-a-req".into();
11205        let err = s.validate().unwrap_err();
11206        let AplicacaoError::MembroVersaoInvalid {
11207            caixa,
11208            versao,
11209            reason,
11210        } = err
11211        else {
11212            panic!("expected MembroVersaoInvalid, got other variant");
11213        };
11214        assert_eq!(caixa, "payment");
11215        assert_eq!(versao, "not-a-req");
11216        assert!(
11217            !reason.is_empty(),
11218            "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
11219        );
11220    }
11221
11222    #[test]
11223    fn membro_versao_invalid_runs_before_contratos_check() {
11224        // A malformed `:versao` on any member must surface its own
11225        // diagnostic (which names *which* member to fix) before any
11226        // `:contratos` membership lookup raises `ContratoMemberMissing`.
11227        // The `:contratos` gate runs after `validate_membros`, so this
11228        // is structurally guaranteed — pin it explicitly so a future
11229        // refactor that reorders the gates surfaces here.
11230        let mut s = three_member_spec();
11231        s.membros[1].versao = "^^0.1".into();
11232        // Add a contrato whose `:para` doesn't exist — would normally
11233        // raise ContratoMemberMissing at the membership lookup, but
11234        // the membros gate must fire first.
11235        s.contratos
11236            .push(contract_http("cart", "phantom", "/never-reached"));
11237        let err = s.validate().unwrap_err();
11238        assert!(
11239            matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
11240            "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
11241        );
11242    }
11243
11244    #[test]
11245    fn membros_validation_runs_before_contratos_membership_check() {
11246        // If `:membros` carries a duplicate, the membership-collapse
11247        // would silently accept a `:contratos :para "phantom"` so long
11248        // as some entry hashes to "phantom". Pinning order: the
11249        // duplicate-membros error fires first, regardless of whether
11250        // contratos reference real members.
11251        let mut s = three_member_spec();
11252        s.membros = vec![
11253            membro("cart", "^0.1"),
11254            membro("cart", "^0.2"),
11255            membro("catalog", "^0.1"),
11256            membro("payment", "^0.1"),
11257        ];
11258        let err = s.validate().unwrap_err();
11259        assert!(
11260            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
11261            "got {err:?}"
11262        );
11263    }
11264
11265    #[test]
11266    fn distinct_membros_validate() {
11267        // Pin the happy-path: every `:membros` entry has a non-empty
11268        // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
11269        // The fixture already satisfies this; this test makes the
11270        // invariant explicit so a future refactor of the fixture can't
11271        // silently break the guarantee.
11272        three_member_spec().validate().unwrap();
11273    }
11274
11275    // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
11276
11277    #[test]
11278    fn rejects_membro_caixa_with_uppercase() {
11279        // The canonical "I copied the Servico's display name verbatim"
11280        // typo — caixa names are lowercase per K8s DNS-1123 label rule,
11281        // but author tools often round-trip a TitleCase or CamelCase
11282        // identifier from an ADR or a sketch. Pin the diagnostic names
11283        // the offending name and suggests the lower-cased fix in one
11284        // edit, mirroring the `rejects_entrada_host_with_uppercase`
11285        // gate's shape (c7d05ec).
11286        let mut s = three_member_spec();
11287        s.membros[1].caixa = "Cart".into();
11288        let err = s.validate().unwrap_err();
11289        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
11290            panic!("expected MembroCaixaInvalid, got other variant");
11291        };
11292        assert_eq!(caixa, "Cart");
11293        assert!(
11294            reason.contains("uppercase"),
11295            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
11296        );
11297        assert!(
11298            reason.contains("\"cart\""),
11299            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
11300        );
11301    }
11302
11303    #[test]
11304    fn rejects_membro_caixa_with_underscore() {
11305        // The canonical "I'm thinking of a Python module / Postgres
11306        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
11307        // label schema. K8s rejects `metadata.name: my_cart` at admission
11308        // time with an opaque `field is invalid` (no source-citing
11309        // diagnostic). The gate moves it to caixa-build time.
11310        let mut s = three_member_spec();
11311        s.membros[0].caixa = "my_cart".into();
11312        let err = s.validate().unwrap_err();
11313        assert!(
11314            matches!(
11315                err,
11316                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
11317                    if caixa == "my_cart" && reason.contains('_')
11318            ),
11319            "got {err:?}"
11320        );
11321    }
11322
11323    #[test]
11324    fn rejects_membro_caixa_with_dot() {
11325        // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
11326        // subdomain — even though K8s `metadata.name` itself accepts
11327        // dots (DNS-1123 subdomain rule), this string also lands as a
11328        // K8s Service name (DNS-1035 label — no dots) and as a label
11329        // value on identity-based Cilium selectors. The strictest floor
11330        // among the use sites wins. The "I want to namespace my member
11331        // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
11332        let mut s = three_member_spec();
11333        s.membros[2].caixa = "team.cart".into();
11334        let err = s.validate().unwrap_err();
11335        assert!(
11336            matches!(
11337                err,
11338                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
11339                    if caixa == "team.cart" && reason.contains('.')
11340            ),
11341            "got {err:?}"
11342        );
11343    }
11344
11345    #[test]
11346    fn rejects_membro_caixa_with_leading_hyphen() {
11347        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
11348        // with an alphanumeric. The K8s apiserver rejects `-cart`
11349        // outright; the renderer would emit a `metadata.name: "-cart"`
11350        // that fails admission far from the source caixa.lisp.
11351        let mut s = three_member_spec();
11352        s.membros[0].caixa = "-cart".into();
11353        let err = s.validate().unwrap_err();
11354        assert!(
11355            matches!(
11356                err,
11357                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
11358                    if caixa == "-cart" && reason.contains("start and end")
11359            ),
11360            "got {err:?}"
11361        );
11362    }
11363
11364    #[test]
11365    fn rejects_membro_caixa_with_trailing_hyphen() {
11366        // The symmetric arm of the boundary rule. Pin separately so
11367        // both ends of the label are covered against a future relaxation
11368        // that only checks one boundary.
11369        let mut s = three_member_spec();
11370        s.membros[1].caixa = "cart-".into();
11371        let err = s.validate().unwrap_err();
11372        assert!(
11373            matches!(
11374                err,
11375                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
11376                    if caixa == "cart-"
11377            ),
11378            "got {err:?}"
11379        );
11380    }
11381
11382    #[test]
11383    fn rejects_membro_caixa_with_unicode() {
11384        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
11385        // (`xn--…`) by the author before it reaches K8s. The byte-by-
11386        // byte ASCII validity check rejects multi-byte UTF-8 sequences
11387        // by the first byte that fails the `[a-z0-9-]` predicate.
11388        let mut s = three_member_spec();
11389        s.membros[2].caixa = "café".into();
11390        let err = s.validate().unwrap_err();
11391        assert!(
11392            matches!(
11393                err,
11394                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
11395                    if caixa == "café"
11396            ),
11397            "got {err:?}"
11398        );
11399    }
11400
11401    #[test]
11402    fn rejects_membro_caixa_with_whitespace() {
11403        // Whitespace is the canonical "I pasted from a sketch / doc"
11404        // footgun. The apiserver rejects every `metadata.name` value
11405        // carrying whitespace; pin the gate fires at the right boundary.
11406        let mut s = three_member_spec();
11407        s.membros[0].caixa = "my cart".into();
11408        let err = s.validate().unwrap_err();
11409        assert!(
11410            matches!(
11411                err,
11412                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
11413                    if caixa == "my cart"
11414            ),
11415            "got {err:?}"
11416        );
11417    }
11418
11419    #[test]
11420    fn rejects_membro_caixa_too_long() {
11421        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
11422        // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
11423        // exactly. The gate's reason names both the cap and the actual
11424        // length so the author can shorten in one edit.
11425        let mut s = three_member_spec();
11426        let too_long = "a".repeat(64);
11427        s.membros[1].caixa = too_long.clone();
11428        let err = s.validate().unwrap_err();
11429        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
11430            panic!("expected MembroCaixaInvalid");
11431        };
11432        assert_eq!(caixa, too_long);
11433        assert!(
11434            reason.contains("63") && reason.contains("64"),
11435            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
11436        );
11437    }
11438
11439    #[test]
11440    fn membro_caixa_max_length_validates() {
11441        // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
11442        // so a future tightening (e.g. dropping to 62) surfaces here as
11443        // a regression, mirroring `entrada_host_max_length_validates`
11444        // (c7d05ec).
11445        let mut s = three_member_spec();
11446        s.membros[2].caixa = "a".repeat(63);
11447        s.entrada.as_mut().unwrap().para = "a".repeat(63);
11448        // remove contratos referencing the renamed member; they'd
11449        // raise ContratoMemberMissing otherwise
11450        s.contratos
11451            .retain(|c| c.de != "payment" && c.para != "payment");
11452        s.validate().unwrap();
11453    }
11454
11455    #[test]
11456    fn accepts_canonical_membro_caixa_forms() {
11457        // The DNS-1123 label shapes a caixa author is realistically
11458        // going to write: single-word lowercase, hyphen-joined, ending
11459        // in a digit-suffixed version (`cart-v2`), starting with a
11460        // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
11461        // DNS-1035 which requires a letter at position 0), single-
11462        // character (`a` — boundary). Pin every leg so a future
11463        // tightening that bans (e.g.) digit-start identifiers surfaces
11464        // here.
11465        for form in [
11466            "checkout",
11467            "cart",
11468            "cart-v2",
11469            "a",
11470            "c0",
11471            "3rd-party-shim",
11472            "x-1-2-3-4",
11473        ] {
11474            let mut s = three_member_spec();
11475            // Renaming a member also requires updating downstream refs;
11476            // drop everything else and rebuild a minimal spec around
11477            // just the one renamed member.
11478            s.membros = vec![membro(form, "^0.1")];
11479            s.contratos = vec![];
11480            s.entrada = None;
11481            s.validate()
11482                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
11483        }
11484    }
11485
11486    #[test]
11487    fn membro_caixa_empty_takes_precedence_over_invalid() {
11488        // Order pin: the existing `MembroCaixaEmpty` diagnostic
11489        // (which doesn't try to parse) fires before the new
11490        // `MembroCaixaInvalid` parse-side diagnostic, so an empty
11491        // `:caixa` keeps its narrower error message — the new gate
11492        // would also reject `""`, but the empty-string arm is the more
11493        // self-locating diagnostic for the author. Mirrors the
11494        // `entrada_host_empty_takes_precedence_over_invalid` pin
11495        // (c7d05ec).
11496        let mut s = three_member_spec();
11497        s.membros[1].caixa = String::new();
11498        let err = s.validate().unwrap_err();
11499        assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
11500    }
11501
11502    #[test]
11503    fn membro_caixa_invalid_fires_before_versao_check() {
11504        // Order pin: an invalid-shape `:caixa` surfaces *its own*
11505        // diagnostic (which names the offending caixa name), even when
11506        // the same entry's `:versao` is also empty/invalid. The shape
11507        // gate runs first because the diagnostic is more self-locating —
11508        // an empty/invalid `:versao` on an invalid-shape caixa name is
11509        // a downstream-fix-after-the-caixa-rename concern.
11510        let mut s = three_member_spec();
11511        s.membros[1].caixa = "Cart".into();
11512        s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
11513        let err = s.validate().unwrap_err();
11514        assert!(
11515            matches!(
11516                err,
11517                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
11518            ),
11519            "got {err:?}"
11520        );
11521    }
11522
11523    #[test]
11524    fn membro_caixa_invalid_fires_before_duplicate_check() {
11525        // Order pin: a malformed-shape `:caixa` on an earlier entry
11526        // surfaces *its own* diagnostic, even when a later entry would
11527        // otherwise collapse onto a duplicate name. The per-entry shape
11528        // gate runs inline before the duplicate-key insert, parallel
11529        // to `membro_versao_invalid_fires_before_duplicate_check`.
11530        let mut s = three_member_spec();
11531        s.membros[0].caixa = "Catalog".into();
11532        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
11533        let err = s.validate().unwrap_err();
11534        assert!(
11535            matches!(
11536                err,
11537                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
11538            ),
11539            "got {err:?}"
11540        );
11541    }
11542
11543    #[test]
11544    fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
11545        // The diagnostic-shape pin: the error names the offending
11546        // `:caixa` value verbatim so the author can grep their
11547        // caixa.lisp without re-running the build, and carries a
11548        // non-empty `reason` naming the specific violation. Same
11549        // shape every typed-shape gate enshrines (c7d05ec's
11550        // `entrada_host_diagnostic_carries_offending_host`,
11551        // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
11552        let mut s = three_member_spec();
11553        s.membros[2].caixa = "BAD_NAME".into();
11554        let err = s.validate().unwrap_err();
11555        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
11556            panic!("expected MembroCaixaInvalid");
11557        };
11558        assert_eq!(caixa, "BAD_NAME");
11559        assert!(
11560            !reason.is_empty(),
11561            "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
11562        );
11563    }
11564
11565    #[test]
11566    fn rejects_contrato_with_unknown_de() {
11567        let mut s = three_member_spec();
11568        s.contratos.push(contract_http("phantom", "catalog", "/x"));
11569        let err = s.validate().unwrap_err();
11570        assert!(
11571            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
11572        );
11573    }
11574
11575    #[test]
11576    fn rejects_contrato_with_unknown_para() {
11577        let mut s = three_member_spec();
11578        s.contratos.push(contract_http("cart", "phantom", "/x"));
11579        let err = s.validate().unwrap_err();
11580        assert!(
11581            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
11582        );
11583    }
11584
11585    #[test]
11586    fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
11587        // The read-path pin: the phantom-`:de` refusal arm's
11588        // `ContratoMemberMissing.caixa` carrier must be observed through
11589        // the lifted [`WitContract::source`] accessor, not the raw
11590        // `.de.clone()` field-access `String`-carry. Peer of the sibling
11591        // per-`:contratos` self-loop arm's `.source().to_string()` /
11592        // `.world_ref().to_string()` `String`-carry sites the earlier
11593        // convergence lifted onto the same accessor pair. A future
11594        // silent detour that reintroduced the raw `.de.clone()` at the
11595        // wrap envelope while the shape-gate and membership lookup
11596        // routed through the accessor would surface here as a byte-equal
11597        // miss between the fired diagnostic's `caixa:` field and the
11598        // offending edge's `.source()` — pinning the accessor as the
11599        // sole read path across the phantom-name refusal arm's arg +
11600        // wrap-envelope emit surface.
11601        let mut s = three_member_spec();
11602        let phantom = contract_http("phantom", "catalog", "/x");
11603        s.contratos.push(phantom.clone());
11604        let err = s.validate().unwrap_err();
11605        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
11606            panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
11607        };
11608        assert_eq!(
11609            caixa,
11610            phantom.source(),
11611            "ContratoMemberMissing.caixa on the phantom-:de arm must \
11612             byte-equal WitContract::source — the wrap envelope must \
11613             route through the lifted accessor rather than the raw \
11614             .de.clone() field-access String-carry"
11615        );
11616    }
11617
11618    #[test]
11619    fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
11620        // The symmetric read-path pin on the `:para` phantom-name
11621        // refusal arm — same shape as the sibling `:de` pin above but
11622        // on the callee-Servico axis. Pins the wrap envelope's
11623        // `caixa:` field is observed through the lifted
11624        // [`WitContract::destination`] accessor, not the raw
11625        // `.para.clone()` field-access `String`-carry.
11626        let mut s = three_member_spec();
11627        let phantom = contract_http("cart", "phantom", "/x");
11628        s.contratos.push(phantom.clone());
11629        let err = s.validate().unwrap_err();
11630        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
11631            panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
11632        };
11633        assert_eq!(
11634            caixa,
11635            phantom.destination(),
11636            "ContratoMemberMissing.caixa on the phantom-:para arm must \
11637             byte-equal WitContract::destination — the wrap envelope \
11638             must route through the lifted accessor rather than the raw \
11639             .para.clone() field-access String-carry"
11640        );
11641    }
11642
11643    #[test]
11644    fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
11645        // The read-path pin on the `:de` DNS-1123-malformed shape-gate
11646        // refusal arm — the `validate_contrato_caixa` arg must be
11647        // observed through the lifted [`WitContract::source`] accessor,
11648        // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
11649        // value routes through the shared
11650        // [`crate::render::require_valid_dns_1123_label`] floor with the
11651        // accessor-projected value; the fired
11652        // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
11653        // the offending edge's `.source()`, pinning that the arg + the
11654        // downstream `caixa: caixa.to_string()` wrap route through the
11655        // same accessor's read path.
11656        let mut s = three_member_spec();
11657        let malformed = contract_http("BAD_NAME", "catalog", "/x");
11658        s.contratos.push(malformed.clone());
11659        let err = s.validate().unwrap_err();
11660        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
11661            panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
11662        };
11663        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
11664        assert_eq!(
11665            caixa,
11666            malformed.source(),
11667            "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
11668             byte-equal WitContract::source — the shape-gate arg + wrap \
11669             envelope must route through the lifted accessor rather \
11670             than the raw &c.de &String-borrow"
11671        );
11672    }
11673
11674    #[test]
11675    fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
11676        // Symmetric arm to the sibling `:de` malformed-shape pin above,
11677        // on the `:para` axis. Pins the shape-gate arg + wrap envelope
11678        // route through the lifted [`WitContract::destination`]
11679        // accessor. `:para` runs after the `:de` shape gate in the
11680        // canonical edge-direction order, so the `:de` value must be
11681        // well-shaped for the `:para` gate to fire — the `cart` :de is
11682        // canonical.
11683        let mut s = three_member_spec();
11684        let malformed = contract_http("cart", "BAD_NAME", "/x");
11685        s.contratos.push(malformed.clone());
11686        let err = s.validate().unwrap_err();
11687        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
11688            panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
11689        };
11690        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
11691        assert_eq!(
11692            caixa,
11693            malformed.destination(),
11694            "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
11695             byte-equal WitContract::destination — the shape-gate arg + \
11696             wrap envelope must route through the lifted accessor \
11697             rather than the raw &c.para &String-borrow"
11698        );
11699    }
11700
11701    // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
11702
11703    #[test]
11704    fn rejects_contrato_de_empty() {
11705        // `:de ""` previously fell through to `ContratoMemberMissing`
11706        // (with `caixa: ""`) because the validated `:membros :caixa`
11707        // set never contains the empty string. The narrower
11708        // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
11709        // the offending slot.
11710        let mut s = three_member_spec();
11711        s.contratos.push(contract_http("", "catalog", "/x"));
11712        let err = s.validate().unwrap_err();
11713        assert_eq!(
11714            err,
11715            AplicacaoError::ContratoCaixaEmpty {
11716                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
11717            },
11718            "got {err:?}"
11719        );
11720    }
11721
11722    #[test]
11723    fn rejects_contrato_para_empty() {
11724        // Symmetric arm to `:de ""` — `:para ""` previously fell
11725        // through to `ContratoMemberMissing { caixa: "" }`.
11726        let mut s = three_member_spec();
11727        s.contratos.push(contract_http("cart", "", "/x"));
11728        let err = s.validate().unwrap_err();
11729        assert_eq!(
11730            err,
11731            AplicacaoError::ContratoCaixaEmpty {
11732                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
11733            },
11734            "got {err:?}"
11735        );
11736    }
11737
11738    #[test]
11739    fn rejects_contrato_de_with_uppercase() {
11740        // The canonical "I copied the Servico's TitleCase display
11741        // name from an ADR" typo. Until this gate landed `:de "Cart"`
11742        // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
11743        // as "this caixa isn't in `:membros`" when the root cause is
11744        // "this `:de` value's shape can never legitimately match a
11745        // validated member (DNS-1123 labels are lowercase)". The
11746        // narrower diagnostic names the offending slot, the value
11747        // verbatim, and the parser-shaped reason.
11748        let mut s = three_member_spec();
11749        s.contratos.push(contract_http("Cart", "catalog", "/x"));
11750        let err = s.validate().unwrap_err();
11751        let AplicacaoError::ContratoCaixaInvalid {
11752            slot,
11753            caixa,
11754            reason,
11755        } = err
11756        else {
11757            panic!("expected ContratoCaixaInvalid, got other variant");
11758        };
11759        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
11760        assert_eq!(caixa, "Cart");
11761        assert!(
11762            reason.contains("uppercase"),
11763            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
11764        );
11765    }
11766
11767    #[test]
11768    fn rejects_contrato_para_with_underscore() {
11769        // The canonical "I'm thinking of a Python module" leak —
11770        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
11771        // Pin the `:para` axis surfaces the same diagnostic shape as
11772        // the `:de` axis on the underscore violation.
11773        let mut s = three_member_spec();
11774        s.contratos.push(contract_http("cart", "my_catalog", "/x"));
11775        let err = s.validate().unwrap_err();
11776        assert!(
11777            matches!(
11778                err,
11779                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
11780                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
11781            ),
11782            "got {err:?}"
11783        );
11784    }
11785
11786    #[test]
11787    fn rejects_contrato_de_with_dot() {
11788        // A `:contratos :de` value is a single DNS-1123 *label*, not
11789        // a subdomain — mirroring the `:membros :caixa` floor. The
11790        // strictest floor among the use sites wins.
11791        let mut s = three_member_spec();
11792        s.contratos
11793            .push(contract_http("team.cart", "catalog", "/x"));
11794        let err = s.validate().unwrap_err();
11795        assert!(
11796            matches!(
11797                err,
11798                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
11799                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
11800            ),
11801            "got {err:?}"
11802        );
11803    }
11804
11805    #[test]
11806    fn rejects_contrato_para_with_unicode() {
11807        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
11808        // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
11809        // validity check rejects multi-byte UTF-8 by the first
11810        // non-`[a-z0-9-]` byte.
11811        let mut s = three_member_spec();
11812        s.contratos.push(contract_http("cart", "café", "/x"));
11813        let err = s.validate().unwrap_err();
11814        assert!(
11815            matches!(
11816                err,
11817                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
11818                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
11819            ),
11820            "got {err:?}"
11821        );
11822    }
11823
11824    #[test]
11825    fn rejects_contrato_de_with_leading_hyphen() {
11826        // DNS-1123 boundary rule: labels must start and end with an
11827        // alphanumeric. K8s rejects `-cart` outright; the narrower
11828        // shape diagnostic now names the violation at caixa-build
11829        // time rather than the misframed membership-lookup arm.
11830        let mut s = three_member_spec();
11831        s.contratos.push(contract_http("-cart", "catalog", "/x"));
11832        let err = s.validate().unwrap_err();
11833        assert!(
11834            matches!(
11835                err,
11836                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
11837                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
11838            ),
11839            "got {err:?}"
11840        );
11841    }
11842
11843    #[test]
11844    fn contrato_de_empty_takes_precedence_over_invalid() {
11845        // Order pin: the `ContratoCaixaEmpty` arm fires before the
11846        // `ContratoCaixaInvalid` parse-side arm — same empty-first
11847        // cascade `validate_membro_caixa` / `validate_placement_cluster`
11848        // / `validate_entrada_host` already establish on their peer
11849        // name axes. The empty string is a structurally distinct
11850        // authoring footgun (the author left the field blank, vs.
11851        // typed a malformed value), so it gets its own diagnostic.
11852        let mut s = three_member_spec();
11853        s.contratos.push(contract_http("", "catalog", "/x"));
11854        let err = s.validate().unwrap_err();
11855        assert_eq!(
11856            err,
11857            AplicacaoError::ContratoCaixaEmpty {
11858                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
11859            }
11860        );
11861    }
11862
11863    #[test]
11864    fn contrato_de_shape_fires_before_para_shape() {
11865        // Per-axis order pin: within one `:contratos` entry, the `:de`
11866        // shape gate fires before the `:para` shape gate — same
11867        // edge-direction order the existing `ContratoMemberMissing` /
11868        // `ContratoSelfLoop` / target-dispatch checks use, so the
11869        // diagnostic for a contract with both `:de` and `:para`
11870        // malformed is stable. Authors fixing the surfaced `:de`
11871        // first will see `:para`'s diagnostic on re-run.
11872        let mut s = three_member_spec();
11873        s.contratos.push(contract_http("Cart", "Catalog", "/x"));
11874        let err = s.validate().unwrap_err();
11875        assert!(
11876            matches!(
11877                err,
11878                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
11879                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
11880            ),
11881            "got {err:?}"
11882        );
11883    }
11884
11885    #[test]
11886    fn contrato_shape_fires_before_membership_lookup() {
11887        // The load-bearing pin: an invalid-shape `:de` surfaces its
11888        // *own* diagnostic, not the misframed `ContratoMemberMissing`.
11889        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
11890        // an invalid-shape `:de` could never legitimately match any
11891        // member — the prior `ContratoMemberMissing` diagnostic was
11892        // a structural impossibility framed as a graph-membership
11893        // failure. The shape gate now routes every such input through
11894        // the narrower self-locating diagnostic.
11895        let mut s = three_member_spec();
11896        s.contratos.push(contract_http("Cart", "catalog", "/x"));
11897        let err = s.validate().unwrap_err();
11898        assert!(
11899            matches!(
11900                err,
11901                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
11902            ),
11903            "got {err:?}"
11904        );
11905        // And the symmetric case: an invalid-shape `:para` surfaces
11906        // its own diagnostic too, even when `:de` is well-shaped.
11907        let mut s = three_member_spec();
11908        s.contratos.push(contract_http("cart", "Catalog", "/x"));
11909        let err = s.validate().unwrap_err();
11910        assert!(
11911            matches!(
11912                err,
11913                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
11914            ),
11915            "got {err:?}"
11916        );
11917    }
11918
11919    #[test]
11920    fn contrato_shape_fires_before_self_edge_check() {
11921        // A `:de "Cart" :para "Cart"` entry is two distinct authoring
11922        // bugs: the shape violation (uppercase) and the self-edge
11923        // violation. The narrower per-axis shape diagnostic surfaces
11924        // first because fixing the shape may reveal that the author
11925        // also meant to point `:para` at a different member — the
11926        // self-edge framing is only useful once both endpoints have
11927        // valid shape.
11928        let mut s = three_member_spec();
11929        s.contratos.push(contract_http("Cart", "Cart", "/x"));
11930        let err = s.validate().unwrap_err();
11931        assert!(
11932            matches!(
11933                err,
11934                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
11935                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
11936            ),
11937            "got {err:?}"
11938        );
11939    }
11940
11941    #[test]
11942    fn contrato_well_shaped_phantom_still_raises_member_missing() {
11943        // Strict-improvement pin: a well-shaped `:de` that simply
11944        // isn't in `:membros` (a phantom reference — author meant
11945        // to add the member but didn't, or renamed and missed an
11946        // update) still surfaces `ContratoMemberMissing`, unchanged.
11947        // The shape gate only intercepts inputs that could never
11948        // legitimately match a validated member; legitimately-shaped
11949        // phantom references remain on the graph-membership axis.
11950        let mut s = three_member_spec();
11951        s.contratos
11952            .push(contract_http("phantom-shim", "catalog", "/x"));
11953        let err = s.validate().unwrap_err();
11954        assert!(
11955            matches!(
11956                err,
11957                AplicacaoError::ContratoMemberMissing { ref caixa }
11958                    if caixa == "phantom-shim"
11959            ),
11960            "got {err:?}"
11961        );
11962    }
11963
11964    #[test]
11965    fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
11966        // The diagnostic-shape pin: the error names the offending
11967        // slot (`:de` or `:para`) verbatim and the offending value
11968        // verbatim plus a non-empty parser-shaped reason, so the
11969        // author can grep their caixa.lisp for `:de "<name>"` /
11970        // `:para "<name>"` and fix it in one edit. Same diagnostic
11971        // shape as `MembroCaixaInvalid` (3f9d7a0) and
11972        // `PlacementClusterInvalid` (6c8c00b).
11973        let mut s = three_member_spec();
11974        s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
11975        let err = s.validate().unwrap_err();
11976        let AplicacaoError::ContratoCaixaInvalid {
11977            slot,
11978            caixa,
11979            reason,
11980        } = err
11981        else {
11982            panic!("expected ContratoCaixaInvalid, got {err:?}");
11983        };
11984        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
11985        assert_eq!(caixa, "BAD_NAME");
11986        assert!(
11987            !reason.is_empty(),
11988            "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
11989        );
11990    }
11991
11992    #[test]
11993    fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
11994        // Scalar-value pin: the two author-facing kebab-case labels the
11995        // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
11996        // admits on the `:contratos` per-entry endpoint-shape axis,
11997        // one arm per typed sub-slot. Mirrors the peer scalar-value
11998        // pin the sibling top-level M2 / M3 / Supervisor
11999        // author-facing-label consts carry
12000        // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
12001        // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
12002        // slot itself), so every altitude of the typed-slot algebra
12003        // shares the same "one canonical byte-string per arm"
12004        // discipline. A future rebrand (`:de` → `:from` matching the
12005        // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
12006        // sibling, `:para` → `:to` matching the same, or
12007        // `:de`/`:para` → `:source`/`:target` matching the WIT
12008        // world's `import`/`export` half-vocabulary) lands as an
12009        // edit to exactly one const, and every consumer that reaches
12010        // for the label picks it up at build time rather than at
12011        // runtime as a downstream `ContratoCaixaEmpty` /
12012        // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
12013        // diagnostic mismatch far from the rename's commit.
12014        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
12015        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
12016    }
12017
12018    #[test]
12019    fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
12020        // Production-through-const pin: the two per-axis labels the
12021        // per-`:contratos` entry endpoint-shape gate at
12022        // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
12023        // argument to [`validate_contrato_caixa`] route through the
12024        // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
12025        // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
12026        // future rebrand that reaches the const but not the gate (or
12027        // vice versa) surfaces here at build time rather than at
12028        // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
12029        // `slot: <stale-kebab-case>` diagnostic far from the rename's
12030        // commit. Mirror of the peer
12031        // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
12032        // pin (882f498) on the sibling M3 top-level slot axis.
12033        let mut s = three_member_spec();
12034        s.contratos.push(contract_http("", "catalog", "/x"));
12035        assert_eq!(
12036            s.validate().unwrap_err(),
12037            AplicacaoError::ContratoCaixaEmpty {
12038                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
12039            }
12040        );
12041        let mut s = three_member_spec();
12042        s.contratos.push(contract_http("cart", "", "/x"));
12043        assert_eq!(
12044            s.validate().unwrap_err(),
12045            AplicacaoError::ContratoCaixaEmpty {
12046                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
12047            }
12048        );
12049    }
12050
12051    #[test]
12052    fn accepts_canonical_contrato_caixa_forms() {
12053        // The DNS-1123 label shapes a caixa author is realistically
12054        // going to write on a `:contratos :de` / `:para`. Pin every
12055        // leg so a future tightening that bans (e.g.) digit-start
12056        // identifiers surfaces here, mirroring
12057        // `accepts_canonical_membro_caixa_forms` on the peer name
12058        // axis.
12059        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
12060            let mut s = three_member_spec();
12061            s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
12062            s.contratos = vec![contract_http("checkout", form, "/x")];
12063            s.entrada = None;
12064            s.validate().unwrap_or_else(|e| {
12065                panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
12066            });
12067
12068            let mut s = three_member_spec();
12069            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
12070            s.contratos = vec![contract_http(form, "catalog", "/x")];
12071            s.entrada = None;
12072            s.validate().unwrap_or_else(|e| {
12073                panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
12074            });
12075        }
12076    }
12077
12078    #[test]
12079    fn rejects_empty_wit() {
12080        let mut s = three_member_spec();
12081        s.contratos.push(WitContract {
12082            de: "cart".into(),
12083            para: "catalog".into(),
12084            wit: String::new(),
12085            endpoint: None,
12086            subject: None,
12087            slot: None,
12088        });
12089        let err = s.validate().unwrap_err();
12090        assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
12091    }
12092
12093    #[test]
12094    fn rejects_entrada_to_unknown_member() {
12095        let mut s = three_member_spec();
12096        s.entrada.as_mut().unwrap().para = "phantom".into();
12097        assert!(matches!(
12098            s.validate().unwrap_err(),
12099            AplicacaoError::EntradaMemberMissing { .. }
12100        ));
12101    }
12102
12103    // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
12104
12105    #[test]
12106    fn rejects_entrada_para_empty() {
12107        // `:para ""` previously fell through to
12108        // `EntradaMemberMissing { para: "" }` because the validated
12109        // `:membros :caixa` set never contains the empty string. The
12110        // narrower `EntradaParaEmpty` diagnostic now names the
12111        // offending slot directly — same empty-first cascade
12112        // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
12113        // `ContratoCaixaEmpty` establish on the peer name axes.
12114        let mut s = three_member_spec();
12115        s.entrada.as_mut().unwrap().para = String::new();
12116        let err = s.validate().unwrap_err();
12117        assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
12118    }
12119
12120    #[test]
12121    fn rejects_entrada_para_with_uppercase() {
12122        // The canonical "I copied the Servico's TitleCase display
12123        // name from an ADR" typo. Until this gate landed `:para "Cart"`
12124        // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
12125        // as "this caixa isn't in `:membros`" when the root cause is
12126        // "this `:para` value's shape can never legitimately match a
12127        // validated member (DNS-1123 labels are lowercase)". The
12128        // narrower diagnostic names the value verbatim plus the
12129        // parser-shaped reason.
12130        let mut s = three_member_spec();
12131        s.entrada.as_mut().unwrap().para = "Cart".into();
12132        let err = s.validate().unwrap_err();
12133        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
12134            panic!("expected EntradaParaInvalid, got other variant");
12135        };
12136        assert_eq!(para, "Cart");
12137        assert!(
12138            reason.contains("uppercase"),
12139            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
12140        );
12141    }
12142
12143    #[test]
12144    fn rejects_entrada_para_with_underscore() {
12145        // The canonical "I'm thinking of a Python module" leak —
12146        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
12147        let mut s = three_member_spec();
12148        s.entrada.as_mut().unwrap().para = "my_cart".into();
12149        let err = s.validate().unwrap_err();
12150        assert!(
12151            matches!(
12152                err,
12153                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
12154                    if para == "my_cart" && reason.contains('_')
12155            ),
12156            "got {err:?}"
12157        );
12158    }
12159
12160    #[test]
12161    fn rejects_entrada_para_with_dot() {
12162        // An `:entrada :para` value is a single DNS-1123 *label*, not
12163        // a subdomain — mirroring the `:membros :caixa` floor. The
12164        // strictest floor among the use sites wins.
12165        let mut s = three_member_spec();
12166        s.entrada.as_mut().unwrap().para = "team.cart".into();
12167        let err = s.validate().unwrap_err();
12168        assert!(
12169            matches!(
12170                err,
12171                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
12172                    if para == "team.cart" && reason.contains('.')
12173            ),
12174            "got {err:?}"
12175        );
12176    }
12177
12178    #[test]
12179    fn rejects_entrada_para_with_unicode() {
12180        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
12181        // (`xn--…`) before it reaches K8s.
12182        let mut s = three_member_spec();
12183        s.entrada.as_mut().unwrap().para = "café".into();
12184        let err = s.validate().unwrap_err();
12185        assert!(
12186            matches!(
12187                err,
12188                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
12189            ),
12190            "got {err:?}"
12191        );
12192    }
12193
12194    #[test]
12195    fn rejects_entrada_para_with_leading_hyphen() {
12196        // DNS-1123 boundary rule: labels must start and end with an
12197        // alphanumeric. K8s rejects `-cart` outright.
12198        let mut s = three_member_spec();
12199        s.entrada.as_mut().unwrap().para = "-cart".into();
12200        let err = s.validate().unwrap_err();
12201        assert!(
12202            matches!(
12203                err,
12204                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
12205                    if para == "-cart" && reason.contains("start and end")
12206            ),
12207            "got {err:?}"
12208        );
12209    }
12210
12211    #[test]
12212    fn rejects_entrada_para_with_trailing_hyphen() {
12213        // Symmetric boundary arm.
12214        let mut s = three_member_spec();
12215        s.entrada.as_mut().unwrap().para = "cart-".into();
12216        let err = s.validate().unwrap_err();
12217        assert!(
12218            matches!(
12219                err,
12220                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
12221                    if para == "cart-" && reason.contains("start and end")
12222            ),
12223            "got {err:?}"
12224        );
12225    }
12226
12227    #[test]
12228    fn rejects_entrada_para_too_long() {
12229        // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
12230        // bytes per label. K8s rejects longer names at admission on
12231        // every `metadata.name` axis.
12232        let mut s = three_member_spec();
12233        s.entrada.as_mut().unwrap().para = "a".repeat(64);
12234        let err = s.validate().unwrap_err();
12235        assert!(
12236            matches!(
12237                err,
12238                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
12239                    if para.len() == 64 && reason.contains("max length")
12240            ),
12241            "got {err:?}"
12242        );
12243    }
12244
12245    #[test]
12246    fn entrada_para_empty_takes_precedence_over_invalid() {
12247        // Order pin: the `EntradaParaEmpty` arm fires before the
12248        // `EntradaParaInvalid` parse-side arm — same empty-first
12249        // cascade `validate_membro_caixa` / `validate_placement_cluster`
12250        // / `validate_contrato_caixa` already establish.
12251        let mut s = three_member_spec();
12252        s.entrada.as_mut().unwrap().para = String::new();
12253        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
12254    }
12255
12256    #[test]
12257    fn entrada_para_shape_fires_before_membership_lookup() {
12258        // The load-bearing pin: an invalid-shape `:para` surfaces its
12259        // *own* diagnostic, not the misframed `EntradaMemberMissing`.
12260        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
12261        // an invalid-shape `:para` could never legitimately match any
12262        // member — the prior `EntradaMemberMissing` diagnostic framed
12263        // a structural impossibility as a graph-membership failure.
12264        let mut s = three_member_spec();
12265        s.entrada.as_mut().unwrap().para = "Cart".into();
12266        let err = s.validate().unwrap_err();
12267        assert!(
12268            matches!(
12269                err,
12270                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
12271            ),
12272            "got {err:?}"
12273        );
12274    }
12275
12276    #[test]
12277    fn entrada_para_shape_fires_before_host_gate() {
12278        // Per-`:entrada` order pin: the `:para` shape gate fires
12279        // before the `:host` gate, mirroring the existing
12280        // `entrada_host_member_missing_takes_precedence_over_host_invalid`
12281        // ordering where the member-lookup arm preceded the host gate.
12282        // The shape gate slots ahead of that, so a malformed `:para`
12283        // surfaces its own diagnostic even when `:host` is also wrong.
12284        let mut s = three_member_spec();
12285        let e = s.entrada.as_mut().unwrap();
12286        e.para = "Cart".into();
12287        e.host = "BAD HOST".into();
12288        let err = s.validate().unwrap_err();
12289        assert!(
12290            matches!(
12291                err,
12292                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
12293            ),
12294            "got {err:?}"
12295        );
12296    }
12297
12298    #[test]
12299    fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
12300        // Strict-improvement pin: a well-shaped `:para` that simply
12301        // isn't in `:membros` (a phantom reference — author meant to
12302        // add the member but didn't, or renamed and missed an
12303        // update) still surfaces `EntradaMemberMissing`, unchanged.
12304        // The shape gate only intercepts inputs that could never
12305        // legitimately match a validated member.
12306        let mut s = three_member_spec();
12307        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
12308        let err = s.validate().unwrap_err();
12309        assert!(
12310            matches!(
12311                err,
12312                AplicacaoError::EntradaMemberMissing { ref para }
12313                    if para == "phantom-shim"
12314            ),
12315            "got {err:?}"
12316        );
12317    }
12318
12319    #[test]
12320    fn entrada_para_invalid_diagnostic_carries_offending_para() {
12321        // The diagnostic-shape pin: the error names the offending
12322        // `:para` value verbatim plus a non-empty parser-shaped
12323        // reason, so the author can grep their caixa.lisp for
12324        // `:para "<name>"` and fix it in one edit. Same diagnostic
12325        // shape as `MembroCaixaInvalid` (3f9d7a0),
12326        // `PlacementClusterInvalid` (6c8c00b), and
12327        // `ContratoCaixaInvalid` (8d5af6b).
12328        let mut s = three_member_spec();
12329        s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
12330        let err = s.validate().unwrap_err();
12331        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
12332            panic!("expected EntradaParaInvalid, got {err:?}");
12333        };
12334        assert_eq!(para, "BAD_NAME");
12335        assert!(
12336            !reason.is_empty(),
12337            "EntradaParaInvalid `reason` must carry a parser-shaped wording"
12338        );
12339    }
12340
12341    #[test]
12342    fn accepts_canonical_entrada_para_forms() {
12343        // Positive-control sweep covering the DNS-1123 label shapes a
12344        // caixa author is realistically going to write on `:entrada
12345        // :para`. Pin every leg so a future tightening that bans
12346        // (e.g.) digit-start identifiers surfaces here, mirroring
12347        // `accepts_canonical_membro_caixa_forms` and
12348        // `accepts_canonical_contrato_caixa_forms` on the peer name
12349        // axes.
12350        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
12351            let mut s = three_member_spec();
12352            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
12353            s.contratos = vec![contract_http(form, "catalog", "/x")];
12354            s.entrada = Some(Entrada {
12355                host: "checkout.quero.cloud".into(),
12356                para: form.into(),
12357                paths: vec!["/api".into()],
12358                port: 8080,
12359            });
12360            s.validate().unwrap_or_else(|e| {
12361                panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
12362            });
12363        }
12364    }
12365
12366    #[test]
12367    fn rejects_replicated_without_clusters() {
12368        let mut s = three_member_spec();
12369        s.placement.clusters = vec![];
12370        assert!(matches!(
12371            s.validate().unwrap_err(),
12372            AplicacaoError::PlacementWithoutClusters { .. }
12373        ));
12374    }
12375
12376    #[test]
12377    fn rejects_sharded_without_key() {
12378        let mut s = three_member_spec();
12379        s.placement.estrategia = PlacementStrategy::Sharded;
12380        s.placement.shard_key = None;
12381        s.placement.clusters = vec!["rio".into()];
12382        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
12383    }
12384
12385    #[test]
12386    fn sharded_with_key_validates() {
12387        let mut s = three_member_spec();
12388        s.placement.estrategia = PlacementStrategy::Sharded;
12389        s.placement.shard_key = Some("$tenantId".into());
12390        s.validate().unwrap();
12391    }
12392
12393    #[test]
12394    fn round_trip_via_json_preserves_shape() {
12395        let s = three_member_spec();
12396        let json = serde_json::to_string(&s.membros).unwrap();
12397        let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
12398        assert_eq!(back, s.membros);
12399
12400        let json = serde_json::to_string(&s.contratos).unwrap();
12401        let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
12402        assert_eq!(back, s.contratos);
12403
12404        let json = serde_json::to_string(&s.placement).unwrap();
12405        let back: Placement = serde_json::from_str(&json).unwrap();
12406        assert_eq!(back, s.placement);
12407
12408        let json = serde_json::to_string(&s.entrada).unwrap();
12409        let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
12410        assert_eq!(back, s.entrada);
12411    }
12412
12413    #[test]
12414    fn rate_limit_round_trip_seconds() {
12415        let policy = MeshPolicy {
12416            rate_limit: Some(RateLimit {
12417                rate: 100,
12418                window: Duration::from_secs(1),
12419            }),
12420            ..Default::default()
12421        };
12422        let json = serde_json::to_string(&policy).unwrap();
12423        assert!(json.contains("\"100/s\""));
12424        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
12425        assert_eq!(back.rate_limit.unwrap().rate, 100);
12426        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
12427    }
12428
12429    #[test]
12430    fn rate_limit_round_trip_minutes() {
12431        let policy = MeshPolicy {
12432            rate_limit: Some(RateLimit {
12433                rate: 5000,
12434                window: Duration::from_secs(60),
12435            }),
12436            ..Default::default()
12437        };
12438        let json = serde_json::to_string(&policy).unwrap();
12439        assert!(json.contains("\"5000/m\""));
12440    }
12441
12442    #[test]
12443    fn circuit_breaker_round_trip() {
12444        let policy = MeshPolicy {
12445            circuit_breaker: Some(CircuitBreaker {
12446                max_failures: 5,
12447                window: Duration::from_secs(60),
12448            }),
12449            ..Default::default()
12450        };
12451        let json = serde_json::to_string(&policy).unwrap();
12452        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
12453        assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
12454        assert_eq!(
12455            back.circuit_breaker.unwrap().window,
12456            Duration::from_secs(60)
12457        );
12458    }
12459
12460    #[test]
12461    fn rejects_http_contrato_without_endpoint() {
12462        let mut s = three_member_spec();
12463        s.contratos.push(WitContract {
12464            de: "cart".into(),
12465            para: "catalog".into(),
12466            wit: "wasi:http/proxy".into(),
12467            endpoint: None,
12468            subject: None,
12469            slot: None,
12470        });
12471        let err = s.validate().unwrap_err();
12472        assert!(matches!(
12473            err,
12474            AplicacaoError::ContratoMissingTarget {
12475                expected: WitTarget::HTTP_FIELD_NAME,
12476                ..
12477            }
12478        ));
12479    }
12480
12481    #[test]
12482    fn rejects_http_contrato_with_subject() {
12483        let mut s = three_member_spec();
12484        s.contratos.push(WitContract {
12485            de: "cart".into(),
12486            para: "catalog".into(),
12487            wit: "wasi:http/proxy".into(),
12488            endpoint: Some("/x".into()),
12489            subject: Some("not.allowed.here".into()),
12490            slot: None,
12491        });
12492        let err = s.validate().unwrap_err();
12493        assert!(matches!(
12494            err,
12495            AplicacaoError::ContratoWrongTarget {
12496                expected: WitTarget::HTTP_FIELD_NAME,
12497                ..
12498            }
12499        ));
12500    }
12501
12502    #[test]
12503    fn rejects_pubsub_contrato_without_subject() {
12504        let mut s = three_member_spec();
12505        s.contratos.push(WitContract {
12506            de: "cart".into(),
12507            para: "catalog".into(),
12508            wit: "nats:pub-sub".into(),
12509            endpoint: None,
12510            subject: None,
12511            slot: None,
12512        });
12513        let err = s.validate().unwrap_err();
12514        assert!(matches!(
12515            err,
12516            AplicacaoError::ContratoMissingTarget {
12517                expected: WitTarget::PUBSUB_FIELD_NAME,
12518                ..
12519            }
12520        ));
12521    }
12522
12523    #[test]
12524    fn rejects_pubsub_contrato_with_endpoint() {
12525        let mut s = three_member_spec();
12526        s.contratos.push(WitContract {
12527            de: "cart".into(),
12528            para: "catalog".into(),
12529            wit: "kafka:topic".into(),
12530            endpoint: Some("/wrong".into()),
12531            subject: Some("topic.x".into()),
12532            slot: None,
12533        });
12534        let err = s.validate().unwrap_err();
12535        assert!(matches!(
12536            err,
12537            AplicacaoError::ContratoWrongTarget {
12538                expected: WitTarget::PUBSUB_FIELD_NAME,
12539                ..
12540            }
12541        ));
12542    }
12543
12544    #[test]
12545    fn rejects_store_contrato_without_slot() {
12546        let mut s = three_member_spec();
12547        s.contratos.push(WitContract {
12548            de: "cart".into(),
12549            para: "catalog".into(),
12550            wit: "wasi:keyvalue/store".into(),
12551            endpoint: None,
12552            subject: None,
12553            slot: None,
12554        });
12555        let err = s.validate().unwrap_err();
12556        assert!(matches!(
12557            err,
12558            AplicacaoError::ContratoMissingTarget {
12559                expected: WitTarget::STORE_FIELD_NAME,
12560                ..
12561            }
12562        ));
12563    }
12564
12565    // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
12566
12567    #[test]
12568    fn rejects_http_contrato_with_empty_endpoint() {
12569        // `Some("")` for an HTTP endpoint passes the presence check
12570        // (target() previously returned WitTarget::Http { endpoint: "" })
12571        // but renders as a `path: ""` Cilium L7 rule that matches no
12572        // traffic. Same value-shape footgun closed for :entrada :paths
12573        // entries (eb3456d).
12574        let mut s = three_member_spec();
12575        s.contratos.push(WitContract {
12576            de: "cart".into(),
12577            para: "catalog".into(),
12578            wit: "wasi:http/proxy".into(),
12579            endpoint: Some(String::new()),
12580            subject: None,
12581            slot: None,
12582        });
12583        let err = s.validate().unwrap_err();
12584        assert!(
12585            matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
12586                if de == "cart" && para == "catalog"),
12587            "got {err:?}"
12588        );
12589    }
12590
12591    #[test]
12592    fn rejects_http_contrato_with_relative_endpoint() {
12593        // Cilium L7 :path + Gateway API PathPrefix both require a
12594        // leading `/`. Same shape required of :entrada :paths
12595        // (eb3456d). Lifted into target() so every consumer of the
12596        // typed WitTarget view inherits the guarantee.
12597        let mut s = three_member_spec();
12598        s.contratos.push(WitContract {
12599            de: "cart".into(),
12600            para: "catalog".into(),
12601            wit: "wasi:http/proxy".into(),
12602            endpoint: Some("products/:id".into()),
12603            subject: None,
12604            slot: None,
12605        });
12606        let err = s.validate().unwrap_err();
12607        assert!(
12608            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
12609                if endpoint == "products/:id"),
12610            "got {err:?}"
12611        );
12612    }
12613
12614    #[test]
12615    fn rejects_pubsub_contrato_with_empty_subject() {
12616        // NATS / Kafka publish without a subject is a no-op subscribe;
12617        // never the author's intent. Same empty-string rejection as
12618        // :membros :caixa, :placement :clusters entries, :entrada
12619        // :paths entries — every value carried by every typed slot is
12620        // value-shape-checked at validate().
12621        let mut s = three_member_spec();
12622        s.contratos.push(WitContract {
12623            de: "cart".into(),
12624            para: "catalog".into(),
12625            wit: "nats:pub-sub".into(),
12626            endpoint: None,
12627            subject: Some(String::new()),
12628            slot: None,
12629        });
12630        let err = s.validate().unwrap_err();
12631        assert!(
12632            matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
12633                if de == "cart" && para == "catalog"),
12634            "got {err:?}"
12635        );
12636    }
12637
12638    #[test]
12639    fn rejects_store_contrato_with_empty_slot() {
12640        // An empty slot template addresses the bucket root, defeating
12641        // the per-key isolation the slot exists for — a footgun on
12642        // `wasi:keyvalue/store` whose closest analog is the empty
12643        // shard-key rejected on :placement Sharded (c7c7799).
12644        let mut s = three_member_spec();
12645        s.contratos.push(WitContract {
12646            de: "cart".into(),
12647            para: "catalog".into(),
12648            wit: "wasi:keyvalue/store".into(),
12649            endpoint: None,
12650            subject: None,
12651            slot: Some(String::new()),
12652        });
12653        let err = s.validate().unwrap_err();
12654        assert!(
12655            matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
12656                if de == "cart" && para == "catalog"),
12657            "got {err:?}"
12658        );
12659    }
12660
12661    #[test]
12662    fn http_contrato_root_endpoint_validates() {
12663        // Pin the boundary case: a single-`/` endpoint is the catch-all
12664        // form the Gateway HTTPRoute renderer falls back to when
12665        // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
12666        // must remain a valid contrato endpoint too.
12667        let mut s = three_member_spec();
12668        s.contratos.push(contract_http("cart", "catalog", "/"));
12669        s.validate().unwrap();
12670    }
12671
12672    // ── :contratos :endpoint value-shape gate ────────────────────────────
12673    //
12674    // Mirrors the `:entrada :paths` value-shape suite on the peer
12675    // HTTP-path axis. Until this gate landed `WitContract::target()`
12676    // only refused the empty string + the missing-leading-`/` form
12677    // (c4213a4); a structurally invalid endpoint passed validate and
12678    // landed verbatim as a Cilium L7 `path:` rule
12679    // (caixa-mesh/src/lib.rs:311) that either silently dropped all
12680    // traffic or was rejected at apply time by Cilium policy admission.
12681    // Every authoring footgun the K8s Gateway API webhook / Cilium
12682    // policy validator would catch on admission now becomes a caixa-
12683    // build-time `ContratoEndpointInvalid` with the offending
12684    // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
12685    // shape as `EntradaPathInvalid` on the sibling axis; same shared
12686    // predicate (`crate::render::is_gateway_api_http_path`) ensures
12687    // drift between the two axes' rule enforcement is a build error
12688    // at the predicate.
12689
12690    fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
12691        // Fresh spec per call so the would-be-duplicate edge
12692        // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
12693        // `three_member_spec`'s pre-existing
12694        // `(cart, catalog, …, /products/:id)` entry — only the
12695        // endpoint payload differs.
12696        let mut s = three_member_spec();
12697        s.contratos.push(contract_http("cart", "catalog", ep));
12698        s.validate().unwrap_err()
12699    }
12700
12701    #[test]
12702    fn rejects_http_contrato_endpoint_with_query() {
12703        // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
12704        // silently rendered as a Cilium L7 `path: "/charge?token=X"`
12705        // rule the L7 matcher would never satisfy.
12706        let err = contrato_endpoint_err("/charge?token=X");
12707        assert!(
12708            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12709                if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
12710            "got {err:?}"
12711        );
12712    }
12713
12714    #[test]
12715    fn rejects_http_contrato_endpoint_with_fragment() {
12716        let err = contrato_endpoint_err("/charge#frag");
12717        assert!(
12718            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12719                if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
12720            "got {err:?}"
12721        );
12722    }
12723
12724    #[test]
12725    fn rejects_http_contrato_endpoint_with_whitespace() {
12726        let err = contrato_endpoint_err("/foo bar");
12727        assert!(
12728            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12729                if endpoint == "/foo bar" && reason.contains("whitespace")),
12730            "got {err:?}"
12731        );
12732    }
12733
12734    #[test]
12735    fn rejects_http_contrato_endpoint_with_control_char() {
12736        let err = contrato_endpoint_err("/api/\x01bar");
12737        assert!(
12738            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12739                if endpoint == "/api/\x01bar" && reason.contains("control character")),
12740            "got {err:?}"
12741        );
12742    }
12743
12744    #[test]
12745    fn rejects_http_contrato_endpoint_with_non_ascii() {
12746        let err = contrato_endpoint_err("/api/café");
12747        assert!(
12748            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12749                if endpoint == "/api/café" && reason.contains("non-ASCII")),
12750            "got {err:?}"
12751        );
12752    }
12753
12754    #[test]
12755    fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
12756        let err = contrato_endpoint_err("/api//cart");
12757        assert!(
12758            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12759                if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
12760            "got {err:?}"
12761        );
12762    }
12763
12764    #[test]
12765    fn rejects_http_contrato_endpoint_with_dot_segment() {
12766        let err = contrato_endpoint_err("/api/./cart");
12767        assert!(
12768            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12769                if endpoint == "/api/./cart" && reason.contains("`.` segment")),
12770            "got {err:?}"
12771        );
12772    }
12773
12774    #[test]
12775    fn rejects_http_contrato_endpoint_with_parent_segment() {
12776        // Path-traversal in a contrato endpoint is the canonical
12777        // "L7 rule that the workload's HTTP server's path-resolution
12778        // logic interprets differently than the policy enforcer"
12779        // footgun. Rejected outright at validate time.
12780        let err = contrato_endpoint_err("/api/../etc");
12781        assert!(
12782            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12783                if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
12784            "got {err:?}"
12785        );
12786    }
12787
12788    #[test]
12789    fn rejects_http_contrato_endpoint_too_long() {
12790        // 1025-byte endpoint — one over the Gateway API
12791        // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
12792        // path matcher has no inherent length limit but the policy
12793        // CR itself rides through the K8s apiserver, which enforces
12794        // ConfigMap-shaped limits; sharing the Gateway API cap is the
12795        // conservative floor.
12796        let big = format!("/api/{}", "a".repeat(1020));
12797        assert_eq!(big.len(), 1025);
12798        let err = contrato_endpoint_err(&big);
12799        assert!(
12800            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12801                if endpoint == &big && reason.contains("max length of 1024")),
12802            "got {err:?}"
12803        );
12804    }
12805
12806    #[test]
12807    fn http_contrato_endpoint_max_length_validates() {
12808        // 1024-byte endpoint — exactly the cap. Boundary pin: drift
12809        // in the cap surfaces here and at
12810        // `rejects_http_contrato_endpoint_too_long` simultaneously,
12811        // mirroring `entrada_path_max_length_validates` on the peer
12812        // axis.
12813        let big = format!("/api/{}", "a".repeat(1019));
12814        assert_eq!(big.len(), 1024);
12815        let mut s = three_member_spec();
12816        s.contratos.push(contract_http("cart", "catalog", &big));
12817        s.validate().unwrap();
12818    }
12819
12820    #[test]
12821    fn http_contrato_endpoint_accepts_canonical_forms() {
12822        // Positive-set sweep: every canonical HTTP-path shape the
12823        // sibling `:entrada :paths` axis accepts (the bare-root `/`,
12824        // plain paths, hidden-file-style `.config` segments distinct
12825        // from the `.` segment, digit-bearing segments, the canonical
12826        // route-template `:param` form, trailing-slash form,
12827        // percent-encoded segments, the `/foo..bar` interior-`..`-
12828        // substring forms that are NOT `..` segments) must remain a
12829        // valid contrato endpoint too. Drift between this list and
12830        // the entrada path positive sweep surfaces at the shared
12831        // `is_gateway_api_http_path` substrate-side suite — one
12832        // source of truth. Uses a fresh `(payment, catalog)` edge so
12833        // none of the swept endpoints collide with the pre-existing
12834        // `(cart, catalog, /products/:id)` / `(cart, payment,
12835        // /charge)` entries in `three_member_spec`.
12836        for ep in [
12837            "/",
12838            "/charge",
12839            "/v1/charge",
12840            "/api/.config",
12841            "/products/:id",
12842            "/api/cart/",
12843            "/api/caf%C3%A9",
12844            "/foo..bar",
12845            "/...",
12846        ] {
12847            let mut s = three_member_spec();
12848            s.contratos.push(contract_http("payment", "catalog", ep));
12849            s.validate()
12850                .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
12851        }
12852    }
12853
12854    #[test]
12855    fn contrato_endpoint_empty_takes_precedence_over_invalid() {
12856        // Ordering pin: `ContratoEndpointEmpty` is the more self-
12857        // locating diagnostic on `""` and must lead — the value-
12858        // shape gate is only reached after the empty-check fires.
12859        // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
12860        // on the peer axis.
12861        let mut s = three_member_spec();
12862        s.contratos.push(WitContract {
12863            de: "cart".into(),
12864            para: "catalog".into(),
12865            wit: "wasi:http/proxy".into(),
12866            endpoint: Some(String::new()),
12867            subject: None,
12868            slot: None,
12869        });
12870        let err = s.validate().unwrap_err();
12871        assert!(
12872            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
12873            "got {err:?}"
12874        );
12875    }
12876
12877    #[test]
12878    fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
12879        // Ordering pin: an endpoint without a leading `/` surfaces the
12880        // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
12881        // value-shape gate is only consulted on endpoints that already
12882        // satisfy the absolute-prefix invariant. Mirrors
12883        // `entrada_path_not_absolute_takes_precedence_over_invalid`.
12884        let err = contrato_endpoint_err("bad path");
12885        assert!(
12886            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
12887                if endpoint == "bad path"),
12888            "got {err:?}"
12889        );
12890    }
12891
12892    #[test]
12893    fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
12894        // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
12895        // `:para` + a non-empty reason flow through verbatim so the
12896        // author can grep their caixa.lisp for the offending contrato
12897        // block and fix it in one edit. Same shape as
12898        // `entrada_path_diagnostic_carries_offending_path`.
12899        let err = contrato_endpoint_err("/api?q=1");
12900        match err {
12901            AplicacaoError::ContratoEndpointInvalid {
12902                de,
12903                para,
12904                endpoint,
12905                reason,
12906            } => {
12907                assert_eq!(de, "cart");
12908                assert_eq!(para, "catalog");
12909                assert_eq!(endpoint, "/api?q=1");
12910                assert!(!reason.is_empty(), "reason field must be non-empty");
12911            }
12912            other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
12913        }
12914    }
12915
12916    #[test]
12917    fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
12918        // The compounding theorem: every &str inside a WitTarget
12919        // returned by target() is non-empty (and absolute, for Http).
12920        // Renderers downstream of typed_view() can rely on this
12921        // without re-checking — the type system carries the proof.
12922        let http = contract_http("cart", "catalog", "/x");
12923        match http.target().unwrap() {
12924            WitTarget::Http { endpoint } => {
12925                assert!(!endpoint.is_empty());
12926                assert!(endpoint.starts_with('/'));
12927            }
12928            other => panic!("expected Http, got {other:?}"),
12929        }
12930        let nats = WitContract {
12931            de: "a".into(),
12932            para: "b".into(),
12933            wit: "nats:pub-sub".into(),
12934            endpoint: None,
12935            subject: Some("topic.x".into()),
12936            slot: None,
12937        };
12938        match nats.target().unwrap() {
12939            WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
12940            other => panic!("expected PubSub, got {other:?}"),
12941        }
12942        let kv = WitContract {
12943            de: "a".into(),
12944            para: "b".into(),
12945            wit: "wasi:keyvalue/store".into(),
12946            endpoint: None,
12947            subject: None,
12948            slot: Some("checkout/$orderId".into()),
12949        };
12950        match kv.target().unwrap() {
12951            WitTarget::Store { slot } => assert!(!slot.is_empty()),
12952            other => panic!("expected Store, got {other:?}"),
12953        }
12954    }
12955
12956    #[test]
12957    fn target_diagnostic_names_offending_endpoint_value() {
12958        // When the malformed endpoint string is non-trivial, the
12959        // diagnostic carries the actual value back to the author —
12960        // not a generic "endpoint malformed" error.
12961        let bad = WitContract {
12962            de: "src".into(),
12963            para: "dst".into(),
12964            wit: "wasi:http/proxy".into(),
12965            endpoint: Some("api/v1/charge".into()),
12966            subject: None,
12967            slot: None,
12968        };
12969        match bad.target().unwrap_err() {
12970            AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
12971                assert_eq!(de, "src");
12972                assert_eq!(para, "dst");
12973                assert_eq!(endpoint, "api/v1/charge");
12974            }
12975            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
12976        }
12977    }
12978
12979    #[test]
12980    fn rejects_unknown_wit_with_target_set() {
12981        let mut s = three_member_spec();
12982        s.contratos.push(WitContract {
12983            de: "cart".into(),
12984            para: "catalog".into(),
12985            wit: "custom:exchange".into(),
12986            endpoint: Some("/leaked".into()),
12987            subject: None,
12988            slot: None,
12989        });
12990        let err = s.validate().unwrap_err();
12991        assert!(matches!(
12992            err,
12993            AplicacaoError::ContratoWrongTarget {
12994                expected: WitTarget::CAPABILITY_EXPECTED,
12995                ..
12996            }
12997        ));
12998    }
12999
13000    #[test]
13001    fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
13002        // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
13003        // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
13004        // fourth arm of the same "which payload field name goes in the
13005        // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
13006        // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13007        // consts cover on the peer HTTP / PubSub / Store arms
13008        // (`wit_target_field_name_pins_per_variant`). Until this lift
13009        // landed the byte-string sat twice — once inline in the
13010        // [`WitContract::target`] Capability-arm rejection at the
13011        // production dispatch, once in `rejects_unknown_wit_with_target_set`
13012        // pinning against the same literal — with no compile-time link
13013        // between them. Same "one canonical declaration, next to the
13014        // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
13015        // lift established for the payload-less arm's human-readable
13016        // label axis; this test is the shape peer of
13017        // `wit_target_label_pins_per_variant`'s Capability-arm assertion
13018        // pair (routes-through-const + scalar-value pin) on the
13019        // wrong-target diagnostic-scalar axis.
13020        //
13021        // Fail-before-pass-after was verified locally by mutating the
13022        // const declaration to `"capability"` — the scalar-value pin
13023        // below fires (`"capability" != "none"`) and the routes-through
13024        // assertion below still holds (production and const walk in
13025        // lockstep), which is the correct behavior: a rename on the
13026        // const drifts here first, not at a downstream consumer.
13027        assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
13028
13029        let mut s = three_member_spec();
13030        s.contratos.push(WitContract {
13031            de: "cart".into(),
13032            para: "catalog".into(),
13033            wit: "custom:exchange".into(),
13034            endpoint: Some("/leaked".into()),
13035            subject: None,
13036            slot: None,
13037        });
13038        match s.validate().unwrap_err() {
13039            AplicacaoError::ContratoWrongTarget { expected, .. } => {
13040                assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
13041            }
13042            other => panic!("expected ContratoWrongTarget, got {other:?}"),
13043        }
13044    }
13045
13046    #[test]
13047    fn unknown_wit_capability_only_validates() {
13048        let mut s = three_member_spec();
13049        s.contratos.push(WitContract {
13050            de: "cart".into(),
13051            para: "catalog".into(),
13052            // A WIT world we haven't yet shaped — accept it as a typed
13053            // capability edge so authors aren't blocked while the WIT
13054            // registry catches up. No payload field may be carried.
13055            wit: "custom:exchange".into(),
13056            endpoint: None,
13057            subject: None,
13058            slot: None,
13059        });
13060        s.validate().unwrap();
13061        let added = s.contratos.last().unwrap();
13062        assert_eq!(added.target().unwrap(), WitTarget::Capability);
13063    }
13064
13065    #[test]
13066    fn target_typed_view_round_trips_each_shape() {
13067        let http = contract_http("cart", "catalog", "/products/:id");
13068        assert_eq!(
13069            http.target().unwrap(),
13070            WitTarget::Http {
13071                endpoint: "/products/:id"
13072            }
13073        );
13074        let nats = WitContract {
13075            de: "a".into(),
13076            para: "b".into(),
13077            wit: "nats:pub-sub".into(),
13078            endpoint: None,
13079            subject: Some("topic.x".into()),
13080            slot: None,
13081        };
13082        assert_eq!(
13083            nats.target().unwrap(),
13084            WitTarget::PubSub { subject: "topic.x" }
13085        );
13086        let kv = WitContract {
13087            de: "a".into(),
13088            para: "b".into(),
13089            wit: "wasi:keyvalue/store".into(),
13090            endpoint: None,
13091            subject: None,
13092            slot: Some("checkout/$orderId".into()),
13093        };
13094        assert_eq!(
13095            kv.target().unwrap(),
13096            WitTarget::Store {
13097                slot: "checkout/$orderId"
13098            }
13099        );
13100    }
13101
13102    #[test]
13103    fn wit_contract_kind_predicates() {
13104        let http = contract_http("a", "b", "/x");
13105        assert!(http.is_http());
13106        assert!(!http.is_pubsub());
13107        assert!(!http.is_store());
13108        assert!(!http.is_capability());
13109
13110        let nats = WitContract {
13111            de: "a".into(),
13112            para: "b".into(),
13113            wit: "nats:pub-sub".into(),
13114            endpoint: None,
13115            subject: Some("topic.x".into()),
13116            slot: None,
13117        };
13118        assert!(nats.is_pubsub());
13119        assert!(!nats.is_http());
13120        assert!(!nats.is_capability());
13121
13122        let kv = WitContract {
13123            de: "a".into(),
13124            para: "b".into(),
13125            wit: "wasi:keyvalue/store".into(),
13126            endpoint: None,
13127            subject: None,
13128            slot: Some("checkout/$orderId".into()),
13129        };
13130        assert!(kv.is_store());
13131        assert!(!kv.is_http());
13132        assert!(!kv.is_capability());
13133
13134        // Fourth arm on the paired closed-set predicate family: the
13135        // payload-less capability edge that projects to the payload-
13136        // less [`WitTarget::Capability`] arm under [`WitContract::target`].
13137        // Extends the 3-arm predicate sweep this test opened to cover
13138        // the closed 4-way partition [`WitContract::is_capability`]
13139        // closes on the pre-projection WIT-shape axis, matched with the
13140        // sibling post-projection [`WitTarget`]-side `IsVariant`-derived
13141        // 4-arm predicate set.
13142        let cap = WitContract {
13143            de: "a".into(),
13144            para: "b".into(),
13145            wit: "custom:capability-only".into(),
13146            endpoint: None,
13147            subject: None,
13148            slot: None,
13149        };
13150        assert!(cap.is_capability());
13151        assert!(!cap.is_http());
13152        assert!(!cap.is_pubsub());
13153        assert!(!cap.is_store());
13154    }
13155
13156    // ── :contratos :wit value-shape gate ─────────────────────────────────
13157    //
13158    // Mirrors the `:contratos :endpoint` value-shape suite on the peer
13159    // dispatch-discriminator axis. Until this gate landed
13160    // `WitContract::target()` accepted any non-empty string and
13161    // silently demoted unrecognized shapes to a capability-only L4
13162    // edge — the canonical "I thought I had L7 HTTP routing, got
13163    // L4-only" footgun. Every authoring footgun the WIT registry's
13164    // own grammar rejects (uppercase, hyphen-for-colon typo,
13165    // whitespace, empty package, doubled `@`, …) now becomes a
13166    // caixa-build-time `ContratoWitInvalid` with the offending
13167    // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
13168    // as `ContratoEndpointInvalid` on the sibling axis; same shared
13169    // predicate (`crate::render::is_wit_world_ref`) ensures drift
13170    // between any two axes' rule enforcement is a build error at the
13171    // predicate, not piecemeal across renderers.
13172
13173    fn contrato_wit_err(wit: &str) -> AplicacaoError {
13174        // Fresh spec per call so the new contract doesn't collide on
13175        // identity with `three_member_spec`'s pre-existing entries.
13176        // The new edge uses `(payment, catalog)` — a pair the fixture
13177        // doesn't already declare — with no payload field set, so the
13178        // wit-shape gate fires before any payload-shape arm.
13179        let mut s = three_member_spec();
13180        s.contratos.push(WitContract {
13181            de: "payment".into(),
13182            para: "catalog".into(),
13183            wit: wit.into(),
13184            endpoint: None,
13185            subject: None,
13186            slot: None,
13187        });
13188        s.validate().unwrap_err()
13189    }
13190
13191    #[test]
13192    fn rejects_wit_with_uppercase_namespace() {
13193        // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
13194        // didn't match the lowercase `wasi:http/` prefix is_http() keys
13195        // off, so the dispatch fell through to the capability arm and
13196        // the contract silently rendered as an L4-only Cilium edge.
13197        // The new gate surfaces the uppercase typo at validate time
13198        // with the offending `:wit` named.
13199        let err = contrato_wit_err("WASI:http/proxy");
13200        assert!(
13201            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
13202                if wit == "WASI:http/proxy" && reason.contains("lowercase")),
13203            "got {err:?}"
13204        );
13205    }
13206
13207    #[test]
13208    fn rejects_wit_with_hyphen_for_colon_typo() {
13209        // The canonical "I forgot the `:` separator" typo — pre-gate
13210        // this passed as Capability silently, so the renderer emitted
13211        // an L4-only policy where the author expected L7 HTTP rules.
13212        let err = contrato_wit_err("wasi-http/proxy");
13213        assert!(
13214            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
13215                if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
13216            "got {err:?}"
13217        );
13218    }
13219
13220    #[test]
13221    fn rejects_wit_with_multiple_colons() {
13222        // Doubled `:` — the namespace/package split has nowhere to
13223        // anchor, so the dispatch silently demotes to Capability.
13224        let err = contrato_wit_err("wasi:http:proxy");
13225        assert!(
13226            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
13227                if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
13228            "got {err:?}"
13229        );
13230    }
13231
13232    #[test]
13233    fn rejects_wit_with_empty_package() {
13234        // `wasi:` — namespace alone with no package. Pre-gate this
13235        // failed neither the is_http nor is_pubsub nor is_store
13236        // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
13237        // a bare `wasi:`), so it silently demoted to Capability.
13238        let err = contrato_wit_err("wasi:");
13239        assert!(
13240            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
13241                if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
13242            "got {err:?}"
13243        );
13244    }
13245
13246    #[test]
13247    fn rejects_wit_with_underscore() {
13248        // Underscore — WIT identifiers are kebab-case, same rule
13249        // DNS-1123 enforces on its peer axes. The diagnostic carries
13250        // the explicit "use `-` instead" remediation.
13251        let err = contrato_wit_err("wasi:http_proxy");
13252        assert!(
13253            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
13254                if wit == "wasi:http_proxy" && reason.contains('_')),
13255            "got {err:?}"
13256        );
13257    }
13258
13259    #[test]
13260    fn rejects_wit_with_whitespace() {
13261        // Whitespace mid-token — the prefix check matches but the
13262        // package-and-onward parse silently demoted to Capability.
13263        let err = contrato_wit_err("wasi:http proxy");
13264        assert!(
13265            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
13266                if wit == "wasi:http proxy" && reason.contains("whitespace")),
13267            "got {err:?}"
13268        );
13269    }
13270
13271    #[test]
13272    fn rejects_wit_with_non_ascii() {
13273        // Un-percent-encoded non-ASCII byte — the canonical "I copied
13274        // the package name from a doc with smart quotes / accented
13275        // characters" footgun.
13276        let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
13277        assert!(
13278            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
13279                if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
13280            "got {err:?}"
13281        );
13282    }
13283
13284    #[test]
13285    fn rejects_wit_with_consecutive_hyphens() {
13286        // `pub--sub` — WIT identifiers join words with single hyphens.
13287        let err = contrato_wit_err("nats:pub--sub");
13288        assert!(
13289            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
13290                if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
13291            "got {err:?}"
13292        );
13293    }
13294
13295    #[test]
13296    fn rejects_wit_with_trailing_at_no_version() {
13297        // `wasi:http/proxy@` — the version-suffix author started to
13298        // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
13299        // parser would reject this; surface it at validate time.
13300        let err = contrato_wit_err("wasi:http/proxy@");
13301        assert!(
13302            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
13303                if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
13304            "got {err:?}"
13305        );
13306    }
13307
13308    #[test]
13309    fn rejects_wit_too_long() {
13310        // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
13311        // The legitimate-shape arms all pass (lowercase, single `:`,
13312        // kebab-case identifiers); only the cap arm fires. Surfaces
13313        // the paste-from-binary / accidental-multi-line-blob landing
13314        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
13315        // on the peer axis.
13316        let big = format!("wasi:{}", "a".repeat(124));
13317        assert_eq!(big.len(), 129);
13318        let err = contrato_wit_err(&big);
13319        assert!(
13320            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
13321                if wit == &big && reason.contains("max length of 128")),
13322            "got {err:?}"
13323        );
13324    }
13325
13326    #[test]
13327    fn wit_max_length_validates() {
13328        // 128-byte WIT reference — exactly the cap. Boundary pin:
13329        // drift in the cap surfaces here and at `rejects_wit_too_long`
13330        // simultaneously, mirroring
13331        // `http_contrato_endpoint_max_length_validates` on the peer
13332        // axis.
13333        let big = format!("wasi:{}", "a".repeat(123));
13334        assert_eq!(big.len(), 128);
13335        let mut s = three_member_spec();
13336        s.contratos.push(WitContract {
13337            de: "payment".into(),
13338            para: "catalog".into(),
13339            wit: big,
13340            endpoint: None,
13341            subject: None,
13342            slot: None,
13343        });
13344        s.validate().unwrap();
13345    }
13346
13347    #[test]
13348    fn wit_accepts_canonical_forms_at_aplicacao_layer() {
13349        // Positive-set sweep through the AplicacaoSpec::validate
13350        // surface (rather than the substrate-side predicate directly)
13351        // — pins every shape the existing test fixtures + the
13352        // checkout-aplicacao example carry, so the gate's accept-set
13353        // matches the substrate's emit-set. Drift between this list
13354        // and `render::tests::wit_world_ref_accepts_canonical_forms`
13355        // surfaces at the substrate layer's positive sweep — one
13356        // source of truth for the rule.
13357        for wit in [
13358            "wasi:http/proxy",
13359            "wasi:keyvalue/store",
13360            "nats:pub-sub",
13361            "kafka:topic",
13362            "custom:exchange",
13363            "pleme:cap/audit",
13364            "wasi:http/proxy@0.2.0",
13365        ] {
13366            // Payload field paired to the dispatched WIT shape so the
13367            // shape-↔-target arm doesn't fire instead of the wit-shape
13368            // arm we're exercising. Routes off the same
13369            // `wit_shape_is_http` / `wit_shape_is_pubsub` /
13370            // `wit_shape_is_store` free functions the production
13371            // `WitContract::is_http` / `is_pubsub` / `is_store`
13372            // methods delegate to (both consult the lifted
13373            // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
13374            // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
13375            // future prefix addition to the routing accept-set
13376            // reaches this test's payload-dispatch arm by
13377            // construction — no per-test-site drift can hide a
13378            // shape-→-target-slot mismatch that would silently
13379            // demote a canonical `:wit` value to the
13380            // `(None, None, None)` capability-only arm and let the
13381            // `AplicacaoSpec::validate` positive sweep pass on a
13382            // shape it should exercise as HTTP / pub-sub / store.
13383            let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
13384                (Some("/x".into()), None, None)
13385            } else if wit_shape_is_pubsub(wit) {
13386                (None, Some("topic.x".into()), None)
13387            } else if wit_shape_is_store(wit) {
13388                (None, None, Some("bucket/$key".into()))
13389            } else {
13390                (None, None, None)
13391            };
13392            let mut s = three_member_spec();
13393            s.contratos.push(WitContract {
13394                de: "payment".into(),
13395                para: "catalog".into(),
13396                wit: wit.into(),
13397                endpoint,
13398                subject,
13399                slot,
13400            });
13401            s.validate()
13402                .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
13403        }
13404    }
13405
13406    #[test]
13407    fn wit_shape_predicates_accept_canonical_prefix_set() {
13408        // Positive-set sweep pinning every prefix in
13409        // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
13410        // WIT_STORE_SHAPE_PREFIXES against the three free-function
13411        // dispatch predicates. The six prefixes are the load-bearing
13412        // routing keys the substrate's WIT-shape dispatch consults
13413        // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
13414        // key/value-store-slot admission); any drift between the
13415        // free-function accept-set and this list surfaces here
13416        // rather than at apply time as a silent
13417        // shape-→-capability-only demotion.
13418        assert!(wit_shape_is_http("wasi:http/proxy"));
13419        assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
13420        assert!(wit_shape_is_http("http:incoming"));
13421
13422        assert!(wit_shape_is_pubsub("nats:pub-sub"));
13423        assert!(wit_shape_is_pubsub("kafka:topic"));
13424
13425        assert!(wit_shape_is_store("wasi:keyvalue/store"));
13426        assert!(wit_shape_is_store("kv:cache/session"));
13427    }
13428
13429    #[test]
13430    fn wit_shape_predicates_reject_uncanonical_forms() {
13431        // Negative-set pin: the six canonical prefixes are
13432        // lowercase-only (mirrors the `is_wit_world_ref` substrate
13433        // predicate's lowercase invariant — see its docstring on the
13434        // "I thought I had L7 HTTP routing, got L4-only" footgun).
13435        // The empty string, an uppercase-prefixed form, a hyphen-
13436        // instead-of-colon typo, and a bare kebab identifier all miss
13437        // every shape arm — reachable-by-construction only via the
13438        // `is_wit_world_ref` gate that admission-checks the `:wit`
13439        // value first, but pinned here so any future
13440        // free-function change (e.g. a case-insensitive
13441        // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
13442        // this unit level.
13443        for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
13444            assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
13445            assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
13446            assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
13447        }
13448    }
13449
13450    #[test]
13451    fn wit_shape_predicates_partition_canonical_set() {
13452        // Every canonical prefix routes to exactly one shape arm —
13453        // the three prefix sets are pairwise disjoint. Pins the
13454        // routing property [`WitContract::target`] relies on: an
13455        // `is_http()` return of `true` guarantees `is_pubsub()` and
13456        // `is_store()` return `false`, so the shape-→-target-slot
13457        // dispatch (endpoint vs subject vs slot) is unambiguous.
13458        // Drift (e.g. a future `"kv:"` moved into the HTTP set
13459        // without removal from the store set) would silently route
13460        // one prefix to two arms and the first-matching-arm order
13461        // becomes load-bearing — this pin surfaces it as a build
13462        // error instead.
13463        for prefix in WIT_HTTP_SHAPE_PREFIXES {
13464            let sample = format!("{prefix}x");
13465            assert!(wit_shape_is_http(&sample));
13466            assert!(!wit_shape_is_pubsub(&sample));
13467            assert!(!wit_shape_is_store(&sample));
13468        }
13469        for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
13470            let sample = format!("{prefix}x");
13471            assert!(!wit_shape_is_http(&sample));
13472            assert!(wit_shape_is_pubsub(&sample));
13473            assert!(!wit_shape_is_store(&sample));
13474        }
13475        for prefix in WIT_STORE_SHAPE_PREFIXES {
13476            let sample = format!("{prefix}x");
13477            assert!(!wit_shape_is_http(&sample));
13478            assert!(!wit_shape_is_pubsub(&sample));
13479            assert!(wit_shape_is_store(&sample));
13480        }
13481    }
13482
13483    #[test]
13484    fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
13485        // Positive pin: [`wit_shape_matches`] is exactly the
13486        // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
13487        // parameterized on the accept-set. Two-prefix accept-set,
13488        // one-prefix accept-set, and empty accept-set (which must
13489        // reject everything, including the empty string — an empty
13490        // `any()` fold returns `false`) all pinned so a future
13491        // reimplementation that swaps `starts_with` for `contains`,
13492        // `==`, or a case-folded comparator surfaces at unit-test
13493        // time.
13494        let two = &["wasi:http/", "http:"];
13495        assert!(wit_shape_matches("wasi:http/proxy", two));
13496        assert!(wit_shape_matches("http:incoming", two));
13497        assert!(!wit_shape_matches("wasi:keyvalue/store", two));
13498
13499        let one = &["nats:"];
13500        assert!(wit_shape_matches("nats:pub-sub", one));
13501        assert!(!wit_shape_matches("kafka:topic", one));
13502
13503        // Empty accept-set matches nothing — the identity element
13504        // for the disjunctive `any()` fold across the prefix set.
13505        // Reachable via a future `wit_shape_is_<name>` const paired
13506        // to a still-empty prefix table on a nascent shape-arm draft.
13507        let empty: &[&str] = &[];
13508        assert!(!wit_shape_matches("wasi:http/proxy", empty));
13509        assert!(!wit_shape_matches("", empty));
13510
13511        // starts_with, not contains: a prefix embedded mid-string
13512        // never matches. Pins the routing invariant [`WitContract::target`]
13513        // relies on (an authored `:wit "custom:wasi:http/"` string
13514        // does not silently route through the HTTP arm just because
13515        // it happens to contain the canonical HTTP prefix).
13516        assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
13517    }
13518
13519    #[test]
13520    fn wit_shape_predicates_delegate_to_wit_shape_matches() {
13521        // Equivalence pin: each per-shape predicate is exactly
13522        // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
13523        // every canonical prefix + the empty string + one negative
13524        // sample against every peer so a future predicate that grew
13525        // its own inline `iter().any(starts_with)` (rather than
13526        // delegating through the lifted combinator) drifts loudly here
13527        // — the peer-const table's contents must agree with the
13528        // predicate's accept-set by construction.
13529        let samples = [
13530            String::new(),
13531            "wasi:http/proxy".to_string(),
13532            "http:incoming".to_string(),
13533            "nats:pub-sub".to_string(),
13534            "kafka:topic".to_string(),
13535            "wasi:keyvalue/store".to_string(),
13536            "kv:cache/session".to_string(),
13537            "custom-shape".to_string(),
13538            "WASI:HTTP/proxy".to_string(),
13539        ];
13540        for wit in &samples {
13541            assert_eq!(
13542                wit_shape_is_http(wit),
13543                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
13544                "wit_shape_is_http drifted from combinator on {wit:?}",
13545            );
13546            assert_eq!(
13547                wit_shape_is_pubsub(wit),
13548                wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
13549                "wit_shape_is_pubsub drifted from combinator on {wit:?}",
13550            );
13551            assert_eq!(
13552                wit_shape_is_store(wit),
13553                wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
13554                "wit_shape_is_store drifted from combinator on {wit:?}",
13555            );
13556        }
13557    }
13558
13559    #[test]
13560    fn wit_contract_shape_methods_delegate_to_free_functions() {
13561        // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
13562        // `is_store` are `&self` conveniences on top of the free
13563        // functions — for every canonical prefix the method's return
13564        // matches its free-function peer. Sweeps the union of the
13565        // three prefix sets so a future method that grew its own
13566        // inline prefix logic (rather than delegating) drifts loudly
13567        // here on the first prefix the free function accepts and the
13568        // method doesn't.
13569        for shape_set in [
13570            WIT_HTTP_SHAPE_PREFIXES,
13571            WIT_PUBSUB_SHAPE_PREFIXES,
13572            WIT_STORE_SHAPE_PREFIXES,
13573        ] {
13574            for prefix in shape_set {
13575                let c = WitContract {
13576                    de: "cart".into(),
13577                    para: "catalog".into(),
13578                    wit: format!("{prefix}x"),
13579                    endpoint: None,
13580                    subject: None,
13581                    slot: None,
13582                };
13583                assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
13584                assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
13585                assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
13586                assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
13587            }
13588        }
13589        // Capability-arm delegation sweep: two representative
13590        // Capability-shaped `:wit` values (a bare non-prefix-matching
13591        // WIT world, the deliberately-shaped empty string
13592        // [`WitContract::is_capability`]'s docstring calls out as
13593        // syntactically Capability). Extends the free-function
13594        // delegation pin onto the fourth arm so a future
13595        // [`WitContract::is_capability`] rewrite that grew an inline
13596        // prefix-set scan (rather than delegating through
13597        // [`wit_shape_is_capability`]) drifts loudly here on the first
13598        // Capability-shaped sample.
13599        for wit in ["custom:capability-only", ""] {
13600            let c = WitContract {
13601                de: "cart".into(),
13602                para: "catalog".into(),
13603                wit: wit.into(),
13604                endpoint: None,
13605                subject: None,
13606                slot: None,
13607            };
13608            assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
13609        }
13610    }
13611
13612    #[test]
13613    fn wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis() {
13614        // 4-way partition-witness pin on the raw `&str` axis: for every
13615        // canonical prefix in the three payload-arm accept-sets,
13616        // exactly one of the four [`wit_shape_is_http`] /
13617        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
13618        // [`wit_shape_is_capability`] free functions returns `true` and
13619        // the other three return `false` — the four-arm partition
13620        // witness that locks the free-function WIT-shape-classifier
13621        // family into a partition of the `:contratos :wit` axis
13622        // load-bearing. Peer of the sibling [`WitContract`]-surface
13623        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
13624        // partition pin — extends the discipline onto the raw `&str`
13625        // axis so any future arm addition (a hypothetical
13626        // `wasi:sockets/*` transport-layer shape, an `oci:*`
13627        // capability-import carrier per the sibling
13628        // [`wit_shape_matches`] docstring's trajectory bullet) that
13629        // landed on one of the payload-arm free functions without
13630        // shrinking [`wit_shape_is_capability`]'s accept-set surfaces
13631        // here as two arms returning `true` simultaneously at
13632        // caixa-core build time rather than a silent per-consumer
13633        // misclassification at renderer emit time.
13634        for shape_set in [
13635            WIT_HTTP_SHAPE_PREFIXES,
13636            WIT_PUBSUB_SHAPE_PREFIXES,
13637            WIT_STORE_SHAPE_PREFIXES,
13638        ] {
13639            for prefix in shape_set {
13640                let wit = format!("{prefix}x");
13641                let hits = [
13642                    wit_shape_is_http(&wit),
13643                    wit_shape_is_pubsub(&wit),
13644                    wit_shape_is_store(&wit),
13645                    wit_shape_is_capability(&wit),
13646                ]
13647                .iter()
13648                .filter(|&&b| b)
13649                .count();
13650                assert_eq!(
13651                    hits,
13652                    1,
13653                    "raw-&str WIT-shape 4-way predicate partition must \
13654                     admit exactly one arm per canonical prefix; got {hits} \
13655                     hits at wit={wit:?} (is_http={}, is_pubsub={}, is_store={}, \
13656                     is_capability={})",
13657                    wit_shape_is_http(&wit),
13658                    wit_shape_is_pubsub(&wit),
13659                    wit_shape_is_store(&wit),
13660                    wit_shape_is_capability(&wit),
13661                );
13662            }
13663        }
13664        // Capability-arm sweep on the raw `&str` axis: two
13665        // representative Capability-shaped `:wit` values (a bare non-
13666        // prefix-matching WIT world, the deliberately-shaped empty
13667        // string the pure classifier still admits per
13668        // [`wit_shape_is_capability`]'s docstring). Both must land on
13669        // the fourth arm exclusively so the partition witness holds
13670        // across the full 4-arm closure on the raw `&str` axis.
13671        for wit in ["custom:capability-only", ""] {
13672            let hits = [
13673                wit_shape_is_http(wit),
13674                wit_shape_is_pubsub(wit),
13675                wit_shape_is_store(wit),
13676                wit_shape_is_capability(wit),
13677            ]
13678            .iter()
13679            .filter(|&&b| b)
13680            .count();
13681            assert_eq!(
13682                hits, 1,
13683                "raw-&str WIT-shape 4-way predicate partition must \
13684                 admit exactly one arm on Capability-shaped wit={wit:?}"
13685            );
13686            assert!(
13687                wit_shape_is_capability(wit),
13688                "wit={wit:?} must project onto the Capability arm on the raw-&str axis"
13689            );
13690        }
13691    }
13692
13693    #[test]
13694    fn wit_shape_is_capability_composes_through_payload_arm_predicate_negation() {
13695        // Composition-witness pin: [`wit_shape_is_capability`] is the
13696        // exact-inverse disjunction of the sibling payload-arm free-
13697        // function trio [`wit_shape_is_http`] / [`wit_shape_is_pubsub`]
13698        // / [`wit_shape_is_store`]. A future reimplementation that
13699        // grew its own prefix-set scan (e.g. inlining a fourth
13700        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does
13701        // not own today) rather than delegating to the sibling trio
13702        // would drift loudly here — the composition contract binds the
13703        // fourth-arm free-function predicate to the exact-inverse of
13704        // the three payload-arm free-function predicates, so any
13705        // rebrand of any prefix-set const flows through
13706        // [`wit_shape_is_capability`] by construction without a
13707        // coordinated per-consumer rewrite. Peer of the sibling
13708        // [`WitContract`]-surface
13709        // [`wit_contract_is_capability_composes_through_shape_predicate_negation`]
13710        // composition pin — extends the discipline onto the raw
13711        // `&str` axis.
13712        let mut cases: Vec<String> = Vec::new();
13713        for shape_set in [
13714            WIT_HTTP_SHAPE_PREFIXES,
13715            WIT_PUBSUB_SHAPE_PREFIXES,
13716            WIT_STORE_SHAPE_PREFIXES,
13717        ] {
13718            for prefix in shape_set {
13719                cases.push(format!("{prefix}x"));
13720            }
13721        }
13722        cases.push("custom:capability-only".to_string());
13723        cases.push(String::new());
13724        for wit in cases {
13725            assert_eq!(
13726                wit_shape_is_capability(&wit),
13727                !wit_shape_is_http(&wit) && !wit_shape_is_pubsub(&wit) && !wit_shape_is_store(&wit),
13728                "wit_shape_is_capability must equal \
13729                 !wit_shape_is_http() && !wit_shape_is_pubsub() && !wit_shape_is_store() \
13730                 at wit={wit:?}"
13731            );
13732        }
13733    }
13734
13735    #[test]
13736    fn wit_shape_classifier_family_is_const_fn() {
13737        // Fail-before-pass-after pin on the 4-arm free-function WIT-
13738        // shape classifier family's `const`-eval posture. Each of the
13739        // four peer classifiers ([`wit_shape_is_http`] /
13740        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
13741        // [`wit_shape_is_capability`]) and the underlying combinator
13742        // [`wit_shape_matches`] must be `pub const fn` — any future
13743        // accidental downgrade to non-`const` fails the `const fn`
13744        // wrappers below at caixa-core build time with E0015
13745        // (`cannot call non-const function`), strictly stronger than
13746        // a runtime `assert!` and strictly stronger than the module-
13747        // scope `const _: () = assert!(…)` pins immediately after the
13748        // classifier declarations (those anchor specific accept-set
13749        // truth-table entries; this pin anchors the `const` posture
13750        // itself via `const fn` wrappers that are only well-formed
13751        // when the callee is itself `const fn`).
13752        //
13753        // Verified fail-before-pass-after by locally reverting
13754        // `pub const fn` → `pub fn` on each classifier and observing
13755        // E0015 at every corresponding wrapper call site (build
13756        // error, no test-time surface), then restoring `pub const fn`
13757        // and observing the pin pass at test time. Peer of the
13758        // sibling M3
13759        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
13760        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
13761        // M2
13762        // [`child_spec_restart_accessor_is_const_fn`] /
13763        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
13764        // and M3
13765        // [`placement_estrategia_accessor_is_const_fn`] /
13766        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
13767        // sibling `const`-eval-surface-pass axes.
13768        const fn matches_via_const_fn(wit: &str, prefixes: &[&str]) -> bool {
13769            wit_shape_matches(wit, prefixes)
13770        }
13771        const fn http_via_const_fn(wit: &str) -> bool {
13772            wit_shape_is_http(wit)
13773        }
13774        const fn pubsub_via_const_fn(wit: &str) -> bool {
13775            wit_shape_is_pubsub(wit)
13776        }
13777        const fn store_via_const_fn(wit: &str) -> bool {
13778            wit_shape_is_store(wit)
13779        }
13780        const fn capability_via_const_fn(wit: &str) -> bool {
13781            wit_shape_is_capability(wit)
13782        }
13783        // Sweep one canonical accept-set sample per arm plus the
13784        // payload-less/empty capability samples, asserting the
13785        // wrapper and direct dispatches agree byte-for-byte across
13786        // the closed 4-arm partition.
13787        let cases: [(&str, bool, bool, bool, bool); 6] = [
13788            ("wasi:http/proxy", true, false, false, false),
13789            ("http:incoming", true, false, false, false),
13790            ("nats:events", false, true, false, false),
13791            ("kafka:topic", false, true, false, false),
13792            ("wasi:keyvalue/store", false, false, true, false),
13793            ("kv:cache", false, false, true, false),
13794        ];
13795        for (wit, is_http, is_pubsub, is_store, _is_capability) in cases {
13796            assert_eq!(
13797                matches_via_const_fn(wit, WIT_HTTP_SHAPE_PREFIXES),
13798                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
13799                "wit_shape_matches const fn wrapper disagrees at wit={wit:?}",
13800            );
13801            assert_eq!(http_via_const_fn(wit), wit_shape_is_http(wit));
13802            assert_eq!(pubsub_via_const_fn(wit), wit_shape_is_pubsub(wit));
13803            assert_eq!(store_via_const_fn(wit), wit_shape_is_store(wit));
13804            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
13805            assert_eq!(wit_shape_is_http(wit), is_http);
13806            assert_eq!(wit_shape_is_pubsub(wit), is_pubsub);
13807            assert_eq!(wit_shape_is_store(wit), is_store);
13808        }
13809        // Payload-less capability arm (the 4th partition arm).
13810        let capability_samples: [&str; 3] =
13811            ["wasi:filesystem/preopens", "custom:capability-only", ""];
13812        for wit in capability_samples {
13813            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
13814            assert!(wit_shape_is_capability(wit));
13815            assert!(!wit_shape_is_http(wit));
13816            assert!(!wit_shape_is_pubsub(wit));
13817            assert!(!wit_shape_is_store(wit));
13818        }
13819    }
13820
13821    #[test]
13822    fn wit_shape_matches_composes_through_bytes_starts_with_across_boundary_lengths() {
13823        // Composition-witness pin: [`wit_shape_matches`] agrees with
13824        // the reference `prefixes.iter().any(|p| wit.starts_with(p))`
13825        // dispatch (the prior non-`const` implementation) across
13826        // boundary lengths — empty `wit`, empty prefix, one-byte
13827        // slack, prefix longer than `wit`, one-byte trailing slack.
13828        // The rewrite to a byte-level manual starts_with loop (the
13829        // enabler for the `pub const fn` posture) must not change any
13830        // truth-table entry on the canonical accept-set — this pin
13831        // sweeps a targeted boundary corpus and asserts byte-for-byte
13832        // agreement, locking the const-fn rewrite's semantics against
13833        // the prior iterator body by construction.
13834        let prefixes = &["wasi:http/", "http:"][..];
13835        let cases: [(&str, bool); 12] = [
13836            ("wasi:http/proxy", true),
13837            ("wasi:http/", true), // exact-length match on prefix
13838            ("wasi:http", false), // one byte short
13839            ("http:", true),
13840            ("http:incoming", true),
13841            ("http", false), // one byte short
13842            ("", false),
13843            ("wasi:https/proxy", false),
13844            ("nats:events", false),
13845            ("HTTPS:", false), // uppercase — no case-fold in classifier
13846            ("wasi:HTTP/proxy", false),
13847            ("wasi:http", false),
13848        ];
13849        for (wit, expected) in cases {
13850            assert_eq!(
13851                wit_shape_matches(wit, prefixes),
13852                expected,
13853                "wit_shape_matches disagrees with reference at wit={wit:?}",
13854            );
13855            // Byte-equal to the iterator body it replaced.
13856            let via_iter = prefixes.iter().any(|p| wit.starts_with(p));
13857            assert_eq!(
13858                wit_shape_matches(wit, prefixes),
13859                via_iter,
13860                "wit_shape_matches must byte-equal iter().any(starts_with) at wit={wit:?}",
13861            );
13862        }
13863        // Empty prefix set → always false regardless of `wit`.
13864        let empty: &[&str] = &[];
13865        assert!(!wit_shape_matches("", empty));
13866        assert!(!wit_shape_matches("wasi:http/proxy", empty));
13867        // Empty prefix inside a non-empty set → always true (every
13868        // string starts with the empty string, matching the
13869        // iterator body's semantics on `str::starts_with("")`).
13870        let contains_empty: &[&str] = &["nats:", ""];
13871        assert!(wit_shape_matches("", contains_empty));
13872        assert!(wit_shape_matches("wasi:http/proxy", contains_empty));
13873    }
13874
13875    #[test]
13876    fn wit_contract_is_capability_partitions_the_wit_shape_space() {
13877        // 4-way partition-witness pin: for every canonical prefix in
13878        // the payload-arm accept-sets, exactly one of the four
13879        // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
13880        // [`WitContract::is_store`] / [`WitContract::is_capability`]
13881        // predicates returns `true` and the other three return `false`
13882        // — the four-arm partition witness that locks the substrate's
13883        // WIT-shape-space closure on the pre-projection axis load-
13884        // bearing. A future arm addition (a hypothetical fourth
13885        // payload-shape prefix set, a `wasi:sockets/*` transport-layer
13886        // shape) that landed on one of the payload-arm predicates
13887        // without shrinking [`WitContract::is_capability`]'s accept-set
13888        // would surface here as two arms returning `true` simultaneously
13889        // — a partition-witness break the pin catches at caixa-core
13890        // build time rather than a silent per-consumer misclassification
13891        // at renderer emit time. Peer of the sibling `WitTarget`-side
13892        // [`tests::wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`]
13893        // partition-witness pin on the post-projection payload-scalar
13894        // arm-set — extends the discipline onto the pre-projection
13895        // 4-arm shape-space.
13896        for shape_set in [
13897            WIT_HTTP_SHAPE_PREFIXES,
13898            WIT_PUBSUB_SHAPE_PREFIXES,
13899            WIT_STORE_SHAPE_PREFIXES,
13900        ] {
13901            for prefix in shape_set {
13902                let c = WitContract {
13903                    de: "cart".into(),
13904                    para: "catalog".into(),
13905                    wit: format!("{prefix}x"),
13906                    endpoint: None,
13907                    subject: None,
13908                    slot: None,
13909                };
13910                let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
13911                    .iter()
13912                    .filter(|&&b| b)
13913                    .count();
13914                assert_eq!(
13915                    hits,
13916                    1,
13917                    "WitContract WIT-shape 4-way predicate partition must \
13918                     admit exactly one arm per canonical prefix; got {hits} \
13919                     hits at wit={:?} (is_http={}, is_pubsub={}, is_store={}, \
13920                     is_capability={})",
13921                    c.wit,
13922                    c.is_http(),
13923                    c.is_pubsub(),
13924                    c.is_store(),
13925                    c.is_capability(),
13926                );
13927            }
13928        }
13929        // Capability-arm sweep: two representative capability shapes
13930        // (a bare WIT world outside the three payload-arm prefix sets,
13931        // and the deliberately-shaped empty string that
13932        // [`crate::render::is_wit_world_ref`] rejects at
13933        // [`WitContract::target`] time but which the pure classifier
13934        // still admits — see the method docstring's "purely syntactic
13935        // classification" note). Both must land on the fourth arm
13936        // exclusively, so the partition witness holds across the full
13937        // 4-arm closure.
13938        for wit in ["custom:capability-only", ""] {
13939            let c = WitContract {
13940                de: "cart".into(),
13941                para: "catalog".into(),
13942                wit: wit.into(),
13943                endpoint: None,
13944                subject: None,
13945                slot: None,
13946            };
13947            let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
13948                .iter()
13949                .filter(|&&b| b)
13950                .count();
13951            assert_eq!(
13952                hits, 1,
13953                "WitContract WIT-shape 4-way predicate partition must \
13954                 admit exactly one arm on Capability-shaped wit={wit:?}"
13955            );
13956            assert!(
13957                c.is_capability(),
13958                "wit={wit:?} must project onto the Capability arm"
13959            );
13960        }
13961    }
13962
13963    #[test]
13964    fn wit_contract_is_capability_composes_through_shape_predicate_negation() {
13965        // Composition-witness pin: [`WitContract::is_capability`] is the
13966        // exact-inverse disjunction of the sibling payload-arm predicate
13967        // trio [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
13968        // [`WitContract::is_store`]. A future reimplementation that
13969        // grew its own prefix-set scan (e.g. inlining a fourth
13970        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does not
13971        // own today) rather than delegating to the sibling trio would
13972        // drift loudly here — the composition contract binds the
13973        // fourth-arm predicate to the exact-inverse of the three
13974        // payload-arm predicates, so any rebrand of any prefix-set const
13975        // flows through this method by construction without a
13976        // coordinated per-consumer rewrite. Sweeps the union of the
13977        // three payload-arm prefix sets plus two Capability-shaped
13978        // shapes (a bare non-prefix-matching WIT world, the deliberately-
13979        // empty string the pure classifier still admits per the method
13980        // docstring's "purely syntactic classification" note).
13981        let mut cases: Vec<String> = Vec::new();
13982        for shape_set in [
13983            WIT_HTTP_SHAPE_PREFIXES,
13984            WIT_PUBSUB_SHAPE_PREFIXES,
13985            WIT_STORE_SHAPE_PREFIXES,
13986        ] {
13987            for prefix in shape_set {
13988                cases.push(format!("{prefix}x"));
13989            }
13990        }
13991        cases.push("custom:capability-only".to_string());
13992        cases.push(String::new());
13993        for wit in cases {
13994            let c = WitContract {
13995                de: "cart".into(),
13996                para: "catalog".into(),
13997                wit: wit.clone(),
13998                endpoint: None,
13999                subject: None,
14000                slot: None,
14001            };
14002            assert_eq!(
14003                c.is_capability(),
14004                !c.is_http() && !c.is_pubsub() && !c.is_store(),
14005                "WitContract::is_capability must equal \
14006                 !is_http() && !is_pubsub() && !is_store() at wit={wit:?}"
14007            );
14008        }
14009    }
14010
14011    #[test]
14012    fn wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant() {
14013        // Cross-projection-witness pin: whenever [`WitContract::target`]
14014        // succeeds, the pre-projection [`WitContract::is_capability`]
14015        // classification agrees with the post-projection
14016        // [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
14017        // predicate — the 4-arm typed partition on the substrate's
14018        // typed-view surface (7f6aa98 IsVariant lift) and the peer 4-arm
14019        // partition on the pre-projection axis line up by construction.
14020        // A future divergence between the two axes (a peer
14021        // [`WitTarget`] variant addition that landed on the typed-view
14022        // surface without a peer prefix-set + [`WitContract`] predicate
14023        // extension, or vice versa) would surface here at caixa-core
14024        // build time rather than a silent per-consumer split at renderer
14025        // emit time. Peer of the sibling pre-/post-projection
14026        // agreement pins the payload-carrier trio
14027        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
14028        // [`WitContract::slot`] on pre-projection; [`WitTarget::http_endpoint`]
14029        // / [`WitTarget::pubsub_subject`] / [`WitTarget::store_slot`] on
14030        // post-projection — b11bb49 trio lift) already carry across the
14031        // three payload arms — this pin closes the pair on the fourth
14032        // payload-less arm.
14033        let http = WitContract {
14034            de: "cart".into(),
14035            para: "catalog".into(),
14036            wit: "wasi:http/proxy".into(),
14037            endpoint: Some("/x".into()),
14038            subject: None,
14039            slot: None,
14040        };
14041        assert!(!http.is_capability());
14042        assert!(!http.target().unwrap().is_capability());
14043
14044        let nats = WitContract {
14045            de: "cart".into(),
14046            para: "catalog".into(),
14047            wit: "nats:pub-sub".into(),
14048            endpoint: None,
14049            subject: Some("events.x".into()),
14050            slot: None,
14051        };
14052        assert!(!nats.is_capability());
14053        assert!(!nats.target().unwrap().is_capability());
14054
14055        let kv = WitContract {
14056            de: "cart".into(),
14057            para: "catalog".into(),
14058            wit: "wasi:keyvalue/store".into(),
14059            endpoint: None,
14060            subject: None,
14061            slot: Some("checkout/$orderId".into()),
14062        };
14063        assert!(!kv.is_capability());
14064        assert!(!kv.target().unwrap().is_capability());
14065
14066        let cap = WitContract {
14067            de: "cart".into(),
14068            para: "catalog".into(),
14069            wit: "custom:capability-only".into(),
14070            endpoint: None,
14071            subject: None,
14072            slot: None,
14073        };
14074        assert!(cap.is_capability());
14075        assert!(cap.target().unwrap().is_capability());
14076    }
14077
14078    #[test]
14079    fn wit_contract_pre_projection_accessor_family_is_const_fn() {
14080        // Fail-before-pass-after pin on the [`WitContract`] pre-
14081        // projection accessor family's `const`-eval-surface posture.
14082        // Each of the three per-`:contratos` byte-string scalar
14083        // accessors ([`WitContract::source`] / [`WitContract::destination`]
14084        // / [`WitContract::world_ref`], each projecting through
14085        // `String::as_str` — const-stable since Rust 1.87, well within
14086        // the workspace MSRV) and each of the four peer WIT-shape
14087        // predicates ([`WitContract::is_http`] /
14088        // [`WitContract::is_pubsub`] / [`WitContract::is_store`] /
14089        // [`WitContract::is_capability`], each composing
14090        // `wit_shape_is_<arm>(self.world_ref())` on the `pub const fn`
14091        // free-function classifier family the sibling
14092        // [`wit_shape_classifier_family_is_const_fn`] pin already
14093        // anchors on the raw `&str → bool` axis) must be `pub const fn`
14094        // — any future accidental downgrade to non-`const` fails the
14095        // `const fn` wrappers below at caixa-core build time with E0015
14096        // (`cannot call non-const function`), strictly stronger than a
14097        // runtime `assert!` and strictly stronger than a
14098        // module-scope `const _: () = assert!(…)` pin (which cannot be
14099        // formed on a `&WitContract` fixture because the type's
14100        // `String` / `Option<String>` carriers rule out `const`-context
14101        // construction; the `const fn` wrapper is the load-bearing
14102        // shape that side-steps the destructor-in-const restriction on
14103        // the value axis while still pinning the `const`-fn posture on
14104        // the callee).
14105        //
14106        // Peer of the sibling free-function classifier pin
14107        // [`wit_shape_classifier_family_is_const_fn`] (d46420c) on the
14108        // raw `&str → bool` axis — this pin extends the same
14109        // `const`-eval-surface discipline onto the peer method surface
14110        // that composes through those free-function classifiers, and
14111        // simultaneously onto the underlying per-`:contratos`
14112        // byte-string scalar-accessor trio each predicate reads
14113        // through. Sibling of the peer M3
14114        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
14115        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
14116        // M2
14117        // [`child_spec_restart_accessor_is_const_fn`] /
14118        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
14119        // and M3
14120        // [`placement_estrategia_accessor_is_const_fn`] /
14121        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
14122        // sibling `const`-eval-surface-pass axes.
14123        const fn source_via_const_fn(c: &WitContract) -> &str {
14124            c.source()
14125        }
14126        const fn destination_via_const_fn(c: &WitContract) -> &str {
14127            c.destination()
14128        }
14129        const fn world_ref_via_const_fn(c: &WitContract) -> &str {
14130            c.world_ref()
14131        }
14132        const fn is_http_via_const_fn(c: &WitContract) -> bool {
14133            c.is_http()
14134        }
14135        const fn is_pubsub_via_const_fn(c: &WitContract) -> bool {
14136            c.is_pubsub()
14137        }
14138        const fn is_store_via_const_fn(c: &WitContract) -> bool {
14139            c.is_store()
14140        }
14141        const fn is_capability_via_const_fn(c: &WitContract) -> bool {
14142            c.is_capability()
14143        }
14144        // Sweep one canonical accept-set sample per WIT-shape arm plus
14145        // a payload-less capability sample, asserting the wrapper and
14146        // direct dispatches agree byte-for-byte across the closed
14147        // 4-arm partition on both the scalar-accessor trio and the
14148        // WIT-shape-predicate family.
14149        for (wit, is_http, is_pubsub, is_store, is_capability) in [
14150            ("wasi:http/proxy", true, false, false, false),
14151            ("http:incoming", true, false, false, false),
14152            ("nats:events", false, true, false, false),
14153            ("kafka:topic", false, true, false, false),
14154            ("wasi:keyvalue/store", false, false, true, false),
14155            ("kv:cache", false, false, true, false),
14156            ("custom:capability-only", false, false, false, true),
14157            ("", false, false, false, true),
14158        ] {
14159            let c = WitContract {
14160                de: "cart".into(),
14161                para: "catalog".into(),
14162                wit: wit.into(),
14163                endpoint: None,
14164                subject: None,
14165                slot: None,
14166            };
14167            assert_eq!(source_via_const_fn(&c), c.source());
14168            assert_eq!(destination_via_const_fn(&c), c.destination());
14169            assert_eq!(world_ref_via_const_fn(&c), c.world_ref());
14170            assert_eq!(is_http_via_const_fn(&c), c.is_http());
14171            assert_eq!(is_pubsub_via_const_fn(&c), c.is_pubsub());
14172            assert_eq!(is_store_via_const_fn(&c), c.is_store());
14173            assert_eq!(is_capability_via_const_fn(&c), c.is_capability());
14174            assert_eq!(c.source(), "cart");
14175            assert_eq!(c.destination(), "catalog");
14176            assert_eq!(c.world_ref(), wit);
14177            assert_eq!(c.is_http(), is_http);
14178            assert_eq!(c.is_pubsub(), is_pubsub);
14179            assert_eq!(c.is_store(), is_store);
14180            assert_eq!(c.is_capability(), is_capability);
14181        }
14182    }
14183
14184    #[test]
14185    fn wit_contract_identity_projection_accessor_is_const_fn() {
14186        // Fail-before-pass-after pin on the [`WitContract::identity`]
14187        // six-arm composite-projection accessor's `const`-eval-surface
14188        // posture. The accessor projects the typed edge's six identity
14189        // arms (`:de` / `:para` / `:wit` / `:endpoint` / `:subject` /
14190        // `:slot`) as a borrowed [`ContratoIdentity<'_>`] six-tuple —
14191        // every callee is itself `pub const fn` ([`WitContract::source`]
14192        // / [`WitContract::destination`] / [`WitContract::world_ref`]
14193        // through `String::as_str`, const-stable since Rust 1.87;
14194        // [`WitContract::endpoint`] / [`WitContract::subject`] /
14195        // [`WitContract::slot`] through the sibling `match &self
14196        // .<field> { Some(s) => Some(s.as_str()), None => None }` shape
14197        // 0650f64 closed the const-eval surface on) and the tuple
14198        // constructor from borrowed-reference / `Option`-of-borrowed-
14199        // reference arms is trivially const. Any future accidental
14200        // downgrade fails the `identity_via_const_fn` wrapper at
14201        // caixa-core build time with E0015 (`cannot call non-const
14202        // method`), strictly stronger than a runtime `assert!` and
14203        // strictly stronger than a module-scope `const _: () =
14204        // assert!(…)` pin (which cannot be formed on a `&WitContract`
14205        // fixture because the type's `String` / `Option<String>`
14206        // carriers rule out `const`-context value construction; the
14207        // `const fn` wrapper is the load-bearing shape that side-steps
14208        // the destructor-in-const restriction on the value axis while
14209        // still pinning the `const`-fn posture on the callee — mirror
14210        // of the sibling
14211        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
14212        // pin's discipline verbatim on the peer scalar-accessor
14213        // surface).
14214        //
14215        // Peer of the sibling
14216        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
14217        // (279823b) pin on the six per-`:contratos` scalar-accessor
14218        // callees this composite-projection reads through — where that
14219        // pin anchors the const-eval surface at the six individual
14220        // scalar-accessor arms, this pin extends the same posture onto
14221        // the composite six-tuple projection every consumer that dedups
14222        // typed edges on the [`ContratoIdentity`] axis keys off (the
14223        // [`AplicacaoSpec::validate`]-side duplicate-`:contratos`
14224        // scanner + its BTreeMap dedup key; a future per-Aplicacao CR
14225        // materializer's per-edge identity-based admission webhook; a
14226        // future L7 policy-emitter that shards CNPs by identity-tuple
14227        // rather than by name). Same fail-before-pass-after wrapper
14228        // discipline as the peer M2 / M3 accessor-family pins on the
14229        // sibling `const`-eval-surface passes.
14230        const fn identity_via_const_fn(c: &WitContract) -> ContratoIdentity<'_> {
14231            c.identity()
14232        }
14233        // Sweep one canonical WIT-shape sample per payload-carrier arm
14234        // plus a payload-less capability sample so the pin exercises
14235        // both `Some(_)`-carrying and `None`-carrying arms on all three
14236        // `Option<String>` payload-carrier axes (`:endpoint` / `:subject`
14237        // / `:slot`) — every wrapper dispatch must agree byte-for-byte
14238        // with the direct method call on every arm of the closed WIT-
14239        // shape partition.
14240        for (wit, endpoint, subject, slot) in [
14241            ("wasi:http/proxy", Some("/checkout"), None, None),
14242            ("http:incoming", Some("/api"), None, None),
14243            ("nats:events", None, Some("orders.placed"), None),
14244            ("kafka:topic", None, Some("orders.stream"), None),
14245            ("wasi:keyvalue/store", None, None, Some("carts/{id}")),
14246            ("kv:cache", None, None, Some("session/{token}")),
14247            ("custom:capability-only", None, None, None),
14248        ] {
14249            let c = WitContract {
14250                de: "cart".into(),
14251                para: "catalog".into(),
14252                wit: wit.into(),
14253                endpoint: endpoint.map(str::to_string),
14254                subject: subject.map(str::to_string),
14255                slot: slot.map(str::to_string),
14256            };
14257            assert_eq!(identity_via_const_fn(&c), c.identity());
14258            assert_eq!(
14259                c.identity(),
14260                ("cart", "catalog", wit, endpoint, subject, slot,),
14261            );
14262        }
14263    }
14264
14265    #[test]
14266    fn m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn() {
14267        // Fail-before-pass-after pin on the four M3 mesh-slot
14268        // `String → &str` scalar accessors ([`Membro::nome`] /
14269        // [`Membro::versao_requirement`] on the per-`:membros` axis,
14270        // [`Entrada::hostname`] / [`Entrada::destination`] on the
14271        // per-`:entrada` axis) — each projects the typed slot's
14272        // [`String`] storage through the `pub const fn`
14273        // [`String::as_str`] (const-stable since Rust 1.87, well
14274        // within the workspace MSRV) and any future accidental
14275        // downgrade to non-`const` fails the corresponding
14276        // `<name>_via_const_fn` wrapper at caixa-core build time with
14277        // E0015 (`cannot call non-const method`), strictly stronger
14278        // than a runtime `assert!` and strictly stronger than a
14279        // module-scope `const _: () = assert!(…)` pin (which cannot
14280        // be formed on `&Membro` / `&Entrada` fixtures because the
14281        // types' `String` carriers rule out `const`-context value
14282        // construction; the `const fn` wrapper is the load-bearing
14283        // shape that side-steps the destructor-in-const restriction
14284        // on the value axis while still pinning the `const`-fn
14285        // posture on the callee — mirror of the sibling
14286        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
14287        // (279823b) pin on the per-`:contratos` axis). Peer of the
14288        // sibling per-M2/M3/universal-axis `String → &str` accessor
14289        // family pins on the sibling `const`-eval-surface passes
14290        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
14291        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
14292        // typed-newtype wrapper,
14293        // [`crate::supervisor::ChildSpec::nome`] /
14294        // [`crate::supervisor::ChildSpec::versao_requirement`] at the
14295        // M2 supervisor-tree axis,
14296        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
14297        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
14298        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
14299        // axis, and the sibling per-`:contratos`
14300        // [`WitContract::source`] / [`WitContract::destination`] /
14301        // [`WitContract::world_ref`] trio at 279823b).
14302        const fn membro_nome_via_const_fn(m: &Membro) -> &str {
14303            m.nome()
14304        }
14305        const fn membro_versao_via_const_fn(m: &Membro) -> &str {
14306            m.versao_requirement()
14307        }
14308        const fn entrada_hostname_via_const_fn(e: &Entrada) -> &str {
14309            e.hostname()
14310        }
14311        const fn entrada_destination_via_const_fn(e: &Entrada) -> &str {
14312            e.destination()
14313        }
14314        for (caixa, versao) in [
14315            ("cart", "^0.1"),
14316            ("catalog-v2", "~0.2.3"),
14317            ("checkout", "*"),
14318        ] {
14319            let m = Membro {
14320                caixa: caixa.into(),
14321                versao: versao.into(),
14322            };
14323            assert_eq!(membro_nome_via_const_fn(&m), m.nome());
14324            assert_eq!(membro_versao_via_const_fn(&m), m.versao_requirement());
14325            assert_eq!(m.nome(), caixa);
14326            assert_eq!(m.versao_requirement(), versao);
14327        }
14328        for (host, para) in [
14329            ("cart.example.com", "cart"),
14330            ("api.checkout.io", "checkout"),
14331        ] {
14332            let e = Entrada {
14333                host: host.into(),
14334                para: para.into(),
14335                paths: vec![],
14336                port: DEFAULT_SERVICO_PORT,
14337            };
14338            assert_eq!(entrada_hostname_via_const_fn(&e), e.hostname());
14339            assert_eq!(entrada_destination_via_const_fn(&e), e.destination());
14340            assert_eq!(e.hostname(), host);
14341            assert_eq!(e.destination(), para);
14342        }
14343    }
14344
14345    #[test]
14346    fn m3_option_string_scalar_accessor_family_is_const_fn() {
14347        // Fail-before-pass-after pin on the five M3 mesh-slot
14348        // `Option<String> → Option<&str>` scalar accessors
14349        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
14350        // [`WitContract::slot`] on the per-`:contratos` HTTP /
14351        // pub-sub / key-value payload-carrier trio,
14352        // [`Placement::shard_key`] / [`Placement::affinity`] on the
14353        // per-`:placement` Akka-sharding-key + Adaptive-compression-
14354        // hint pair). Each accessor destructures the typed slot's
14355        // `Option<String>` storage through the `match &self.<field> {
14356        // Some(s) => Some(s.as_str()), None => None }` shape —
14357        // routing through [`String::as_str`] (const-stable since Rust
14358        // 1.87, well within the workspace MSRV) rather than the
14359        // non-const [`Option::as_deref`] the pre-lift bodies carried
14360        // — and any future accidental downgrade to non-`const` fails
14361        // the corresponding `<name>_via_const_fn` wrapper at
14362        // caixa-core build time with E0015 (`cannot call non-const
14363        // method`), strictly stronger than a runtime `assert!` and
14364        // strictly stronger than a module-scope `const _: () =
14365        // assert!(…)` pin (which cannot be formed on `&WitContract`
14366        // / `&Placement` fixtures because the types' `String` /
14367        // `Option<String>` carriers rule out `const`-context value
14368        // construction; the `const fn` wrapper is the load-bearing
14369        // shape that side-steps the destructor-in-const restriction
14370        // on the value axis while still pinning the `const`-fn
14371        // posture on the callee — mirror of the sibling
14372        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
14373        // (279823b) and
14374        // [`m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn`]
14375        // (29c5d7e) pins on the peer `String → &str` axes at the same
14376        // structs).
14377        //
14378        // Peer of the sibling per-`Caixa` `Option<String> →
14379        // Option<&str>` accessor family pin
14380        // [`crate::manifest::tests::caixa_option_string_scalar_accessor_family_is_const_fn`]
14381        // on the top-level manifest's optional universal-axis surface
14382        // (`:licenca` / `:repositorio` / `:descricao` / `:edicao` /
14383        // `:restart-window`).
14384        const fn wit_endpoint_via_const_fn(w: &WitContract) -> Option<&str> {
14385            w.endpoint()
14386        }
14387        const fn wit_subject_via_const_fn(w: &WitContract) -> Option<&str> {
14388            w.subject()
14389        }
14390        const fn wit_slot_via_const_fn(w: &WitContract) -> Option<&str> {
14391            w.slot()
14392        }
14393        const fn placement_shard_key_via_const_fn(p: &Placement) -> Option<&str> {
14394            p.shard_key()
14395        }
14396        const fn placement_affinity_via_const_fn(p: &Placement) -> Option<&str> {
14397            p.affinity()
14398        }
14399        // Sweep every closed shape-arm partition on the
14400        // per-`:contratos` payload-carrier trio: HTTP (`:endpoint`
14401        // Some, sibling pair None), pub-sub (`:subject` Some, sibling
14402        // pair None), key-value (`:slot` Some, sibling pair None),
14403        // and Capability (all three None) so each accessor's
14404        // Some/None arm carries a pin through the const dispatch.
14405        for (wit, endpoint, subject, slot) in [
14406            ("wasi:http/proxy", Some("/api"), None, None),
14407            ("nats:pub-sub", None, Some("orders.paid"), None),
14408            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
14409            ("custom:capability-only", None, None, None),
14410        ] {
14411            let c = WitContract {
14412                de: "cart".into(),
14413                para: "catalog".into(),
14414                wit: wit.into(),
14415                endpoint: endpoint.map(str::to_string),
14416                subject: subject.map(str::to_string),
14417                slot: slot.map(str::to_string),
14418            };
14419            assert_eq!(wit_endpoint_via_const_fn(&c), c.endpoint());
14420            assert_eq!(wit_subject_via_const_fn(&c), c.subject());
14421            assert_eq!(wit_slot_via_const_fn(&c), c.slot());
14422            assert_eq!(c.endpoint(), endpoint);
14423            assert_eq!(c.subject(), subject);
14424            assert_eq!(c.slot(), slot);
14425        }
14426        // Sweep both `Some`/`None` arms on each per-`:placement`
14427        // optional-scalar so the shard-key + affinity pair carries a
14428        // const-dispatch pin on both arms.
14429        for (shard_key, affinity) in [
14430            (Some("tenantId"), Some("data-locality")),
14431            (Some("$tenantId"), None),
14432            (None, Some("low-latency")),
14433            (None, None),
14434        ] {
14435            let p = Placement {
14436                estrategia: PlacementStrategy::default(),
14437                clusters: vec![],
14438                affinity: affinity.map(str::to_string),
14439                shard_key: shard_key.map(str::to_string),
14440            };
14441            assert_eq!(placement_shard_key_via_const_fn(&p), p.shard_key());
14442            assert_eq!(placement_affinity_via_const_fn(&p), p.affinity());
14443            assert_eq!(p.shard_key(), shard_key);
14444            assert_eq!(p.affinity(), affinity);
14445        }
14446    }
14447
14448    #[test]
14449    fn m3_placement_entrada_slice_return_accessor_pair_is_const_fn() {
14450        // Fail-before-pass-after pin on the two M3-mesh-slot inner-
14451        // composite `Vec → &[String]` slice-return accessors on
14452        // [`Placement::clusters`] and [`Entrada::paths`]. Each
14453        // destructures the typed slot's `Vec<String>` storage through
14454        // the `pub const fn` [`Vec::as_slice`] (const-stable since Rust
14455        // 1.66, well within the workspace MSRV) — any future accidental
14456        // downgrade to non-`const` fails the corresponding
14457        // `<name>_via_const_fn` wrapper at caixa-core build time with
14458        // E0015 (`cannot call non-const method`), strictly stronger
14459        // than a runtime `assert!`. Sibling of the peer
14460        // [`m3_aplicacao_spec_reference_return_accessor_family_is_const_fn`]
14461        // pin on the outer-`AplicacaoSpec` reference-return family
14462        // (`:membros` / `:contratos` slice-return + `:politicas` /
14463        // `:placement` / `:entrada` composite-reference), and of the
14464        // peer M2 slice-return axis pins
14465        // [`crate::supervisor::tests::supervisor_children_slice_return_accessor_is_const_fn`]
14466        // (on `SupervisorSpec::children`) and
14467        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
14468        // (on `UpgradeFromEntry::instructions`). Together the four
14469        // pins close the last unlifted reference-return accessor
14470        // family across the substrate primitive.
14471        const fn placement_clusters_via_const_fn(p: &Placement) -> &[String] {
14472            p.clusters()
14473        }
14474        const fn entrada_paths_via_const_fn(e: &Entrada) -> &[String] {
14475            e.paths()
14476        }
14477        // Sweep both the empty-Vec (no author-declared entries) and
14478        // the populated-Vec arms on every slice-return accessor so
14479        // each carries a const-dispatch pin on both arms.
14480        let p_empty = Placement {
14481            estrategia: PlacementStrategy::default(),
14482            clusters: vec![],
14483            affinity: None,
14484            shard_key: None,
14485        };
14486        let p_full = Placement {
14487            estrategia: PlacementStrategy::default(),
14488            clusters: vec!["prod-a".into(), "prod-b".into()],
14489            affinity: None,
14490            shard_key: None,
14491        };
14492        assert_eq!(
14493            placement_clusters_via_const_fn(&p_empty),
14494            p_empty.clusters()
14495        );
14496        assert_eq!(placement_clusters_via_const_fn(&p_full), p_full.clusters());
14497        assert!(p_empty.clusters().is_empty());
14498        assert_eq!(p_full.clusters(), &["prod-a", "prod-b"]);
14499        let e_empty = Entrada {
14500            host: "web.example.com".into(),
14501            para: "web".into(),
14502            paths: vec![],
14503            port: DEFAULT_SERVICO_PORT,
14504        };
14505        let e_full = Entrada {
14506            host: "web.example.com".into(),
14507            para: "web".into(),
14508            paths: vec!["/api".into(), "/health".into()],
14509            port: DEFAULT_SERVICO_PORT,
14510        };
14511        assert_eq!(entrada_paths_via_const_fn(&e_empty), e_empty.paths());
14512        assert_eq!(entrada_paths_via_const_fn(&e_full), e_full.paths());
14513        assert!(e_empty.paths().is_empty());
14514        assert_eq!(e_full.paths(), &["/api", "/health"]);
14515    }
14516
14517    #[test]
14518    fn m3_aplicacao_spec_reference_return_accessor_family_is_const_fn() {
14519        // Fail-before-pass-after pin on the five outer-`AplicacaoSpec`
14520        // reference-return accessors — the two `Vec → &[T]` slice-
14521        // return accessors on [`AplicacaoSpec::membros`] and
14522        // [`AplicacaoSpec::contratos`] (each routes through the
14523        // `pub const fn` [`Vec::as_slice`], const-stable since Rust
14524        // 1.66), the two `&Composite` composite-reference accessors
14525        // on [`AplicacaoSpec::politicas`] and
14526        // [`AplicacaoSpec::placement`] (each routes through a raw
14527        // `&self.<field>` borrow, trivially const), and the one
14528        // `Option<&Composite>` optional-composite-reference accessor
14529        // on [`AplicacaoSpec::entrada`] (routes through the
14530        // `pub const fn` [`Option::as_ref`], const-stable since Rust
14531        // 1.83). Any future accidental downgrade to non-`const` fails
14532        // the corresponding `<name>_via_const_fn` wrapper at caixa-
14533        // core build time with E0015 (`cannot call non-const
14534        // method`), strictly stronger than a runtime `assert!`.
14535        // Sibling of the peer inner-composite pin
14536        // [`m3_placement_entrada_slice_return_accessor_pair_is_const_fn`]
14537        // on the `Placement::clusters` + `Entrada::paths` slice-
14538        // return pair, and of the peer M2 axis pins on
14539        // [`crate::supervisor::SupervisorSpec::children`] and
14540        // [`crate::upgrade::UpgradeFromEntry::instructions`].
14541        const fn aplicacao_membros_via_const_fn(s: &AplicacaoSpec) -> &[Membro] {
14542            s.membros()
14543        }
14544        const fn aplicacao_contratos_via_const_fn(s: &AplicacaoSpec) -> &[WitContract] {
14545            s.contratos()
14546        }
14547        const fn aplicacao_politicas_via_const_fn(s: &AplicacaoSpec) -> &MeshPolicy {
14548            s.politicas()
14549        }
14550        const fn aplicacao_placement_via_const_fn(s: &AplicacaoSpec) -> &Placement {
14551            s.placement()
14552        }
14553        const fn aplicacao_entrada_via_const_fn(s: &AplicacaoSpec) -> Option<&Entrada> {
14554            s.entrada()
14555        }
14556        // Construct both a minimal "no :entrada" (internal-only
14557        // mesh) and a full "with :entrada" (external-gateway)
14558        // fixture so the family pins both the `None`-arm (author-
14559        // omitted `:entrada`) and the `Some`-arm (author-declared
14560        // `:entrada`) on the optional-composite axis.
14561        let membro = Membro {
14562            caixa: "web".into(),
14563            versao: "^0.1".into(),
14564        };
14565        let entrada_full = Entrada {
14566            host: "web.example.com".into(),
14567            para: "web".into(),
14568            paths: vec!["/api".into()],
14569            port: DEFAULT_SERVICO_PORT,
14570        };
14571        let internal_only = AplicacaoSpec {
14572            membros: vec![membro.clone()],
14573            contratos: vec![],
14574            politicas: MeshPolicy::default(),
14575            placement: Placement::default(),
14576            entrada: None,
14577        };
14578        let with_entrada = AplicacaoSpec {
14579            membros: vec![membro],
14580            contratos: vec![],
14581            politicas: MeshPolicy::default(),
14582            placement: Placement::default(),
14583            entrada: Some(entrada_full),
14584        };
14585        assert_eq!(
14586            aplicacao_membros_via_const_fn(&internal_only),
14587            internal_only.membros()
14588        );
14589        assert_eq!(
14590            aplicacao_membros_via_const_fn(&with_entrada),
14591            with_entrada.membros()
14592        );
14593        assert_eq!(
14594            aplicacao_contratos_via_const_fn(&internal_only),
14595            internal_only.contratos()
14596        );
14597        assert!(std::ptr::eq(
14598            aplicacao_politicas_via_const_fn(&internal_only),
14599            internal_only.politicas(),
14600        ));
14601        assert!(std::ptr::eq(
14602            aplicacao_placement_via_const_fn(&internal_only),
14603            internal_only.placement(),
14604        ));
14605        assert!(aplicacao_entrada_via_const_fn(&internal_only).is_none());
14606        match (
14607            aplicacao_entrada_via_const_fn(&with_entrada),
14608            with_entrada.entrada(),
14609        ) {
14610            (Some(a), Some(b)) => assert!(std::ptr::eq(a, b)),
14611            _ => panic!(
14612                "aplicacao_entrada_via_const_fn must agree with \
14613                 AplicacaoSpec::entrada on the Some-arm reference"
14614            ),
14615        }
14616    }
14617
14618    #[test]
14619    fn target_projected_returns_byte_equal_typed_view_across_all_four_arms() {
14620        // Load-bearing contract pin: on every canonical
14621        // `(:wit, :endpoint/:subject/:slot)` shape the substrate admits,
14622        // [`WitContract::target_projected`] returns byte-equal to
14623        // [`WitContract::target`]`().unwrap()` — the post-validation
14624        // projection accessor is a thin panicking wrapper over the
14625        // pre-validation validator, no extra work in the projection
14626        // path. Any future divergence (a validator-side normalization
14627        // the projection doesn't route through, an accessor-side
14628        // caching layer the validator doesn't populate) would surface
14629        // here at caixa-core build time rather than a silent per-consumer
14630        // split at renderer emit time. Sweeps the closed 4-arm
14631        // [`WitTarget`] partition ([`WitTarget::Http`] /
14632        // [`WitTarget::PubSub`] / [`WitTarget::Store`] /
14633        // [`WitTarget::Capability`]) so every arm carries a byte-equality
14634        // pin on the two-accessor pair.
14635        for (wit, endpoint, subject, slot) in [
14636            ("wasi:http/proxy", Some("/x"), None, None),
14637            ("nats:pub-sub", None, Some("events.x"), None),
14638            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
14639            ("custom:capability-only", None, None, None),
14640        ] {
14641            let c = WitContract {
14642                de: "cart".into(),
14643                para: "catalog".into(),
14644                wit: wit.into(),
14645                endpoint: endpoint.map(str::to_string),
14646                subject: subject.map(str::to_string),
14647                slot: slot.map(str::to_string),
14648            };
14649            assert_eq!(
14650                c.target_projected(),
14651                c.target().unwrap(),
14652                "target_projected must return byte-equal to target().unwrap() at wit={wit:?}"
14653            );
14654        }
14655    }
14656
14657    #[test]
14658    #[should_panic(expected = "validated by typed_view")]
14659    fn target_projected_panics_with_canonical_message_on_unvalidated_contract() {
14660        // Panic-path pin: [`WitContract::target_projected`] threads the
14661        // canonical [`WitContract::PROJECTED_INVARIANT_MSG`] byte-string
14662        // through its expect-panic when called on a contract whose
14663        // (`:wit`, payload) shape has not been crossed by
14664        // [`AplicacaoSpec::validate`] — a contract with a structurally-
14665        // invalid `:wit` (hyphen-for-colon typo) that would surface
14666        // [`AplicacaoError::ContratoWitInvalid`] at the validator gate.
14667        // A future rebrand on the panic-message axis would land at one
14668        // caixa-core edit on [`WitContract::PROJECTED_INVARIANT_MSG`]
14669        // and this pin's [`should_panic(expected = …)`] literal would
14670        // migrate alongside — the pin catches drift between the const
14671        // and the accessor's `expect(…)` call by construction.
14672        let c = WitContract {
14673            de: "cart".into(),
14674            para: "catalog".into(),
14675            // Hyphen-for-colon typo: `WitContract::target` returns
14676            // [`AplicacaoError::ContratoWitInvalid`] on this shape,
14677            // driving the [`WitContract::target_projected`] expect-panic.
14678            wit: "wasi-http/proxy".into(),
14679            endpoint: Some("/x".into()),
14680            subject: None,
14681            slot: None,
14682        };
14683        let _ = c.target_projected();
14684    }
14685
14686    #[test]
14687    fn target_projected_invariant_msg_matches_prior_inline_call_site_literal() {
14688        // Byte-equivalence pin: [`WitContract::PROJECTED_INVARIANT_MSG`]
14689        // carries the exact byte-string the two prior open-coded
14690        // `.target().expect("validated by typed_view")` production
14691        // consumers threaded through inline before this lift converged
14692        // them onto [`WitContract::target_projected`] — the caixa-mesh
14693        // per-`(:de, :para)` CNP L7 introspection branch at
14694        // `caixa-mesh/src/lib.rs:2825` and the caixa-feira `feira app
14695        // graph` per-`:contratos` payload-column printer at
14696        // `caixa-feira/src/cmd/app.rs:110`. Locks the panic-message
14697        // byte-string load-bearing so a well-meaning const-side rebrand
14698        // that didn't carry a matched pin migration would surface here
14699        // at caixa-core build time rather than a silent per-consumer
14700        // panic-message drift at cluster-apply time. Peer of the
14701        // sibling [`WitTarget::CAPABILITY_LABEL`] /
14702        // [`WitTarget::CAPABILITY_EXPECTED`] /
14703        // [`WitTarget::CAPABILITY_GRAPH_LABEL`] byte-equivalence pins on
14704        // the paired payload-less-arm scalar-const family.
14705        assert_eq!(
14706            WitContract::PROJECTED_INVARIANT_MSG,
14707            "validated by typed_view"
14708        );
14709    }
14710
14711    #[test]
14712    fn empty_wit_takes_precedence_over_invalid() {
14713        // Ordering pin: `EmptyWit` is the more self-locating
14714        // diagnostic on `""` and must lead — the value-shape gate is
14715        // only reached after the empty-check fires. Mirrors
14716        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
14717        // the peer payload axis.
14718        let mut s = three_member_spec();
14719        s.contratos.push(WitContract {
14720            de: "payment".into(),
14721            para: "catalog".into(),
14722            wit: String::new(),
14723            endpoint: None,
14724            subject: None,
14725            slot: None,
14726        });
14727        let err = s.validate().unwrap_err();
14728        assert!(
14729            matches!(err, AplicacaoError::EmptyWit { .. }),
14730            "got {err:?}"
14731        );
14732    }
14733
14734    #[test]
14735    fn wit_invalid_fires_before_payload_shape_arm() {
14736        // Ordering pin: a malformed `:wit` surfaces *its own*
14737        // diagnostic (which names the offending wit verbatim) before
14738        // any payload-field check — a contrato whose wit is
14739        // structurally invalid AND carries a wrong target field
14740        // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
14741        // because the dispatch on the wit is what decides which
14742        // payload field is "right" in the first place. Without this
14743        // ordering, the author would see "wrong target field" for a
14744        // wit that hasn't even been parsed, which doesn't name the
14745        // root cause.
14746        let mut s = three_member_spec();
14747        s.contratos.push(WitContract {
14748            de: "payment".into(),
14749            para: "catalog".into(),
14750            // Hyphen-for-colon typo + endpoint set: pre-gate this
14751            // raised `ContratoWrongTarget { expected: "none" }` (the
14752            // Capability arm rejecting the endpoint), masking the
14753            // real authoring mistake (the wit isn't `wasi:http/proxy`).
14754            wit: "wasi-http/proxy".into(),
14755            endpoint: Some("/x".into()),
14756            subject: None,
14757            slot: None,
14758        });
14759        let err = s.validate().unwrap_err();
14760        assert!(
14761            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
14762                if wit == "wasi-http/proxy"),
14763            "got {err:?}"
14764        );
14765    }
14766
14767    #[test]
14768    fn wit_invalid_diagnostic_carries_offending_wit() {
14769        // Diagnostic-shape pin — the offending `:wit` + `:de` +
14770        // `:para` + a non-empty reason flow through verbatim so the
14771        // author can grep their caixa.lisp for the offending contrato
14772        // block and fix it in one edit. Same shape as
14773        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
14774        let err = contrato_wit_err("WASI:HTTP/proxy");
14775        match err {
14776            AplicacaoError::ContratoWitInvalid {
14777                de,
14778                para,
14779                wit,
14780                reason,
14781            } => {
14782                assert_eq!(de, "payment");
14783                assert_eq!(para, "catalog");
14784                assert_eq!(wit, "WASI:HTTP/proxy");
14785                assert!(!reason.is_empty(), "reason field must be non-empty");
14786            }
14787            other => panic!("expected ContratoWitInvalid, got {other:?}"),
14788        }
14789    }
14790
14791    // ── :contratos :subject value-shape gate ─────────────────────────────
14792    //
14793    // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
14794    // suites on the peer payload axes. Until this gate landed
14795    // `WitContract::target()` only refused the empty string; a
14796    // structurally invalid subject silently passed validate and the
14797    // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
14798    // Subject'` on publish / subscribe, or as a silent message drop,
14799    // far from the source caixa.lisp. Every authoring footgun the
14800    // NATS server's subject parser would catch on admission now
14801    // becomes a caixa-build-time `ContratoSubjectInvalid` with the
14802    // offending `:subject` + `:de` + `:para` named verbatim. Same
14803    // diagnostic shape as `ContratoEndpointInvalid` /
14804    // `ContratoWitInvalid` on the peer payload axes; same shared
14805    // predicate (`crate::render::is_nats_subject`) ensures drift
14806    // between any two axes' rule enforcement is a build error at the
14807    // predicate, not piecemeal across renderers.
14808
14809    fn contrato_subject_err(subject: &str) -> AplicacaoError {
14810        // Fresh spec per call so the new contract doesn't collide on
14811        // identity with `three_member_spec`'s pre-existing entries.
14812        // The new edge uses `(payment, catalog)` — a pair the fixture
14813        // doesn't already declare — with `:wit "nats:pub-sub"` and the
14814        // varying `:subject`, so the subject-shape gate fires cleanly
14815        // after the wit-shape gate (which `"nats:pub-sub"` passes).
14816        let mut s = three_member_spec();
14817        s.contratos.push(WitContract {
14818            de: "payment".into(),
14819            para: "catalog".into(),
14820            wit: "nats:pub-sub".into(),
14821            endpoint: None,
14822            subject: Some(subject.into()),
14823            slot: None,
14824        });
14825        s.validate().unwrap_err()
14826    }
14827
14828    #[test]
14829    fn rejects_pubsub_contrato_subject_with_whitespace() {
14830        // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
14831        // landed at the NATS server as a malformed subject the parser
14832        // rejects with `-ERR 'Invalid Subject'`. Now caught at the
14833        // source caixa.lisp.
14834        let err = contrato_subject_err("foo bar");
14835        assert!(
14836            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14837                if subject == "foo bar" && reason.contains("whitespace")),
14838            "got {err:?}"
14839        );
14840    }
14841
14842    #[test]
14843    fn rejects_pubsub_contrato_subject_with_control_char() {
14844        let err = contrato_subject_err("foo\x01bar");
14845        assert!(
14846            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14847                if subject == "foo\x01bar" && reason.contains("control character")),
14848            "got {err:?}"
14849        );
14850    }
14851
14852    #[test]
14853    fn rejects_pubsub_contrato_subject_with_non_ascii() {
14854        // Un-percent-encoded non-ASCII byte — the canonical "I copied
14855        // the subject from a doc with smart quotes / accented
14856        // characters" footgun.
14857        let err = contrato_subject_err("foo.caf\u{e9}");
14858        assert!(
14859            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14860                if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
14861            "got {err:?}"
14862        );
14863    }
14864
14865    #[test]
14866    fn rejects_pubsub_contrato_subject_with_leading_dot() {
14867        // Empty leading token — NATS rejects.
14868        let err = contrato_subject_err(".foo");
14869        assert!(
14870            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14871                if subject == ".foo" && reason.contains("must not start with `.`")),
14872            "got {err:?}"
14873        );
14874    }
14875
14876    #[test]
14877    fn rejects_pubsub_contrato_subject_with_trailing_dot() {
14878        // Empty trailing token — NATS rejects. The remediation
14879        // (use `>` instead) is in the reason string.
14880        let err = contrato_subject_err("foo.");
14881        assert!(
14882            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14883                if subject == "foo." && reason.contains("must not end with `.`")),
14884            "got {err:?}"
14885        );
14886    }
14887
14888    #[test]
14889    fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
14890        // The canonical "I forgot to fill in the middle segment"
14891        // typo — `"foo..bar"`. NATS rejects empty tokens.
14892        let err = contrato_subject_err("foo..bar");
14893        assert!(
14894            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14895                if subject == "foo..bar" && reason.contains("consecutive `.`")),
14896            "got {err:?}"
14897        );
14898    }
14899
14900    #[test]
14901    fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
14902        // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
14903        // as the final segment. Pre-gate this passed as a typed edge
14904        // and surfaced at runtime as a NATS subscribe rejection.
14905        let err = contrato_subject_err("foo.>.bar");
14906        assert!(
14907            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14908                if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
14909            "got {err:?}"
14910        );
14911    }
14912
14913    #[test]
14914    fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
14915        // `foo*.bar` — NATS wildcards are standalone tokens. The
14916        // remediation is in the reason string.
14917        let err = contrato_subject_err("foo*.bar");
14918        assert!(
14919            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14920                if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
14921            "got {err:?}"
14922        );
14923    }
14924
14925    #[test]
14926    fn rejects_pubsub_contrato_subject_with_invalid_char() {
14927        // `foo,bar` — comma is not a valid NATS subject character.
14928        // Pinned separately from the wildcard arms so the invalid-
14929        // character diagnostic is in force.
14930        let err = contrato_subject_err("foo,bar");
14931        assert!(
14932            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14933                if subject == "foo,bar" && reason.contains("invalid character")),
14934            "got {err:?}"
14935        );
14936    }
14937
14938    #[test]
14939    fn rejects_pubsub_contrato_subject_too_long() {
14940        // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
14941        // The legitimate-shape arms all pass (one all-`a` token, no
14942        // `.`, no wildcards); only the cap arm fires. Surfaces the
14943        // paste-from-binary / accidental-multi-line-blob landing
14944        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
14945        // on the peer axis.
14946        let big = "a".repeat(257);
14947        assert_eq!(big.len(), 257);
14948        let err = contrato_subject_err(&big);
14949        assert!(
14950            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14951                if subject == &big && reason.contains("max length of 256")),
14952            "got {err:?}"
14953        );
14954    }
14955
14956    #[test]
14957    fn pubsub_contrato_subject_max_length_validates() {
14958        // 256-byte subject — exactly the cap. Boundary pin: drift in
14959        // the cap surfaces here and at
14960        // `rejects_pubsub_contrato_subject_too_long` simultaneously,
14961        // mirroring `http_contrato_endpoint_max_length_validates` and
14962        // `wit_max_length_validates` on the peer axes.
14963        let big = "a".repeat(256);
14964        assert_eq!(big.len(), 256);
14965        let mut s = three_member_spec();
14966        s.contratos.push(WitContract {
14967            de: "payment".into(),
14968            para: "catalog".into(),
14969            wit: "nats:pub-sub".into(),
14970            endpoint: None,
14971            subject: Some(big),
14972            slot: None,
14973        });
14974        s.validate().unwrap();
14975    }
14976
14977    #[test]
14978    fn pubsub_contrato_subject_accepts_canonical_forms() {
14979        // Positive-set sweep: every canonical NATS subject shape the
14980        // substrate-side `is_nats_subject` predicate accepts (the
14981        // multi-dot `events.order.charged`, the snake_case / kebab-
14982        // case / mixed-case tokens, the digit-bearing tokens, the
14983        // single-token wildcard `*` at every segment position, and
14984        // the trailing `>` multi-token wildcard) must remain a valid
14985        // contrato subject too. Drift between this list and the
14986        // substrate-side `nats_subject_accepts_canonical_forms` sweep
14987        // surfaces at the shared predicate — one source of truth.
14988        // Uses a fresh `(payment, catalog)` edge so none of the swept
14989        // subjects collide with the pre-existing entries in
14990        // `three_member_spec`.
14991        for subject in [
14992            "checkout.events.charge.failed",
14993            "rio.events.order.charged",
14994            "orders",
14995            "orders.123",
14996            "snake_case.token",
14997            "kebab-case.token",
14998            "MixedCase.Token",
14999            "orders.*.charged",
15000            "*.events.*",
15001            "orders.>",
15002        ] {
15003            let mut s = three_member_spec();
15004            s.contratos.push(WitContract {
15005                de: "payment".into(),
15006                para: "catalog".into(),
15007                wit: "nats:pub-sub".into(),
15008                endpoint: None,
15009                subject: Some(subject.into()),
15010                slot: None,
15011            });
15012            s.validate()
15013                .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
15014        }
15015    }
15016
15017    #[test]
15018    fn contrato_subject_empty_takes_precedence_over_invalid() {
15019        // Ordering pin: `ContratoSubjectEmpty` is the more self-
15020        // locating diagnostic on `""` and must lead — the value-shape
15021        // gate is only reached after the empty-check fires. Mirrors
15022        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
15023        // the peer payload axis.
15024        let mut s = three_member_spec();
15025        s.contratos.push(WitContract {
15026            de: "payment".into(),
15027            para: "catalog".into(),
15028            wit: "nats:pub-sub".into(),
15029            endpoint: None,
15030            subject: Some(String::new()),
15031            slot: None,
15032        });
15033        let err = s.validate().unwrap_err();
15034        assert!(
15035            matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
15036            "got {err:?}"
15037        );
15038    }
15039
15040    #[test]
15041    fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
15042        // Diagnostic-shape pin — the offending `:subject` + `:de` +
15043        // `:para` + a non-empty reason flow through verbatim so the
15044        // author can grep their caixa.lisp for the offending contrato
15045        // block and fix it in one edit. Same shape as
15046        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
15047        // and `wit_invalid_diagnostic_carries_offending_wit`.
15048        let err = contrato_subject_err("foo..bar");
15049        match err {
15050            AplicacaoError::ContratoSubjectInvalid {
15051                de,
15052                para,
15053                subject,
15054                reason,
15055            } => {
15056                assert_eq!(de, "payment");
15057                assert_eq!(para, "catalog");
15058                assert_eq!(subject, "foo..bar");
15059                assert!(!reason.is_empty(), "reason field must be non-empty");
15060            }
15061            other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
15062        }
15063    }
15064
15065    #[test]
15066    fn target_view_pubsub_subject_passes_through_to_typed_view() {
15067        // The compounding theorem on the pub-sub axis: every
15068        // `WitTarget::PubSub { subject }` returned by `target()` carries
15069        // a NATS-server-accepted subject. Renderers downstream of
15070        // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
15071        // NATS Stream/Consumer CR emitter, the future `feira app graph`
15072        // view's subject labeller) can rely on this without re-checking
15073        // — the type system carries the proof. Mirrors
15074        // `target_view_payload_is_guaranteed_nonempty_after_target_call`
15075        // on the peer axes.
15076        let nats = WitContract {
15077            de: "a".into(),
15078            para: "b".into(),
15079            wit: "nats:pub-sub".into(),
15080            endpoint: None,
15081            subject: Some("orders.events.*.charged".into()),
15082            slot: None,
15083        };
15084        match nats.target().unwrap() {
15085            WitTarget::PubSub { subject } => {
15086                assert_eq!(subject, "orders.events.*.charged");
15087            }
15088            other => panic!("expected PubSub, got {other:?}"),
15089        }
15090    }
15091
15092    // ── :contratos :slot value-shape gate ────────────────────────────────
15093    //
15094    // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
15095    // (63e18a0) value-shape suites on the peer payload axes. Until this
15096    // gate landed `WitContract::target()` only refused the empty string
15097    // for the Store arm; a structurally invalid slot (raw whitespace,
15098    // control character, non-ASCII byte, paste-from-binary multi-line
15099    // blob) silently passed validate and surfaced at runtime as a
15100    // per-backend kv write rejection or a silent next-read corruption,
15101    // far from the source caixa.lisp with no field naming which
15102    // `:contratos` edge carried the typo. Every authoring footgun the
15103    // kv backend intersection-floor would catch on write now becomes a
15104    // caixa-build-time `ContratoSlotInvalid` with the offending
15105    // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
15106    // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
15107    // peer payload axes; same shared predicate
15108    // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
15109    // any two axes' rule enforcement is a build error at the
15110    // predicate, not piecemeal across renderers. Closes the typed
15111    // payload-axis value-shape trajectory across all three legs of the
15112    // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
15113
15114    fn contrato_slot_err(slot: &str) -> AplicacaoError {
15115        // Fresh spec per call so the new contract doesn't collide on
15116        // identity with `three_member_spec`'s pre-existing entries
15117        // and doesn't close a synchronous cycle the cycle detector
15118        // would reject before the slot-shape gate fires. The new edge
15119        // uses `(payment, catalog)` — a pair the fixture doesn't
15120        // already declare in either direction (the fixture carries
15121        // `cart -> catalog` and `cart -> payment`, so `payment ->
15122        // catalog` doesn't form a cycle on the sync subgraph) — with
15123        // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
15124        // slot-shape gate fires cleanly after the wit-shape gate
15125        // (which `"wasi:keyvalue/store"` passes). Same edge pair the
15126        // peer `contrato_subject_err` helper uses (63e18a0).
15127        let mut s = three_member_spec();
15128        s.contratos.push(WitContract {
15129            de: "payment".into(),
15130            para: "catalog".into(),
15131            wit: "wasi:keyvalue/store".into(),
15132            endpoint: None,
15133            subject: None,
15134            slot: Some(slot.into()),
15135        });
15136        s.validate().unwrap_err()
15137    }
15138
15139    #[test]
15140    fn rejects_store_contrato_slot_with_whitespace() {
15141        // Fail-before-pass-after pin — pre-gate `"check out/$order"`
15142        // silently landed at the kv backend with whitespace whose
15143        // runtime behavior varies unpredictably across backends (etcd
15144        // accepts, Redis accepts then breaks on next CLI op, DynamoDB
15145        // rejects on write). Now caught at the source caixa.lisp.
15146        let err = contrato_slot_err("check out/$order");
15147        assert!(
15148            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
15149                if slot == "check out/$order" && reason.contains("whitespace")),
15150            "got {err:?}"
15151        );
15152    }
15153
15154    #[test]
15155    fn rejects_store_contrato_slot_with_tab() {
15156        // Tab byte arm-pinned separately from the space arm so a
15157        // future relaxation that admits one but not the other surfaces
15158        // here.
15159        let err = contrato_slot_err("check\tout");
15160        assert!(
15161            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
15162                if slot == "check\tout" && reason.contains("whitespace")),
15163            "got {err:?}"
15164        );
15165    }
15166
15167    #[test]
15168    fn rejects_store_contrato_slot_with_control_char() {
15169        // SOH (0x01) — distinct from the whitespace arm. Redis admits
15170        // and corrupts on RESP protocol framing; DynamoDB rejects on
15171        // write.
15172        let err = contrato_slot_err("checkout/\x01order");
15173        assert!(
15174            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
15175                if slot == "checkout/\x01order" && reason.contains("control character")),
15176            "got {err:?}"
15177        );
15178    }
15179
15180    #[test]
15181    fn rejects_store_contrato_slot_with_newline() {
15182        // Embedded newline — the canonical "the paste-from-binary slug
15183        // spans multiple lines" footgun. Distinct from the whitespace
15184        // arm because `\n` is a control character (0x0A).
15185        let err = contrato_slot_err("checkout\norder");
15186        assert!(
15187            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
15188                if slot == "checkout\norder" && reason.contains("control character")),
15189            "got {err:?}"
15190        );
15191    }
15192
15193    #[test]
15194    fn rejects_store_contrato_slot_with_non_ascii() {
15195        // Un-percent-encoded non-ASCII byte — the canonical "I copied
15196        // the slot from a doc with accented characters" footgun. Each
15197        // kv backend re-encodes non-ASCII differently (etcd preserves
15198        // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
15199        // rejects), so the typed slot's value set is the intersection-
15200        // floor every backend admits identically (printable ASCII).
15201        let err = contrato_slot_err("ch\u{e9}ckout/$order");
15202        assert!(
15203            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
15204                if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
15205            "got {err:?}"
15206        );
15207    }
15208
15209    #[test]
15210    fn rejects_store_contrato_slot_too_long() {
15211        // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
15212        // legitimate-shape arms all pass (a single all-`a` token, no
15213        // separators); only the cap arm fires. Surfaces the paste-
15214        // from-binary / accidental-multi-line-blob landing footgun.
15215        // Mirrors `rejects_pubsub_contrato_subject_too_long` and
15216        // `rejects_http_contrato_endpoint_too_long` on the peer
15217        // payload axes.
15218        let big = "a".repeat(513);
15219        assert_eq!(big.len(), 513);
15220        let err = contrato_slot_err(&big);
15221        assert!(
15222            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
15223                if slot == &big && reason.contains("max length of 512")),
15224            "got {err:?}"
15225        );
15226    }
15227
15228    #[test]
15229    fn store_contrato_slot_max_length_validates() {
15230        // 512-byte slot — exactly the cap. Boundary pin: drift in the
15231        // cap surfaces here and at `rejects_store_contrato_slot_too_long`
15232        // simultaneously, mirroring
15233        // `pubsub_contrato_subject_max_length_validates` and
15234        // `http_contrato_endpoint_max_length_validates` on the peer
15235        // payload axes.
15236        let big = "a".repeat(512);
15237        assert_eq!(big.len(), 512);
15238        let mut s = three_member_spec();
15239        s.contratos.push(WitContract {
15240            de: "payment".into(),
15241            para: "catalog".into(),
15242            wit: "wasi:keyvalue/store".into(),
15243            endpoint: None,
15244            subject: None,
15245            slot: Some(big),
15246        });
15247        s.validate().unwrap();
15248    }
15249
15250    #[test]
15251    fn store_contrato_slot_accepts_canonical_forms() {
15252        // Positive-set sweep: every canonical kv slot template the
15253        // substrate-side `is_wasi_keyvalue_slot` predicate accepts
15254        // (single-token identifiers, path-namespaced `$`-templates,
15255        // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
15256        // snake_case / kebab-case / MixedCase tokens, digit-bearing
15257        // tokens, percent-encoded fragments) must remain valid
15258        // contrato slots too. Drift between this list and the
15259        // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
15260        // surfaces at the shared predicate — one source of truth.
15261        // Uses a fresh `(payment, catalog)` edge so none of the swept
15262        // slots collide with the pre-existing entries in
15263        // `three_member_spec`.
15264        for slot in [
15265            "checkout",
15266            "checkout/$orderId",
15267            "users:{tenant}/{id}",
15268            "session.<sid>",
15269            "session.tokens.<sid>",
15270            "snake_case_key",
15271            "kebab-case-key",
15272            "MixedCase",
15273            "shard0",
15274            "v2/key",
15275            "users/caf%C3%A9",
15276        ] {
15277            let mut s = three_member_spec();
15278            s.contratos.push(WitContract {
15279                de: "payment".into(),
15280                para: "catalog".into(),
15281                wit: "wasi:keyvalue/store".into(),
15282                endpoint: None,
15283                subject: None,
15284                slot: Some(slot.into()),
15285            });
15286            s.validate()
15287                .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
15288        }
15289    }
15290
15291    #[test]
15292    fn contrato_slot_empty_takes_precedence_over_invalid() {
15293        // Ordering pin: `ContratoSlotEmpty` is the more self-locating
15294        // diagnostic on `""` and must lead — the value-shape gate is
15295        // only reached after the empty-check fires. Mirrors
15296        // `contrato_subject_empty_takes_precedence_over_invalid` and
15297        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
15298        // the peer payload axes.
15299        let mut s = three_member_spec();
15300        s.contratos.push(WitContract {
15301            de: "payment".into(),
15302            para: "catalog".into(),
15303            wit: "wasi:keyvalue/store".into(),
15304            endpoint: None,
15305            subject: None,
15306            slot: Some(String::new()),
15307        });
15308        let err = s.validate().unwrap_err();
15309        assert!(
15310            matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
15311            "got {err:?}"
15312        );
15313    }
15314
15315    #[test]
15316    fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
15317        // Diagnostic-shape pin — the offending `:slot` + `:de` +
15318        // `:para` + a non-empty reason flow through verbatim so the
15319        // author can grep their caixa.lisp for the offending contrato
15320        // block and fix it in one edit. Same shape as
15321        // `contrato_subject_invalid_diagnostic_carries_offending_subject`
15322        // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
15323        // on the peer payload axes.
15324        let err = contrato_slot_err("check out/$order");
15325        match err {
15326            AplicacaoError::ContratoSlotInvalid {
15327                de,
15328                para,
15329                slot,
15330                reason,
15331            } => {
15332                assert_eq!(de, "payment");
15333                assert_eq!(para, "catalog");
15334                assert_eq!(slot, "check out/$order");
15335                assert!(!reason.is_empty(), "reason field must be non-empty");
15336            }
15337            other => panic!("expected ContratoSlotInvalid, got {other:?}"),
15338        }
15339    }
15340
15341    #[test]
15342    fn target_view_store_slot_passes_through_to_typed_view() {
15343        // The compounding theorem on the store axis: every
15344        // `WitTarget::Store { slot }` returned by `target()` carries a
15345        // kv-backend-accepted slot template. Renderers downstream of
15346        // `typed_view()` (the future per-Servico `:capabilities
15347        // wasi:keyvalue/store` axis emitter, the future `feira app
15348        // graph` view's slot labeller, the future kv-provider CR
15349        // materializer) can rely on this without re-checking — the
15350        // type system carries the proof. Mirrors
15351        // `target_view_pubsub_subject_passes_through_to_typed_view` on
15352        // the peer payload axis.
15353        let store = WitContract {
15354            de: "a".into(),
15355            para: "b".into(),
15356            wit: "wasi:keyvalue/store".into(),
15357            endpoint: None,
15358            subject: None,
15359            slot: Some("checkout/$orderId".into()),
15360        };
15361        match store.target().unwrap() {
15362            WitTarget::Store { slot } => {
15363                assert_eq!(slot, "checkout/$orderId");
15364            }
15365            other => panic!("expected Store, got {other:?}"),
15366        }
15367    }
15368
15369    #[test]
15370    fn rejects_self_loop_in_synchronous_contratos() {
15371        // A synchronous self-edge (`cart → cart` over HTTP) is now
15372        // rejected by the dedicated `ContratoSelfLoop` gate — a precise
15373        // "this edge is degenerate" diagnostic — rather than incidentally
15374        // by the cycle detector framing it as a `["cart", "cart"]`
15375        // multi-node deadlock.
15376        let mut s = three_member_spec();
15377        s.contratos.push(contract_http("cart", "cart", "/loop"));
15378        let err = s.validate().unwrap_err();
15379        match err {
15380            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
15381                assert_eq!(caixa, "cart");
15382                assert_eq!(wit, "wasi:http/proxy");
15383            }
15384            other => panic!("expected ContratoSelfLoop, got {other:?}"),
15385        }
15386    }
15387
15388    #[test]
15389    fn rejects_self_loop_in_pubsub_contratos() {
15390        // The cycle detector excludes pub-sub edges (acyclic by
15391        // construction), so before the explicit gate a `nats:pub-sub`
15392        // self-edge silently validated and rendered a self-allow CNP.
15393        // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
15394        let mut s = three_member_spec();
15395        s.contratos.push(WitContract {
15396            de: "payment".into(),
15397            para: "payment".into(),
15398            wit: "nats:pub-sub".into(),
15399            endpoint: None,
15400            subject: Some("rio.events.payment".into()),
15401            slot: None,
15402        });
15403        let err = s.validate().unwrap_err();
15404        match err {
15405            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
15406                assert_eq!(caixa, "payment");
15407                assert_eq!(wit, "nats:pub-sub");
15408            }
15409            other => panic!("expected ContratoSelfLoop, got {other:?}"),
15410        }
15411    }
15412
15413    #[test]
15414    fn self_loop_fires_before_payload_shape_check() {
15415        // The structural "this edge can't exist" error precedes the
15416        // narrower payload-shape diagnostics: a self-edge carrying an
15417        // otherwise-malformed endpoint still reports ContratoSelfLoop,
15418        // not ContratoEndpointInvalid.
15419        let mut s = three_member_spec();
15420        s.contratos.push(WitContract {
15421            de: "cart".into(),
15422            para: "cart".into(),
15423            wit: "wasi:http/proxy".into(),
15424            endpoint: Some("not-absolute".into()),
15425            subject: None,
15426            slot: None,
15427        });
15428        match s.validate().unwrap_err() {
15429            AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
15430            other => panic!("expected ContratoSelfLoop, got {other:?}"),
15431        }
15432    }
15433
15434    #[test]
15435    fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
15436        // A self-edge naming a non-member reports the more fundamental
15437        // ContratoMemberMissing first (the member doesn't exist), so the
15438        // self-loop gate is reached only once both endpoints resolve.
15439        let mut s = three_member_spec();
15440        s.contratos.push(contract_http("ghost", "ghost", "/loop"));
15441        match s.validate().unwrap_err() {
15442            AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
15443            other => panic!("expected ContratoMemberMissing, got {other:?}"),
15444        }
15445    }
15446
15447    #[test]
15448    fn rejects_two_node_synchronous_cycle() {
15449        let mut s = three_member_spec();
15450        // existing edges: cart → catalog, cart → payment
15451        // adding catalog → cart closes a 2-cycle on the HTTP subgraph
15452        s.contratos
15453            .push(contract_http("catalog", "cart", "/refresh"));
15454        let err = s.validate().unwrap_err();
15455        match err {
15456            AplicacaoError::ContratoCycle { cycle } => {
15457                // Cycle traversal should mention both endpoints, with
15458                // the back-edge target appearing as both first and last
15459                // element to close the loop.
15460                assert!(cycle.len() >= 3);
15461                assert_eq!(cycle.first(), cycle.last());
15462                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
15463                assert!(body.contains("cart"));
15464                assert!(body.contains("catalog"));
15465            }
15466            other => panic!("expected ContratoCycle, got {other:?}"),
15467        }
15468    }
15469
15470    #[test]
15471    fn rejects_three_node_synchronous_cycle() {
15472        let mut s = three_member_spec();
15473        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
15474        s.contratos = vec![
15475            contract_http("catalog", "cart", "/x"),
15476            contract_http("cart", "payment", "/y"),
15477            contract_http("payment", "catalog", "/z"),
15478        ];
15479        let err = s.validate().unwrap_err();
15480        match err {
15481            AplicacaoError::ContratoCycle { cycle } => {
15482                assert_eq!(cycle.first(), cycle.last());
15483                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
15484                assert_eq!(body.len(), 3);
15485                assert!(body.contains("cart"));
15486                assert!(body.contains("catalog"));
15487                assert!(body.contains("payment"));
15488            }
15489            other => panic!("expected ContratoCycle, got {other:?}"),
15490        }
15491    }
15492
15493    #[test]
15494    fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
15495        // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
15496        // "acyclic by construction" — so a cycle whose closing edge
15497        // is pub-sub should NOT raise ContratoCycle.
15498        let mut s = three_member_spec();
15499        s.contratos = vec![
15500            contract_http("catalog", "cart", "/x"),
15501            contract_http("cart", "payment", "/y"),
15502            // Closing edge is pub-sub — async; not a sync deadlock.
15503            WitContract {
15504                de: "payment".into(),
15505                para: "catalog".into(),
15506                wit: "nats:pub-sub".into(),
15507                endpoint: None,
15508                subject: Some("checkout.events.charge.completed".into()),
15509                slot: None,
15510            },
15511        ];
15512        s.validate().expect("pub-sub edge breaks the sync cycle");
15513    }
15514
15515    #[test]
15516    fn store_edge_counts_as_synchronous_for_cycle_detection() {
15517        // wasi:keyvalue/store is request/response; a cycle through one
15518        // *is* a sync deadlock, just like HTTP.
15519        let mut s = three_member_spec();
15520        s.contratos = vec![
15521            contract_http("catalog", "cart", "/x"),
15522            WitContract {
15523                de: "cart".into(),
15524                para: "catalog".into(),
15525                wit: "wasi:keyvalue/store".into(),
15526                endpoint: None,
15527                subject: None,
15528                slot: Some("session/$id".into()),
15529            },
15530        ];
15531        let err = s.validate().unwrap_err();
15532        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
15533    }
15534
15535    #[test]
15536    fn capability_edge_counts_as_synchronous_for_cycle_detection() {
15537        // Capability-only edges (unknown WIT shape, no payload) default
15538        // to synchronous — safer; authors with truly async capability
15539        // semantics can model them as pub-sub explicitly.
15540        let mut s = three_member_spec();
15541        s.contratos = vec![
15542            contract_http("catalog", "cart", "/x"),
15543            WitContract {
15544                de: "cart".into(),
15545                para: "catalog".into(),
15546                wit: "custom:exchange".into(),
15547                endpoint: None,
15548                subject: None,
15549                slot: None,
15550            },
15551        ];
15552        let err = s.validate().unwrap_err();
15553        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
15554    }
15555
15556    #[test]
15557    fn long_acyclic_chain_validates() {
15558        // A long sync chain (no back-edges) must validate even when
15559        // every node is reachable from the first.
15560        let mut s = three_member_spec();
15561        s.membros = vec![
15562            membro("a", "^0.1"),
15563            membro("b", "^0.1"),
15564            membro("c", "^0.1"),
15565            membro("d", "^0.1"),
15566            membro("e", "^0.1"),
15567        ];
15568        s.contratos = vec![
15569            contract_http("a", "b", "/1"),
15570            contract_http("b", "c", "/2"),
15571            contract_http("c", "d", "/3"),
15572            contract_http("d", "e", "/4"),
15573        ];
15574        s.entrada.as_mut().unwrap().para = "a".into();
15575        s.validate().unwrap();
15576    }
15577
15578    #[test]
15579    fn diamond_acyclic_validates() {
15580        // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
15581        let mut s = three_member_spec();
15582        s.membros = vec![
15583            membro("a", "^0.1"),
15584            membro("b", "^0.1"),
15585            membro("c", "^0.1"),
15586            membro("d", "^0.1"),
15587        ];
15588        s.contratos = vec![
15589            contract_http("a", "b", "/1"),
15590            contract_http("a", "c", "/2"),
15591            contract_http("b", "d", "/3"),
15592            contract_http("c", "d", "/4"),
15593        ];
15594        s.entrada.as_mut().unwrap().para = "a".into();
15595        s.validate().unwrap();
15596    }
15597
15598    // ── duplicate-`:contratos` build-error gate ──────────────────────────
15599
15600    #[test]
15601    fn rejects_duplicate_http_contrato() {
15602        // Fail-before-pass-after pin: the fixture's `cart → catalog`
15603        // HTTP edge appears once. Push an identical entry — same
15604        // (de, para, wit, endpoint) — and validate() must reject it.
15605        // Until this gate landed the typed surface accepted the
15606        // duplicate silently and caixa-mesh's `cilium_network_policies`
15607        // emitted two ``CiliumNetworkPolicy`` objects with identical
15608        // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
15609        // admission rejects on `kubectl apply` far from the source.
15610        let mut s = three_member_spec();
15611        s.contratos
15612            .push(contract_http("cart", "catalog", "/products/:id"));
15613        let err = s.validate().unwrap_err();
15614        assert!(
15615            matches!(
15616                err,
15617                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
15618                    if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
15619            ),
15620            "got {err:?}"
15621        );
15622    }
15623
15624    #[test]
15625    fn rejects_duplicate_pubsub_contrato() {
15626        // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
15627        // edges with identical (de, para, subject) are degenerate;
15628        // pin that the typed surface refuses both at validate time.
15629        let mut s = three_member_spec();
15630        let pubsub = WitContract {
15631            de: "payment".into(),
15632            para: "cart".into(),
15633            wit: "nats:pub-sub".into(),
15634            endpoint: None,
15635            subject: Some("checkout.events.charge.failed".into()),
15636            slot: None,
15637        };
15638        s.contratos.push(pubsub.clone());
15639        s.contratos.push(pubsub);
15640        let err = s.validate().unwrap_err();
15641        assert!(
15642            matches!(
15643                err,
15644                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
15645                    if de == "payment" && para == "cart" && wit == "nats:pub-sub"
15646            ),
15647            "got {err:?}"
15648        );
15649    }
15650
15651    #[test]
15652    fn rejects_duplicate_store_contrato() {
15653        // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
15654        // edges with identical (de, para, slot) collapse to one mesh-
15655        // policy edge; pin the build error.
15656        let mut s = three_member_spec();
15657        let store = WitContract {
15658            de: "cart".into(),
15659            para: "payment".into(),
15660            wit: "wasi:keyvalue/store".into(),
15661            endpoint: None,
15662            subject: None,
15663            slot: Some("checkout/$orderId".into()),
15664        };
15665        // Drop the conflicting HTTP `cart → payment` edge from the
15666        // fixture so the duplicate-store pair is the only one
15667        // distinguishable on this pair.
15668        s.contratos
15669            .retain(|c| !(c.de == "cart" && c.para == "payment"));
15670        s.contratos.push(store.clone());
15671        s.contratos.push(store);
15672        let err = s.validate().unwrap_err();
15673        assert!(
15674            matches!(
15675                err,
15676                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
15677                    if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
15678            ),
15679            "got {err:?}"
15680        );
15681    }
15682
15683    #[test]
15684    fn rejects_duplicate_capability_contrato() {
15685        // Same gate on the pure-capability axis (no payload selector).
15686        // Two contracts with identical (de, para, wit) and no
15687        // endpoint/subject/slot are duplicate edges; pin so a future
15688        // `target_label` change can't accidentally collapse the
15689        // capability arm into a None-shaped key that compares equal
15690        // to a populated one.
15691        let mut s = three_member_spec();
15692        let capability = WitContract {
15693            de: "cart".into(),
15694            para: "catalog".into(),
15695            wit: "pleme:cap/audit".into(),
15696            endpoint: None,
15697            subject: None,
15698            slot: None,
15699        };
15700        s.contratos.push(capability.clone());
15701        s.contratos.push(capability);
15702        let err = s.validate().unwrap_err();
15703        match err {
15704            AplicacaoError::ContratoDuplicate {
15705                de,
15706                para,
15707                wit,
15708                target,
15709            } => {
15710                assert_eq!(de, "cart");
15711                assert_eq!(para, "catalog");
15712                assert_eq!(wit, "pleme:cap/audit");
15713                assert!(
15714                    target.contains("capability"),
15715                    "capability-edge duplicate diagnostic must surface the \
15716                     no-payload shape (got target = {target:?})"
15717                );
15718            }
15719            other => panic!("expected ContratoDuplicate, got {other:?}"),
15720        }
15721    }
15722
15723    #[test]
15724    fn accepts_distinct_http_paths_between_same_pair() {
15725        // Negative pin: two HTTP contracts cart → catalog at distinct
15726        // endpoints (`/products/:id` and `/search`) are *not*
15727        // duplicates — they're distinct typed edges differing on the
15728        // payload axis. The duplicate-gate must not over-match here,
15729        // since the cart-calls-catalog-on-multiple-paths shape is the
15730        // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
15731        // example: cart calls catalog at /products/:id, payment at
15732        // /charge — same shape extends to two paths on one para).
15733        let mut s = three_member_spec();
15734        s.contratos
15735            .push(contract_http("cart", "catalog", "/search"));
15736        s.validate()
15737            .expect("distinct endpoints between same (de, para) must validate");
15738    }
15739
15740    #[test]
15741    fn accepts_same_endpoint_on_different_pairs() {
15742        // Negative pin: the same `/charge` endpoint reused on two
15743        // different (de, para) pairs is two distinct edges, not a
15744        // duplicate. Pinning this shape so the gate's identity key
15745        // includes both `de` and `para` (not just `(wit, endpoint)`).
15746        let mut s = three_member_spec();
15747        s.contratos
15748            .push(contract_http("payment", "catalog", "/charge"));
15749        s.validate()
15750            .expect("same endpoint reused on distinct (de, para) must validate");
15751    }
15752
15753    #[test]
15754    fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
15755        // Pin the diagnostic shape: the duplicate-edge error names
15756        // *which* target field carried the conflict, so the author
15757        // doesn't have to re-grep the source caixa.lisp to find it.
15758        // Same self-locating diagnostic discipline as
15759        // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
15760        let mut s = three_member_spec();
15761        s.contratos
15762            .push(contract_http("cart", "catalog", "/products/:id"));
15763        let err = s.validate().unwrap_err();
15764        let msg = format!("{err}");
15765        assert!(
15766            msg.contains("\"/products/:id\""),
15767            "duplicate-contrato diagnostic must name the offending \
15768             :endpoint payload (got: {msg:?})"
15769        );
15770        assert!(
15771            msg.contains("cart") && msg.contains("catalog"),
15772            "diagnostic must name both endpoints of the duplicate edge \
15773             (got: {msg:?})"
15774        );
15775    }
15776
15777    #[test]
15778    fn duplicate_contrato_gate_runs_after_membership_check() {
15779        // Order pin: a duplicate contract whose `:de` is *also* not in
15780        // `:membros` surfaces the membership error first — the
15781        // missing-member diagnostic is more locating than the
15782        // duplicate-edge one (the author has to fix the membership
15783        // before the duplicate is meaningful). Same ordering
15784        // discipline as `membros_validation_runs_before_contratos_membership_check`.
15785        let mut s = three_member_spec();
15786        s.contratos.push(contract_http("phantom", "catalog", "/x"));
15787        s.contratos.push(contract_http("phantom", "catalog", "/x"));
15788        let err = s.validate().unwrap_err();
15789        assert!(
15790            matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
15791            "membership-missing must fire before duplicate-edge (got {err:?})"
15792        );
15793    }
15794
15795    #[test]
15796    fn duplicate_contrato_gate_runs_after_target_shape_check() {
15797        // Order pin: a contract with a malformed target (e.g. an HTTP
15798        // wit world with an empty :endpoint) surfaces the target-shape
15799        // error first, not the duplicate one. Even when two such
15800        // malformed entries are identical, the per-contract `target()`
15801        // check fires inside the loop *before* the duplicate-key
15802        // insert, so the diagnostic remains the most-locating one.
15803        let mut s = three_member_spec();
15804        let malformed = WitContract {
15805            de: "cart".into(),
15806            para: "catalog".into(),
15807            wit: "wasi:http/proxy".into(),
15808            endpoint: Some(String::new()),
15809            subject: None,
15810            slot: None,
15811        };
15812        s.contratos.push(malformed.clone());
15813        s.contratos.push(malformed);
15814        let err = s.validate().unwrap_err();
15815        assert!(
15816            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
15817            "endpoint-empty must fire before duplicate-edge (got {err:?})"
15818        );
15819    }
15820
15821    #[test]
15822    fn wit_target_label_pins_per_variant_format() {
15823        // Label format is the single source of truth every duplicate-
15824        // `:contratos` diagnostic + every future `feira app graph`
15825        // consumer routes through. Pin the shape per variant so a
15826        // future edit to `WitTarget::label` (e.g. a JSON emitter that
15827        // strips the leading `:`, or a rename from `endpoint` →
15828        // `path`) surfaces as a red-red test rather than as a silent
15829        // downstream diagnostic drift. Together with the exhaustive
15830        // `match` on `WitTarget` inside `label()`, adding a future
15831        // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
15832        // peer, per-edge WIT registry variants) is a compile error at
15833        // the label site — not a fall-through into the `Capability`
15834        // "no payload" default the prior raw-field-probe helper
15835        // silently landed on.
15836        assert_eq!(
15837            WitTarget::Http {
15838                endpoint: "/charge",
15839            }
15840            .label(),
15841            "\
15842:endpoint \"/charge\""
15843        );
15844        assert_eq!(
15845            WitTarget::PubSub {
15846                subject: "events.checkout.paid",
15847            }
15848            .label(),
15849            "\
15850:subject \"events.checkout.paid\""
15851        );
15852        assert_eq!(
15853            WitTarget::Store {
15854                slot: "checkout/$order",
15855            }
15856            .label(),
15857            "\
15858:slot \"checkout/$order\""
15859        );
15860        assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
15861        // Capability-arm label routes through the lifted
15862        // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
15863        // declaration per arm, next to the variant" discipline the
15864        // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
15865        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
15866        // consts already carry extends to the payload-less arm; the
15867        // byte-string equality pin below plus this label-routes-
15868        // through-the-const pin make a future rebrand on either the
15869        // const declaration or the `label()` template a build error
15870        // here rather than a downstream consumer surprise.
15871        assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
15872        assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
15873    }
15874
15875    #[test]
15876    fn wit_target_display_routes_through_label_helper() {
15877        // Fail-before-pass-after pin on the fourth (and only remaining)
15878        // typed-shape-discriminator axis to converge onto the
15879        // three-path-convergence discipline the sibling M3
15880        // [`PlacementStrategy`] (0a2f653) and M2
15881        // [`crate::supervisor::RestartStrategy`] /
15882        // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
15883        // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
15884        // through [`WitTarget::label`], so every consumer reaching for
15885        // `format!("{v}")` on a typed payload target lands on the same
15886        // stable author-facing byte-string [`WitTarget::label`] returns
15887        // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
15888        // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
15889        // `:contratos` gate seeds via [`WitTarget::label`] at
15890        // aplicacao.rs:5491 already threads through.
15891        //
15892        // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
15893        // through to the `Debug` derive's structural output
15894        // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
15895        // rather than the [`WitTarget::label`] helper's stable byte-
15896        // string (`:endpoint "/charge"` — the author-facing `:contratos`
15897        // keyword form). Every future consumer that reaches for
15898        // `format!("{target}")` — the canonical shape every user-facing
15899        // pretty-print site on the sibling typed-enum axes
15900        // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
15901        // [`crate::supervisor::RestartPolicy`]) already uses — would
15902        // silently land under a different byte-string than the
15903        // [`WitTarget::label`] callers that the duplicate-`:contratos`
15904        // diagnostic already threads through, with the mismatch
15905        // surfacing as a downstream diagnostic / graph / audit line
15906        // reading one spelling while the substrate's own gate emitted
15907        // another.
15908        //
15909        // Pin the routing here so a future
15910        // `impl std::fmt::Display for WitTarget<'_>` reimplementation
15911        // that hand-rolls the per-arm formatting instead of delegating
15912        // to [`WitTarget::label`] fails at caixa-core build time.
15913        for variant in [
15914            WitTarget::Http {
15915                endpoint: "/charge",
15916            },
15917            WitTarget::PubSub {
15918                subject: "events.checkout.paid",
15919            },
15920            WitTarget::Store {
15921                slot: "checkout/$order",
15922            },
15923            WitTarget::Capability,
15924        ] {
15925            assert_eq!(
15926                variant.to_string(),
15927                variant.label(),
15928                "WitTarget::{variant:?} Display must route through \
15929                 WitTarget::label (single source of truth: the lifted \
15930                 payload_pair 4-arm dispatch the label helper already \
15931                 threads through)"
15932            );
15933        }
15934    }
15935
15936    #[test]
15937    fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
15938        // Consumer-side pin on the three-path convergence:
15939        // [`std::fmt::Display`] agrees byte-for-byte with the
15940        // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
15941        // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
15942        // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
15943        // Pre-lift the two paths were structurally independent — the
15944        // substrate-side gate reached for `target_view.label()` while a
15945        // future downstream diagnostic / graph / audit line reaching
15946        // for `format!("{target}")` would silently land on the `Debug`
15947        // derive's structural output. Pin the two paths byte-for-byte
15948        // here so any future variant addition (M4 `Rest`/`Grpc` split
15949        // of [`WitTarget::Http`], `Queue`-shaped peer of
15950        // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
15951        // match error at [`WitTarget::payload_pair`] rather than a
15952        // silent per-consumer dispatch miss.
15953        for variant in [
15954            WitTarget::Http {
15955                endpoint: "/charge",
15956            },
15957            WitTarget::PubSub {
15958                subject: "events.checkout.paid",
15959            },
15960            WitTarget::Store {
15961                slot: "checkout/$order",
15962            },
15963            WitTarget::Capability,
15964        ] {
15965            assert_eq!(
15966                format!("{variant}"),
15967                variant.label(),
15968                "WitTarget::{variant:?} Display byte-string must match \
15969                 the AplicacaoError::ContratoDuplicate `target:` carrier \
15970                 the AplicacaoSpec::validate duplicate-`:contratos` gate \
15971                 seeds via WitTarget::label — three-path convergence: \
15972                 Display + label + payload_pair all resolve to the same \
15973                 per-arm byte-string"
15974            );
15975        }
15976    }
15977
15978    #[test]
15979    fn wit_target_payload_pair_pins_per_variant() {
15980        // Pin the per-arm `(field-name, payload)` pair single-sourced
15981        // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
15982        // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
15983        // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
15984        // and [`WitTarget::field_name`] (returns the first component)
15985        // route through. Until this lift landed [`WitTarget::label`]
15986        // dispatched on the same three arms with a per-arm
15987        // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
15988        // paired [`WitTarget::HTTP_FIELD_NAME`] /
15989        // [`WitTarget::PUBSUB_FIELD_NAME`] /
15990        // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
15991        // canonical "same shape, written N times" duplication
15992        // THEORY.md §I.3.5 promotes to a build-time concern. A future
15993        // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
15994        // [`WitTarget::Http`], `Queue`-shaped peer of
15995        // [`WitTarget::Store`]) is one match-arm edit at
15996        // [`WitTarget::payload_pair`], visible here as a compile-time
15997        // exhaustiveness error on both this pin and the label-format
15998        // pin above.
15999        assert_eq!(
16000            WitTarget::Http {
16001                endpoint: "/charge"
16002            }
16003            .payload_pair(),
16004            Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
16005        );
16006        assert_eq!(
16007            WitTarget::PubSub {
16008                subject: "events.x",
16009            }
16010            .payload_pair(),
16011            Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
16012        );
16013        assert_eq!(
16014            WitTarget::Store {
16015                slot: "checkout/$order",
16016            }
16017            .payload_pair(),
16018            Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
16019        );
16020        assert_eq!(WitTarget::Capability.payload_pair(), None);
16021    }
16022
16023    #[test]
16024    fn wit_target_field_name_pins_per_variant() {
16025        // Pin the per-arm author-facing `:contratos` payload field
16026        // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
16027        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
16028        // + returned by [`WitTarget::field_name`]. Every downstream
16029        // consumer (the [`WitContract::target`] gate's `expected:`
16030        // scalar, the [`WitTarget::label`] template's keyword prefix,
16031        // the `feira app graph` verb's `endpoint=…` prefix) routes
16032        // through the same three peer consts, so a rename on the
16033        // author-surface `(defcaixa … :contratos ((:de … :para …
16034        // :wit … :endpoint …)))` field lands in exactly one place.
16035        assert_eq!(
16036            WitTarget::Http {
16037                endpoint: "/charge"
16038            }
16039            .field_name(),
16040            Some(WitTarget::HTTP_FIELD_NAME),
16041        );
16042        assert_eq!(
16043            WitTarget::PubSub {
16044                subject: "events.x",
16045            }
16046            .field_name(),
16047            Some(WitTarget::PUBSUB_FIELD_NAME),
16048        );
16049        assert_eq!(
16050            WitTarget::Store {
16051                slot: "checkout/$order",
16052            }
16053            .field_name(),
16054            Some(WitTarget::STORE_FIELD_NAME),
16055        );
16056        // Capability arm carries no payload field — the diagnostic
16057        // never reports `expected: "capability"` because the gate's
16058        // Capability arm accepts no payload at all (it fires the
16059        // "expected: none" WrongTarget error instead), so the field-
16060        // name method returns None here rather than a placeholder.
16061        assert_eq!(WitTarget::Capability.field_name(), None);
16062
16063        // Peer const scalar values pinned so a rename on either side
16064        // (author-surface field name in the `(defcaixa …)` DSL, or
16065        // the diagnostic's `expected:` scalar) can't drift without
16066        // failing here first.
16067        assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
16068        assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
16069        assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
16070    }
16071
16072    #[test]
16073    fn wit_target_payload_pins_per_variant() {
16074        // Pin the per-arm payload scalar single-sourced onto the
16075        // [`WitTarget::payload_pair`] 4-arm dispatch and surfaced through
16076        // [`WitTarget::payload`] — the peer per-half projection to
16077        // [`WitTarget::field_name`] on the paired sub-selector axis. The
16078        // three payload-carrying arms round-trip their author-declared
16079        // scalar verbatim (`Http` → `Some("/charge")`, `PubSub` →
16080        // `Some("events.x")`, `Store` → `Some("checkout/$order")`) and
16081        // the payload-less [`WitTarget::Capability`] arm returns `None`.
16082        // Same shape as the sibling `wit_target_field_name_pins_per_variant`
16083        // (c6ec2af) pin on the Component-0 projection axis, extended
16084        // onto the Component-1 projection axis so both per-half readers
16085        // on the paired dispatch carry their own byte-shape pin.
16086        assert_eq!(
16087            WitTarget::Http {
16088                endpoint: "/charge",
16089            }
16090            .payload(),
16091            Some("/charge"),
16092        );
16093        assert_eq!(
16094            WitTarget::PubSub {
16095                subject: "events.x",
16096            }
16097            .payload(),
16098            Some("events.x"),
16099        );
16100        assert_eq!(
16101            WitTarget::Store {
16102                slot: "checkout/$order",
16103            }
16104            .payload(),
16105            Some("checkout/$order"),
16106        );
16107        assert_eq!(WitTarget::Capability.payload(), None);
16108    }
16109
16110    #[test]
16111    fn wit_target_payload_matches_payload_pair_second_component_per_variant() {
16112        // Per-variant equivalence pin: for every arm of [`WitTarget`],
16113        // `.payload()` equals `.payload_pair().map(|(_, p)| p)`
16114        // byte-for-byte. Guards the drift surface where a future refactor
16115        // that split one accessor off the shared match onto its own
16116        // dispatch — a well-meaning "inline the pair back into per-half
16117        // fields for one crate-internal caller who only wanted one half"
16118        // or a scratch `impl` shadowing the derived projection — would
16119        // silently desynchronize [`WitTarget::payload`] from the
16120        // authoritative [`WitTarget::payload_pair`] dispatch, and every
16121        // downstream consumer that thinks "the payload half of the pair"
16122        // would drift from the diagnostic / graph consumers reading the
16123        // same match through [`WitTarget::label`] / [`WitTarget::graph_label`].
16124        // Sibling to the peer [`caixa_flux::GitRefSpec`] `ref_value`
16125        // per-half projection pin (`gitrefspec_ref_pair_projects_
16126        // ref_field_name_and_ref_value_per_variant`, 655a1c0) on the
16127        // FluxCD source-controller `spec.ref.<field>` axis — same "one
16128        // paired dispatch, both per-half projections agree byte-for-
16129        // byte" discipline extended onto the M3 `:contratos` payload-
16130        // arm surface.
16131        for variant in [
16132            WitTarget::Http {
16133                endpoint: "/charge",
16134            },
16135            WitTarget::PubSub {
16136                subject: "events.checkout.paid",
16137            },
16138            WitTarget::Store {
16139                slot: "checkout/$order",
16140            },
16141            WitTarget::Capability,
16142        ] {
16143            let via_projection = variant.payload();
16144            let via_pair = variant.payload_pair().map(|(_, p)| p);
16145            assert_eq!(
16146                via_projection, via_pair,
16147                "WitTarget::{variant:?} payload() must equal \
16148                 payload_pair().map(|(_, p)| p) byte-for-byte — a \
16149                 regression that splits the two per-half projections off \
16150                 their shared match would silently desynchronize the \
16151                 payload accessor from the paired dispatch every \
16152                 diagnostic / graph consumer reads through",
16153            );
16154        }
16155    }
16156
16157    #[test]
16158    fn wit_target_http_endpoint_pins_per_variant() {
16159        // Pin the per-arm HTTP-endpoint scalar single-sourced onto the
16160        // [`WitTarget::http_endpoint`] 2-arm dispatch — the
16161        // substrate-primitive per-arm post-projection accessor every
16162        // L7-HTTP-facing consumer routes through, sibling to the peer
16163        // WitContract pre-projection [`WitContract::endpoint`] (7020470)
16164        // scalar accessor on the raw-field axis. The [`WitTarget::Http`]
16165        // arm round-trips its author-declared endpoint verbatim as
16166        // `Some("/charge")`; the three sibling arms
16167        // ([`WitTarget::PubSub`] / [`WitTarget::Store`] /
16168        // [`WitTarget::Capability`]) each return `None` because they
16169        // carry no HTTP endpoint by definition. Same fail-before-pass-
16170        // after per-variant discipline as the sibling
16171        // `wit_target_payload_pins_per_variant` (5d6dc92) /
16172        // `wit_target_field_name_pins_per_variant` (c6ec2af) /
16173        // `wit_target_payload_pair_pins_per_variant` (6788ed6) pins on
16174        // the peer pan-arm / per-half projection axes — extended onto
16175        // the per-arm HTTP-shape post-projection axis so a future
16176        // [`WitTarget`] variant addition (a `Rest`/`Grpc` split of
16177        // [`WitTarget::Http`], a `Queue`-shaped peer of
16178        // [`WitTarget::Store`]) trips a compile-time exhaustiveness
16179        // error on the sibling [`WitTarget::http_endpoint`] match arms
16180        // whose payload the L7-HTTP-shape accept-set is meant to bound.
16181        assert_eq!(
16182            WitTarget::Http {
16183                endpoint: "/charge",
16184            }
16185            .http_endpoint(),
16186            Some("/charge"),
16187        );
16188        assert_eq!(
16189            WitTarget::PubSub {
16190                subject: "events.checkout.paid",
16191            }
16192            .http_endpoint(),
16193            None,
16194        );
16195        assert_eq!(
16196            WitTarget::Store {
16197                slot: "checkout/$order",
16198            }
16199            .http_endpoint(),
16200            None,
16201        );
16202        assert_eq!(WitTarget::Capability.http_endpoint(), None);
16203    }
16204
16205    #[test]
16206    fn wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere() {
16207        // Per-variant coherence pin: for every arm of [`WitTarget`],
16208        // `.http_endpoint()` equals `.payload()` on the [`WitTarget::Http`]
16209        // arm (both project the same author-declared request-path
16210        // scalar), and returns `None` on every sibling arm regardless of
16211        // whether [`WitTarget::payload`] itself returns `Some` (PubSub /
16212        // Store carry their own payload the pan-arm accessor surfaces,
16213        // but that payload is not an HTTP endpoint — the per-arm
16214        // accessor must not leak it through the HTTP-shape channel).
16215        // Guards the drift surface where a future refactor that
16216        // conflated the per-arm HTTP projection with the pan-arm
16217        // [`WitTarget::payload`] projection — a well-meaning "one
16218        // accessor for the L7 branch, one for the graph" collapse that
16219        // routes both through the same 4-arm dispatch — would silently
16220        // widen the L7-HTTP-shape accept-set onto pub-sub / store
16221        // payloads at the caixa-mesh L7 emit branch, admitting a
16222        // `nats:pub-sub` edge's `:subject` as a Cilium L7 HTTP `path:`
16223        // rule with the operator-side apply-time symptom (Cilium's
16224        // eBPF data-plane rejects every ingress edge whose L7 filter
16225        // doesn't match the wire-format HTTP request line) far from
16226        // the source refactor. Sibling to the peer
16227        // `wit_target_payload_matches_payload_pair_second_component_
16228        // per_variant` (5d6dc92) coherence pin on the pan-arm axis —
16229        // extended onto the per-arm HTTP specialization axis so both
16230        // the pan-arm and the per-arm projections carry their own
16231        // byte-shape coherence witness against the substrate's typed
16232        // arm-family accept-set.
16233        for variant in [
16234            WitTarget::Http {
16235                endpoint: "/charge",
16236            },
16237            WitTarget::PubSub {
16238                subject: "events.checkout.paid",
16239            },
16240            WitTarget::Store {
16241                slot: "checkout/$order",
16242            },
16243            WitTarget::Capability,
16244        ] {
16245            let per_arm = variant.http_endpoint();
16246            let pan_arm = variant.payload();
16247            if variant.is_http() {
16248                assert_eq!(
16249                    per_arm, pan_arm,
16250                    "WitTarget::{variant:?} http_endpoint() must equal \
16251                     payload() on the Http arm — a per-arm-vs-pan-arm \
16252                     split would silently drift the L7 emit branch's \
16253                     path-scalar source from the graph verb's payload \
16254                     scalar source",
16255                );
16256            } else {
16257                assert_eq!(
16258                    per_arm, None,
16259                    "WitTarget::{variant:?} http_endpoint() must return \
16260                     None on non-Http arms — a leak that surfaced a \
16261                     pub-sub :subject or a key/value :slot through the \
16262                     HTTP-endpoint accessor would silently widen the \
16263                     Cilium L7 HTTP `path:` rule accept-set onto \
16264                     protocol shapes Cilium's eBPF data-plane can't \
16265                     introspect",
16266                );
16267            }
16268        }
16269    }
16270
16271    #[test]
16272    fn wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant() {
16273        // Per-variant coherence pin: for every arm of [`WitTarget`],
16274        // `.http_endpoint().is_some()` iff `.is_http()`. Guards the
16275        // drift surface where a future extension of the
16276        // [`WitTarget::http_endpoint`] accessor's accept-set (e.g. a
16277        // `Rest`/`Grpc` split of [`WitTarget::Http`] that widened the
16278        // accessor to cover both peers) landed without a paired
16279        // extension of the [`gen_platform::IsVariant`]-derived
16280        // `is_http()` predicate's accept-set, or vice versa — a
16281        // regression that split the "which arms count as HTTP-shaped
16282        // for L7-path emission?" answer between two dispatch surfaces
16283        // the substrate ships. Sibling to the peer
16284        // `wit_target_field_name_pins_per_variant` (c6ec2af) discipline
16285        // on the paired dispatch axis — extended onto the per-arm
16286        // predicate-vs-accessor coherence axis so the gen-platform
16287        // IsVariant predicate and the substrate-lifted per-arm
16288        // accessor carry one shared answer to "is this the HTTP arm?".
16289        for variant in [
16290            WitTarget::Http {
16291                endpoint: "/charge",
16292            },
16293            WitTarget::PubSub {
16294                subject: "events.checkout.paid",
16295            },
16296            WitTarget::Store {
16297                slot: "checkout/$order",
16298            },
16299            WitTarget::Capability,
16300        ] {
16301            assert_eq!(
16302                variant.http_endpoint().is_some(),
16303                variant.is_http(),
16304                "WitTarget::{variant:?} http_endpoint().is_some() must \
16305                 equal is_http() — a drift would split the L7 emit \
16306                 branch's arm-set gate from the substrate-derived \
16307                 shape-discrimination predicate on the same axis",
16308            );
16309        }
16310    }
16311
16312    #[test]
16313    fn wit_target_pubsub_subject_pins_per_variant() {
16314        // Fail-before-pass-after pin: the substrate-canonical per-arm
16315        // pub-sub-subject scalar accessor [`WitTarget::pubsub_subject`]
16316        // is the single dispatch every future pub-sub-facing consumer
16317        // routes through, sibling to the peer [`WitContract::subject`]
16318        // (63e18a0) pre-projection scalar accessor on the raw-field
16319        // axis and to the peer [`WitTarget::http_endpoint`] (5d6dc92)
16320        // post-projection per-arm accessor on the sibling HTTP-shape
16321        // axis. The [`WitTarget::PubSub`] arm round-trips its
16322        // author-declared subject verbatim as
16323        // `Some("events.checkout.paid")`; the three sibling arms each
16324        // return `None` because they carry no NATS-shaped subject by
16325        // definition. Same fail-before-pass-after per-variant discipline
16326        // as the sibling `wit_target_http_endpoint_pins_per_variant`
16327        // pin on the peer per-arm axis — extended onto the per-arm
16328        // pub-sub-shape post-projection axis so a future [`WitTarget`]
16329        // variant addition (a `Rest`/`Grpc` split of [`WitTarget::Http`],
16330        // a `Queue`-shaped peer of [`WitTarget::Store`]) trips a
16331        // compile-time exhaustiveness error on the sibling
16332        // [`WitTarget::pubsub_subject`] match arms whose payload the
16333        // pub-sub-shape accept-set is meant to bound.
16334        assert_eq!(
16335            WitTarget::PubSub {
16336                subject: "events.checkout.paid",
16337            }
16338            .pubsub_subject(),
16339            Some("events.checkout.paid"),
16340        );
16341        assert_eq!(
16342            WitTarget::Http {
16343                endpoint: "/charge",
16344            }
16345            .pubsub_subject(),
16346            None,
16347        );
16348        assert_eq!(
16349            WitTarget::Store {
16350                slot: "checkout/$order",
16351            }
16352            .pubsub_subject(),
16353            None,
16354        );
16355        assert_eq!(WitTarget::Capability.pubsub_subject(), None);
16356    }
16357
16358    #[test]
16359    fn wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere() {
16360        // Per-variant coherence pin: for every arm of [`WitTarget`],
16361        // `.pubsub_subject()` equals `.payload()` on the
16362        // [`WitTarget::PubSub`] arm (both project the same
16363        // author-declared subject scalar), and returns `None` on every
16364        // sibling arm regardless of whether [`WitTarget::payload`]
16365        // itself returns `Some` (Http / Store carry their own payload
16366        // the pan-arm accessor surfaces, but that payload is not a
16367        // pub-sub subject — the per-arm accessor must not leak it
16368        // through the pub-sub-shape channel). Sibling to the peer
16369        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
16370        // coherence pin on the per-arm HTTP-shape axis — extended onto
16371        // the per-arm pub-sub specialization axis so both per-arm
16372        // projections carry their own byte-shape coherence witness
16373        // against the substrate's typed arm-family accept-set.
16374        for variant in [
16375            WitTarget::Http {
16376                endpoint: "/charge",
16377            },
16378            WitTarget::PubSub {
16379                subject: "events.checkout.paid",
16380            },
16381            WitTarget::Store {
16382                slot: "checkout/$order",
16383            },
16384            WitTarget::Capability,
16385        ] {
16386            let per_arm = variant.pubsub_subject();
16387            let pan_arm = variant.payload();
16388            if variant.is_pubsub() {
16389                assert_eq!(
16390                    per_arm, pan_arm,
16391                    "WitTarget::{variant:?} pubsub_subject() must equal \
16392                     payload() on the PubSub arm — a per-arm-vs-pan-arm \
16393                     split would silently drift the pub-sub-shape emit \
16394                     branch's subject-scalar source from the graph verb's \
16395                     payload scalar source",
16396                );
16397            } else {
16398                assert_eq!(
16399                    per_arm, None,
16400                    "WitTarget::{variant:?} pubsub_subject() must return \
16401                     None on non-PubSub arms — a leak that surfaced an \
16402                     HTTP :endpoint or a key/value :slot through the \
16403                     pub-sub-subject accessor would silently widen the \
16404                     downstream NATS-shape accept-set onto protocol \
16405                     shapes NATS servers can't route",
16406                );
16407            }
16408        }
16409    }
16410
16411    #[test]
16412    fn wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant() {
16413        // Per-variant coherence pin: for every arm of [`WitTarget`],
16414        // `.pubsub_subject().is_some()` iff `.is_pubsub()`. Guards the
16415        // drift surface where a future extension of the
16416        // [`WitTarget::pubsub_subject`] accessor's accept-set landed
16417        // without a paired extension of the [`gen_platform::IsVariant`]-
16418        // derived `is_pubsub()` predicate's accept-set, or vice versa
16419        // — a regression that split the "which arms count as pub-sub-
16420        // shaped for subject emission?" answer between two dispatch
16421        // surfaces the substrate ships. Sibling to the peer
16422        // `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
16423        // pin on the per-arm HTTP-shape axis — extended onto the
16424        // per-arm pub-sub predicate-vs-accessor coherence axis so the
16425        // gen-platform IsVariant predicate and the substrate-lifted
16426        // per-arm accessor carry one shared answer to "is this the
16427        // PubSub arm?".
16428        for variant in [
16429            WitTarget::Http {
16430                endpoint: "/charge",
16431            },
16432            WitTarget::PubSub {
16433                subject: "events.checkout.paid",
16434            },
16435            WitTarget::Store {
16436                slot: "checkout/$order",
16437            },
16438            WitTarget::Capability,
16439        ] {
16440            assert_eq!(
16441                variant.pubsub_subject().is_some(),
16442                variant.is_pubsub(),
16443                "WitTarget::{variant:?} pubsub_subject().is_some() must \
16444                 equal is_pubsub() — a drift would split the pub-sub \
16445                 emit branch's arm-set gate from the substrate-derived \
16446                 shape-discrimination predicate on the same axis",
16447            );
16448        }
16449    }
16450
16451    #[test]
16452    fn wit_target_store_slot_pins_per_variant() {
16453        // Fail-before-pass-after pin: the substrate-canonical per-arm
16454        // key/value-store-slot scalar accessor [`WitTarget::store_slot`]
16455        // is the single dispatch every future store-facing consumer
16456        // routes through, sibling to the peer [`WitContract::slot`]
16457        // pre-projection scalar accessor on the raw-field axis and to
16458        // the peer [`WitTarget::http_endpoint`] (5d6dc92) +
16459        // [`WitTarget::pubsub_subject`] post-projection per-arm
16460        // accessors on the sibling per-payload-arm axes. The
16461        // [`WitTarget::Store`] arm round-trips its author-declared
16462        // slot verbatim as `Some("checkout/$order")`; the three
16463        // sibling arms each return `None` because they carry no
16464        // WASI-key/value slot by definition. Same fail-before-pass-
16465        // after per-variant discipline as the sibling
16466        // `wit_target_http_endpoint_pins_per_variant` +
16467        // `wit_target_pubsub_subject_pins_per_variant` pins on the
16468        // peer per-arm axes — extended onto the per-arm store-shape
16469        // post-projection axis so a future [`WitTarget`] variant
16470        // addition trips a compile-time exhaustiveness error on the
16471        // sibling [`WitTarget::store_slot`] match arms whose payload
16472        // the store-shape accept-set is meant to bound.
16473        assert_eq!(
16474            WitTarget::Store {
16475                slot: "checkout/$order",
16476            }
16477            .store_slot(),
16478            Some("checkout/$order"),
16479        );
16480        assert_eq!(
16481            WitTarget::Http {
16482                endpoint: "/charge",
16483            }
16484            .store_slot(),
16485            None,
16486        );
16487        assert_eq!(
16488            WitTarget::PubSub {
16489                subject: "events.checkout.paid",
16490            }
16491            .store_slot(),
16492            None,
16493        );
16494        assert_eq!(WitTarget::Capability.store_slot(), None);
16495    }
16496
16497    #[test]
16498    fn wit_target_store_slot_matches_payload_on_store_arm_and_is_none_elsewhere() {
16499        // Per-variant coherence pin: for every arm of [`WitTarget`],
16500        // `.store_slot()` equals `.payload()` on the
16501        // [`WitTarget::Store`] arm (both project the same
16502        // author-declared slot scalar), and returns `None` on every
16503        // sibling arm regardless of whether [`WitTarget::payload`]
16504        // itself returns `Some`. Sibling to the peer
16505        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
16506        // and `wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere`
16507        // pins on the per-arm HTTP and PubSub axes — closes the
16508        // per-arm-vs-pan-arm byte-shape coherence trio across all
16509        // three payload arms.
16510        for variant in [
16511            WitTarget::Http {
16512                endpoint: "/charge",
16513            },
16514            WitTarget::PubSub {
16515                subject: "events.checkout.paid",
16516            },
16517            WitTarget::Store {
16518                slot: "checkout/$order",
16519            },
16520            WitTarget::Capability,
16521        ] {
16522            let per_arm = variant.store_slot();
16523            let pan_arm = variant.payload();
16524            if variant.is_store() {
16525                assert_eq!(
16526                    per_arm, pan_arm,
16527                    "WitTarget::{variant:?} store_slot() must equal \
16528                     payload() on the Store arm — a per-arm-vs-pan-arm \
16529                     split would silently drift the store-shape emit \
16530                     branch's slot-scalar source from the graph verb's \
16531                     payload scalar source",
16532                );
16533            } else {
16534                assert_eq!(
16535                    per_arm, None,
16536                    "WitTarget::{variant:?} store_slot() must return \
16537                     None on non-Store arms — a leak that surfaced an \
16538                     HTTP :endpoint or a NATS :subject through the \
16539                     key/value-slot accessor would silently widen the \
16540                     downstream WASI-key/value slot accept-set onto \
16541                     protocol shapes the kv backends can't route",
16542                );
16543            }
16544        }
16545    }
16546
16547    #[test]
16548    fn wit_target_store_slot_agrees_with_is_store_predicate_per_variant() {
16549        // Per-variant coherence pin: for every arm of [`WitTarget`],
16550        // `.store_slot().is_some()` iff `.is_store()`. Guards the
16551        // drift surface where a future extension of the
16552        // [`WitTarget::store_slot`] accessor's accept-set landed
16553        // without a paired extension of the [`gen_platform::IsVariant`]-
16554        // derived `is_store()` predicate's accept-set. Sibling to the
16555        // peer `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
16556        // and `wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant`
16557        // pins — closes the per-arm predicate-vs-accessor coherence
16558        // trio across all three payload arms so the gen-platform
16559        // IsVariant predicate and the substrate-lifted per-arm
16560        // accessor carry one shared answer to "is this the Store arm?".
16561        for variant in [
16562            WitTarget::Http {
16563                endpoint: "/charge",
16564            },
16565            WitTarget::PubSub {
16566                subject: "events.checkout.paid",
16567            },
16568            WitTarget::Store {
16569                slot: "checkout/$order",
16570            },
16571            WitTarget::Capability,
16572        ] {
16573            assert_eq!(
16574                variant.store_slot().is_some(),
16575                variant.is_store(),
16576                "WitTarget::{variant:?} store_slot().is_some() must \
16577                 equal is_store() — a drift would split the store-shape \
16578                 emit branch's arm-set gate from the substrate-derived \
16579                 shape-discrimination predicate on the same axis",
16580            );
16581        }
16582    }
16583
16584    #[test]
16585    fn wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set() {
16586        // Fail-before-pass-after cross-axis pin on the trio
16587        // (`http_endpoint`, `pubsub_subject`, `store_slot`): on every
16588        // payload-carrying arm of [`WitTarget`], exactly one per-arm
16589        // accessor returns `Some(payload)` and the two peers return
16590        // `None`; and on the payload-less [`WitTarget::Capability`]
16591        // arm, all three return `None`. Guards the drift surface where
16592        // a future extension of one per-arm accessor's accept-set (e.g.
16593        // a hypothetical `Rest`/`Grpc` split of [`WitTarget::Http`]
16594        // that widened `http_endpoint` to cover both peers without
16595        // narrowing the peer `pubsub_subject` / `store_slot` accept-
16596        // sets to keep the partition mutually exclusive) landed without
16597        // threading through the peer per-arm accessors — the resulting
16598        // silent overlap would land the same edge's payload on two
16599        // downstream per-shape emit branches at once, or leak a
16600        // pub-sub subject through the store-slot channel, at renderer
16601        // emit time far from the substrate primitive's arm-widening
16602        // commit. Peer of the sibling `wit_target_field_names_are_pairwise_distinct`
16603        // 3-way pin on the payload-field-name axis — extended onto the
16604        // per-arm-accessor payload-projection axis so the substrate-
16605        // owned partition invariant is load-bearing at every per-arm
16606        // consumer's read site.
16607        let payload_variants = [
16608            (
16609                WitTarget::Http {
16610                    endpoint: "/charge",
16611                },
16612                "http",
16613            ),
16614            (
16615                WitTarget::PubSub {
16616                    subject: "events.checkout.paid",
16617                },
16618                "pubsub",
16619            ),
16620            (
16621                WitTarget::Store {
16622                    slot: "checkout/$order",
16623                },
16624                "store",
16625            ),
16626        ];
16627        for (variant, own_arm_label) in payload_variants {
16628            let own_arm_hit = match own_arm_label {
16629                "http" => variant.is_http(),
16630                "pubsub" => variant.is_pubsub(),
16631                "store" => variant.is_store(),
16632                other => panic!("unknown own-arm label {other:?}"),
16633            };
16634            let per_arm_results = [
16635                ("http_endpoint", variant.http_endpoint()),
16636                ("pubsub_subject", variant.pubsub_subject()),
16637                ("store_slot", variant.store_slot()),
16638            ];
16639            let some_count = per_arm_results.iter().filter(|(_, v)| v.is_some()).count();
16640            assert_eq!(
16641                some_count, 1,
16642                "WitTarget::{variant:?} must land exactly one per-arm \
16643                 post-projection accessor's Some result — the trio \
16644                 (http_endpoint, pubsub_subject, store_slot) must \
16645                 partition the payload arm-set; got {per_arm_results:?}",
16646            );
16647            assert!(
16648                own_arm_hit,
16649                "WitTarget::{variant:?} own-arm gen-platform predicate \
16650                 must return true on its own arm — a partition failure \
16651                 upstream of this pin",
16652            );
16653            assert!(
16654                variant.payload().is_some(),
16655                "WitTarget::{variant:?} pan-arm payload() must return \
16656                 Some on every payload-carrying arm the trio partitions",
16657            );
16658        }
16659        // The payload-less Capability arm must return None on every
16660        // per-arm accessor — the partition's terminal-fallback shape.
16661        let cap = WitTarget::Capability;
16662        assert_eq!(cap.http_endpoint(), None);
16663        assert_eq!(cap.pubsub_subject(), None);
16664        assert_eq!(cap.store_slot(), None);
16665        assert_eq!(
16666            cap.payload(),
16667            None,
16668            "WitTarget::Capability pan-arm payload() must return None — \
16669             the trio's payload-less-arm coherence witness",
16670        );
16671    }
16672
16673    #[test]
16674    fn wit_target_field_names_are_pairwise_distinct() {
16675        // Distinctness pin: if any two of the three payload-field-name
16676        // scalars ever collapse (e.g. an accidental `endpoint` copy-
16677        // paste over the `subject` const), the [`WitContract::target`]
16678        // gate's diagnostic would point authors at the wrong field —
16679        // an "expected `:endpoint`" error on a pub-sub edge would
16680        // silently misroute the fix. Same cross-axis-distinctness
16681        // discipline as the peer M3 `:placement :estrategia` variant-
16682        // discriminator scalar-value pins (cc8f749) applied to the
16683        // payload-field-name axis.
16684        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
16685        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
16686        assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
16687    }
16688
16689    #[test]
16690    fn wit_target_graph_label_routes_through_payload_pair_on_payload_arms() {
16691        // Fail-before-pass-after pin: the graph-verb payload column's
16692        // per-arm `{field}={payload}` byte-string is derived through the
16693        // single [`WitTarget::payload_pair`] 4-arm dispatch on the three
16694        // payload-carrying arms, not through a hand-rolled per-arm match
16695        // that re-projects [`WitTarget::HTTP_FIELD_NAME`] /
16696        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
16697        // inline. A future variant addition — the M4-and-later per-edge
16698        // WIT registry may split [`WitTarget::Http`] into `Rest` / `Grpc`
16699        // peers, or extend [`WitTarget::Store`] with a `Queue`-shaped
16700        // peer — becomes one match-arm edit at [`WitTarget::payload_pair`],
16701        // and both [`WitTarget::label`] (duplicate-`:contratos`
16702        // diagnostic) and [`WitTarget::graph_label`] (`feira app graph`
16703        // payload column) pick up the new arm from the same dispatch.
16704        // Prior to this lift the graph verb open-coded the 4-arm match
16705        // in caixa-feira, so a variant addition would have to be threaded
16706        // through both projections in lockstep or the graph verb would
16707        // silently drop the new arm to `(capability-only)`.
16708        for variant in [
16709            WitTarget::Http {
16710                endpoint: "/charge",
16711            },
16712            WitTarget::PubSub {
16713                subject: "events.checkout.paid",
16714            },
16715            WitTarget::Store {
16716                slot: "checkout/$order",
16717            },
16718        ] {
16719            let (field, payload) = variant
16720                .payload_pair()
16721                .expect("payload arm must expose (field, payload)");
16722            assert_eq!(
16723                variant.graph_label(),
16724                format!("{field}={payload}"),
16725                "WitTarget::{variant:?} graph_label must route the \
16726                 `{{field}}={{payload}}` template through payload_pair — \
16727                 a regression to a hand-rolled per-arm match at the graph \
16728                 verb would silently disagree with a future variant \
16729                 addition landed only at payload_pair"
16730            );
16731        }
16732    }
16733
16734    #[test]
16735    fn wit_target_graph_label_returns_capability_graph_label_const_on_capability_arm() {
16736        // Fail-before-pass-after pin on the payload-less arm: the graph
16737        // verb's `(capability-only)` byte-string routes through the
16738        // lifted [`WitTarget::CAPABILITY_GRAPH_LABEL`] const on the
16739        // [`WitTarget::Capability`] arm, not through an inline
16740        // `.to_string()` literal at the caixa-feira `cmd::app::GraphArgs::run`
16741        // per-`:contratos` payload column. Peer of the sibling
16742        // [`wit_target_label_pins_per_variant_format`] Capability-arm
16743        // assertion on the [`WitTarget::CAPABILITY_LABEL`] const —
16744        // extended here onto the third payload-less-arm consumer axis
16745        // (graph verb, sibling to the duplicate-`:contratos` diagnostic
16746        // axis and the wrong-target diagnostic axis).
16747        assert_eq!(
16748            WitTarget::Capability.graph_label(),
16749            WitTarget::CAPABILITY_GRAPH_LABEL,
16750        );
16751        assert_eq!(WitTarget::CAPABILITY_GRAPH_LABEL, "(capability-only)");
16752    }
16753
16754    #[test]
16755    fn wit_target_capability_graph_label_distinct_from_capability_label() {
16756        // Cross-consumer-axis distinctness pin: the graph-verb
16757        // payload-column const [`WitTarget::CAPABILITY_GRAPH_LABEL`]
16758        // (`(capability-only)`) and the duplicate-`:contratos` diagnostic
16759        // label const [`WitTarget::CAPABILITY_LABEL`] (`(capability — no
16760        // payload)`) surface the payload-less arm on two distinct
16761        // consumer axes; a collapse (an accidental rebrand that lands
16762        // one spelling on both consts, a copy-paste that unifies them
16763        // "for consistency") would silently merge the two byte-strings
16764        // and lose the vocabulary distinction the graph verb's
16765        // compact-column form and the diagnostic's descriptive-clause
16766        // form each carry on purpose. Peer of the sibling 4-way
16767        // [`wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`]
16768        // pin on the `ContratoWrongTarget::expected` scalar-value axis —
16769        // extended here onto the cross-consumer-axis distinctness of the
16770        // two payload-less-arm consts.
16771        assert_ne!(
16772            WitTarget::CAPABILITY_GRAPH_LABEL,
16773            WitTarget::CAPABILITY_LABEL,
16774            "WitTarget::CAPABILITY_GRAPH_LABEL (graph-verb payload column) \
16775             and WitTarget::CAPABILITY_LABEL (duplicate-`:contratos` \
16776             diagnostic) must remain distinct — a collapse would silently \
16777             merge two consumer axes onto one spelling"
16778        );
16779    }
16780
16781    #[test]
16782    fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
16783        // 4-way distinctness pin extending the sibling
16784        // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
16785        // (which covers only the HTTP / PubSub / Store payload arms)
16786        // onto the fourth scalar the shared
16787        // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
16788        // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
16789        // (`"none"`), the payload-less Capability-arm rejection scalar.
16790        //
16791        // All four [`WitTarget::HTTP_FIELD_NAME`] /
16792        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
16793        // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
16794        // dispatch surface [`WitContract::target`] writes onto the
16795        // `ContratoWrongTarget::expected` field — the same `&'static
16796        // str` axis authors read as "this WIT world's shape admits
16797        // (only|not) `:<field>`". Pairwise-distinctness is the invariant
16798        // downstream consumers rely on: an `expected: "endpoint"`
16799        // diagnostic on a Capability-shaped edge tells the author to
16800        // add a `:endpoint "…"` slot to a WIT world that admits none,
16801        // silently misrouting the fix. Until this pin landed the three
16802        // payload-arm consts were distinctness-guarded by the sibling
16803        // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
16804        // scalar (d4f54f2) sat unguarded — a rebrand collision (the
16805        // author-facing vocabulary shift from `"none"` to `"endpoint"`
16806        // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
16807        // into per-shape peers) would have silently landed one
16808        // Capability-arm rejection on a payload-arm's `expected:` byte-
16809        // string and desynchronized the diagnostic from the author's
16810        // typed shape.
16811        //
16812        // Same 4-way pairwise-distinctness pin discipline as the peer
16813        // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
16814        // (cc8f749) applies on the sibling M3 closed-set typed-enum
16815        // scalar-value dispatch axis; extends the pin trajectory the
16816        // sibling `wit_target_field_names_are_pairwise_distinct`
16817        // 3-way pin opened to cover the last unguarded corner on the
16818        // `ContratoWrongTarget::expected` scalar-value axis.
16819        //
16820        // Fail-before-pass-after locally verified by mutating
16821        // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
16822        // — this pin fires as expected; restoring passes.
16823        let all = [
16824            WitTarget::HTTP_FIELD_NAME,
16825            WitTarget::PUBSUB_FIELD_NAME,
16826            WitTarget::STORE_FIELD_NAME,
16827            WitTarget::CAPABILITY_EXPECTED,
16828        ];
16829        for (i, a) in all.iter().enumerate() {
16830            for (j, b) in all.iter().enumerate() {
16831                if i != j {
16832                    assert_ne!(
16833                        a, b,
16834                        "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
16835                         STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
16836                         pairwise distinct — got duplicate {a:?} at indices \
16837                         {i} and {j}; all four scalars thread through the \
16838                         shared `AplicacaoError::ContratoWrongTarget::expected` \
16839                         &'static str axis, so a collapse silently misdirects \
16840                         the diagnostic on which typed shape the WIT world admits",
16841                    );
16842                }
16843            }
16844        }
16845    }
16846
16847    #[test]
16848    fn wit_target_is_variant_predicates_partition_the_arm_set() {
16849        // Fail-before-pass-after pin on the
16850        // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
16851        // each of the four variants exactly one of the generated
16852        // `is_http` / `is_pubsub` / `is_store` / `is_capability`
16853        // predicates returns `true` and the other three return
16854        // `false`. Prior to this derive the only production
16855        // arm-discriminator on [`WitTarget`] — the sync-cycle
16856        // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
16857        // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
16858        // the variant that expressed no compile-time link back to
16859        // the closed-set typed dispatch a future fifth
16860        // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
16861        // split of [`WitTarget::PubSub`] into shape-specific peers,
16862        // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
16863        // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
16864        // to thread through in lockstep or the DFS exclusion would
16865        // silently disagree with the peer diagnostic templates on
16866        // which arms carry sync-versus-async semantics. Peer of the
16867        // sibling [`crate::CaixaKind`] (f5bba80),
16868        // [`PlacementStrategy`] (766ec63),
16869        // [`crate::supervisor::RestartStrategy`],
16870        // [`crate::supervisor::RestartPolicy`], and
16871        // [`crate::upgrade::UpgradeInstruction`] (915a934)
16872        // `IsVariant` derives on the sibling closed-set typed-enum
16873        // discriminator axes — extends the same one-typed-dispatch-
16874        // per-variant discipline onto the last unlifted closed-set
16875        // typed-enum discriminator on the caixa surface (the M3
16876        // mesh-slot per-`:contratos` target-arm axis), closing the
16877        // arm-discriminator convergence trajectory across every
16878        // closed-set typed enum in caixa-core.
16879        let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
16880            (
16881                WitTarget::Http { endpoint: "/x" },
16882                [true, false, false, false],
16883            ),
16884            (
16885                WitTarget::PubSub {
16886                    subject: "events.x",
16887                },
16888                [false, true, false, false],
16889            ),
16890            (
16891                WitTarget::Store { slot: "kv/x" },
16892                [false, false, true, false],
16893            ),
16894            (WitTarget::Capability, [false, false, false, true]),
16895        ];
16896        for (variant, expected) in rows {
16897            let observed = [
16898                variant.is_http(),
16899                variant.is_pubsub(),
16900                variant.is_store(),
16901                variant.is_capability(),
16902            ];
16903            assert_eq!(
16904                observed, expected,
16905                "WitTarget::{variant:?} is_* predicates must partition \
16906                 the arm set (http, pubsub, store, capability); got {observed:?}"
16907            );
16908        }
16909    }
16910
16911    #[test]
16912    fn wit_target_is_variant_predicates_are_const_fn() {
16913        // The [`gen_platform::IsVariant`] derive emits `const fn`
16914        // predicates on the peer [`crate::CaixaKind`] +
16915        // [`crate::upgrade::UpgradeInstruction`] +
16916        // [`crate::supervisor::RestartStrategy`] +
16917        // [`crate::supervisor::RestartPolicy`] +
16918        // [`PlacementStrategy`] closed-set typed enums — pin the
16919        // same posture on [`WitTarget`] so a future accidental
16920        // downgrade to non-`const` (an added runtime helper reachable
16921        // only from a non-`const` context, a manual hand-rolled
16922        // `impl` that shadows the derive-generated method) trips at
16923        // caixa-core build time rather than surfacing as a downstream
16924        // `const`-context regression far from the derive declaration.
16925        //
16926        // Unlike the peer unit-variant enums (`CaixaKind` /
16927        // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
16928        // whose `const` constructors need no arguments, the three
16929        // payload-carrying [`WitTarget`] arms are const-constructed
16930        // through `&'static str` payloads — the same `'static`
16931        // lifetime the closed-set typed enum's four-arm partition
16932        // pin above already threads through.
16933        //
16934        // The pin lives inside a `const { assert!(..) }` block so the
16935        // compiler enforces both halves (arm predicate is `const`-
16936        // callable AND returns `true` for the matching arm) at
16937        // caixa-core compile time — peer to the sibling
16938        // [`crate::CaixaKind::is_*`] const-block pin on the closed-set
16939        // typed enum arm-predicate const-callability axis.
16940        const {
16941            assert!(WitTarget::Http { endpoint: "/x" }.is_http());
16942            assert!(WitTarget::PubSub { subject: "e" }.is_pubsub());
16943            assert!(WitTarget::Store { slot: "kv/x" }.is_store());
16944            assert!(WitTarget::Capability.is_capability());
16945        }
16946    }
16947
16948    #[test]
16949    fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
16950        // Consumer-side pin on the sole production converge site:
16951        // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
16952        // edges from the synchronous-subgraph DFS via the lifted
16953        // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
16954        // predicate (rebound from the prior raw
16955        // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
16956        // variant). Byte-equivalent today (`is_pubsub` is the
16957        // derive-generated `matches!(self, Self::PubSub { .. })` by
16958        // construction, the `#[is_variant(name = "pubsub")]` override
16959        // aliasing the auto-derived `is_pub_sub` back to the sibling
16960        // [`WitContract::is_pubsub`] name); pin the behavior so a
16961        // future accidental drift (a rebind onto a peer arm
16962        // predicate, a manual hand-rolled `impl` that shadows the
16963        // derive-generated method with different semantics, a peer
16964        // arm rename that shifts which variant carries sync-versus-
16965        // async semantics) trips at caixa-core test time rather than
16966        // at some downstream operator's runtime dispatch far from the
16967        // rebind commit.
16968        //
16969        // The fixture constructs a two-Servico Aplicacao with one
16970        // pub-sub edge that would close a sync-cycle if the DFS did
16971        // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
16972        // pub-sub exclusion means the DFS sees only the `b → a` HTTP
16973        // edge, which is not a cycle. A regression in the converge
16974        // (a rebind that reads the pub-sub arm as sync) would report
16975        // `AplicacaoError::ContratoCycle`.
16976        let s = AplicacaoSpec {
16977            membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
16978            contratos: vec![
16979                // Pub-sub edge: DFS must skip via is_pubsub().
16980                WitContract {
16981                    de: "a".into(),
16982                    para: "b".into(),
16983                    wit: "nats:pub-sub".into(),
16984                    endpoint: None,
16985                    subject: Some("events.x".into()),
16986                    slot: None,
16987                },
16988                // HTTP edge: DFS must include.
16989                WitContract {
16990                    de: "b".into(),
16991                    para: "a".into(),
16992                    wit: "wasi:http/proxy".into(),
16993                    endpoint: Some("/x".into()),
16994                    subject: None,
16995                    slot: None,
16996                },
16997            ],
16998            politicas: MeshPolicy::default(),
16999            placement: Placement {
17000                estrategia: PlacementStrategy::Replicated,
17001                clusters: vec!["rio".into()],
17002                affinity: None,
17003                shard_key: None,
17004            },
17005            entrada: None,
17006        };
17007        s.validate()
17008            .expect("pub-sub edge must be excluded from sync-cycle DFS");
17009    }
17010
17011    #[test]
17012    fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
17013        // Consumer-side pin: the same three peer consts thread through
17014        // both the [`WitTarget::label`] template (leading-`:` keyword
17015        // prefix in the duplicate-`:contratos` diagnostic) and the
17016        // [`WitContract::target`] gate's [`AplicacaoError::
17017        // ContratoMissingTarget`] `expected:` scalar (the field the
17018        // author needs to add). Pin both routes at once so a future
17019        // refactor can't accidentally split them onto separate string
17020        // literals — the "one place, everywhere reaches for it"
17021        // invariant the peer const set carries.
17022        let http_label = WitTarget::Http { endpoint: "/x" }.label();
17023        assert!(
17024            http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
17025            "label must lead with :{} keyword (got {http_label:?})",
17026            WitTarget::HTTP_FIELD_NAME,
17027        );
17028
17029        let mut s = three_member_spec();
17030        s.contratos.push(WitContract {
17031            de: "cart".into(),
17032            para: "catalog".into(),
17033            wit: "kafka:topic".into(),
17034            endpoint: None,
17035            subject: None,
17036            slot: None,
17037        });
17038        match s.validate().unwrap_err() {
17039            AplicacaoError::ContratoMissingTarget { expected, .. } => {
17040                assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
17041            }
17042            other => panic!("expected ContratoMissingTarget, got {other:?}"),
17043        }
17044    }
17045
17046    #[test]
17047    fn duplicate_pubsub_diagnostic_names_offending_subject() {
17048        // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
17049        // on the pub-sub target axis: the duplicate-edge diagnostic
17050        // must name the `:subject` payload verbatim (not just the
17051        // `(de, para, wit)` triple). Prior to lifting the label onto
17052        // [`WitTarget::label`] the diagnostic derived the label from
17053        // raw [`WitContract`] `Option<String>` probes — a future
17054        // `WitTarget` variant addition (M4 per-edge WIT registry)
17055        // would silently fall through to the `Capability` "no
17056        // payload" default without a compiler warning. Pinning the
17057        // pub-sub arm's format closes the second of three
17058        // payload-carrying `WitTarget` arms this diagnostic threads
17059        // through.
17060        let mut s = three_member_spec();
17061        let pubsub = WitContract {
17062            de: "payment".into(),
17063            para: "cart".into(),
17064            wit: "nats:pub-sub".into(),
17065            endpoint: None,
17066            subject: Some("events.checkout.paid".into()),
17067            slot: None,
17068        };
17069        s.contratos.push(pubsub.clone());
17070        s.contratos.push(pubsub);
17071        let err = s.validate().unwrap_err();
17072        let msg = format!("{err}");
17073        assert!(
17074            msg.contains(":subject \"events.checkout.paid\""),
17075            "duplicate-pubsub diagnostic must name the offending \
17076             :subject payload (got: {msg:?})"
17077        );
17078    }
17079
17080    #[test]
17081    fn duplicate_store_diagnostic_names_offending_slot() {
17082        // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
17083        // key-value target axis: the diagnostic must name the `:slot`
17084        // payload verbatim. Third of three payload-carrying
17085        // `WitTarget` arms this diagnostic threads through, closing
17086        // the per-arm label pin trilogy (`Http` — 6841,
17087        // `PubSub` + `Store` — this test + peer above).
17088        let mut s = three_member_spec();
17089        let store = WitContract {
17090            de: "cart".into(),
17091            para: "payment".into(),
17092            wit: "wasi:keyvalue/store".into(),
17093            endpoint: None,
17094            subject: None,
17095            slot: Some("checkout/$orderId".into()),
17096        };
17097        s.contratos
17098            .retain(|c| !(c.de == "cart" && c.para == "payment"));
17099        s.contratos.push(store.clone());
17100        s.contratos.push(store);
17101        let err = s.validate().unwrap_err();
17102        let msg = format!("{err}");
17103        assert!(
17104            msg.contains(":slot \"checkout/$orderId\""),
17105            "duplicate-store diagnostic must name the offending :slot \
17106             payload (got: {msg:?})"
17107        );
17108    }
17109
17110    #[test]
17111    fn rejects_entrada_path_without_leading_slash() {
17112        let mut s = three_member_spec();
17113        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
17114        let err = s.validate().unwrap_err();
17115        assert!(
17116            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
17117            "got {err:?}"
17118        );
17119    }
17120
17121    #[test]
17122    fn rejects_empty_entrada_path() {
17123        let mut s = three_member_spec();
17124        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), String::new()];
17125        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
17126    }
17127
17128    #[test]
17129    fn rejects_duplicate_entrada_paths() {
17130        let mut s = three_member_spec();
17131        s.entrada.as_mut().unwrap().paths = vec![
17132            "/api/cart".into(),
17133            "/api/products".into(),
17134            "/api/cart".into(),
17135        ];
17136        let err = s.validate().unwrap_err();
17137        assert!(
17138            matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
17139            "got {err:?}"
17140        );
17141    }
17142
17143    #[test]
17144    fn rejects_zero_entrada_port() {
17145        let mut s = three_member_spec();
17146        s.entrada.as_mut().unwrap().port = 0;
17147        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
17148    }
17149
17150    // ── :entrada :paths value-shape gate ─────────────────────────────
17151    //
17152    // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
17153    // sibling `:paths` axis. Every authoring footgun the K8s Gateway
17154    // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
17155    // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
17156    // time now becomes a caixa-build-time `EntradaPathInvalid` with
17157    // the offending `:paths` entry named verbatim.
17158
17159    #[test]
17160    fn rejects_entrada_path_with_query() {
17161        // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
17162        // silently passed validate and the Gateway API webhook
17163        // rejected it at apply time with no source citation.
17164        let mut s = three_member_spec();
17165        s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
17166        let err = s.validate().unwrap_err();
17167        assert!(
17168            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
17169                if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
17170            "got {err:?}"
17171        );
17172    }
17173
17174    #[test]
17175    fn rejects_entrada_path_with_fragment() {
17176        let mut s = three_member_spec();
17177        s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
17178        let err = s.validate().unwrap_err();
17179        assert!(
17180            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
17181                if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
17182            "got {err:?}"
17183        );
17184    }
17185
17186    #[test]
17187    fn rejects_entrada_path_with_space() {
17188        let mut s = three_member_spec();
17189        s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
17190        let err = s.validate().unwrap_err();
17191        assert!(
17192            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
17193                if path == "/api/my cart" && reason.contains("whitespace")),
17194            "got {err:?}"
17195        );
17196    }
17197
17198    #[test]
17199    fn rejects_entrada_path_with_tab() {
17200        let mut s = three_member_spec();
17201        s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
17202        let err = s.validate().unwrap_err();
17203        assert!(
17204            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
17205                if path == "/api/\tcart" && reason.contains("whitespace")),
17206            "got {err:?}"
17207        );
17208    }
17209
17210    #[test]
17211    fn rejects_entrada_path_with_control_char() {
17212        // 0x01 (SOH) — a non-whitespace control char surfaces the
17213        // distinct "control character" reason arm, separate from
17214        // the whitespace arm. Pinned so a future refactor that
17215        // collapses the two arms can't accidentally drop the more
17216        // self-locating diagnostic.
17217        let mut s = three_member_spec();
17218        s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
17219        let err = s.validate().unwrap_err();
17220        assert!(
17221            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
17222                if path == "/api/\x01cart" && reason.contains("control character")),
17223            "got {err:?}"
17224        );
17225    }
17226
17227    #[test]
17228    fn rejects_entrada_path_with_non_ascii() {
17229        // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
17230        // unreserved-set rule rejects. The Gateway API webhook
17231        // rejects literal non-ASCII bytes; percent-encoding is the
17232        // only way to author non-ASCII in a path.
17233        let mut s = three_member_spec();
17234        s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
17235        let err = s.validate().unwrap_err();
17236        assert!(
17237            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
17238                if path == "/api/café" && reason.contains("non-ASCII")),
17239            "got {err:?}"
17240        );
17241    }
17242
17243    #[test]
17244    fn rejects_entrada_path_with_consecutive_slashes() {
17245        let mut s = three_member_spec();
17246        s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
17247        let err = s.validate().unwrap_err();
17248        assert!(
17249            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
17250                if path == "/api//cart" && reason.contains("consecutive `/`")),
17251            "got {err:?}"
17252        );
17253    }
17254
17255    #[test]
17256    fn rejects_entrada_path_with_dot_segment() {
17257        let mut s = three_member_spec();
17258        s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
17259        let err = s.validate().unwrap_err();
17260        assert!(
17261            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
17262                if path == "/api/./cart" && reason.contains("`.` segment")),
17263            "got {err:?}"
17264        );
17265    }
17266
17267    #[test]
17268    fn rejects_entrada_path_with_trailing_dot_segment() {
17269        // The bare `/.` and the trailing `/foo/.` are both rejected
17270        // by the Gateway API webhook; pinned separately so a future
17271        // narrowing that catches only the inner form surfaces here.
17272        let mut s = three_member_spec();
17273        s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
17274        let err = s.validate().unwrap_err();
17275        assert!(
17276            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
17277                if path == "/api/." && reason.contains("`.` segment")),
17278            "got {err:?}"
17279        );
17280    }
17281
17282    #[test]
17283    fn rejects_entrada_path_with_parent_segment() {
17284        let mut s = three_member_spec();
17285        s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
17286        let err = s.validate().unwrap_err();
17287        assert!(
17288            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
17289                if path == "/api/../etc" && reason.contains("`..` parent-segment")),
17290            "got {err:?}"
17291        );
17292    }
17293
17294    #[test]
17295    fn rejects_entrada_path_with_trailing_parent_segment() {
17296        // Trailing `/..` — symmetric arm of the parent-segment rule,
17297        // pinned separately so a future relaxation that only checks
17298        // the inner form (`/../`) surfaces here.
17299        let mut s = three_member_spec();
17300        s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
17301        let err = s.validate().unwrap_err();
17302        assert!(
17303            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
17304                if path == "/api/.." && reason.contains("`..` parent-segment")),
17305            "got {err:?}"
17306        );
17307    }
17308
17309    #[test]
17310    fn rejects_entrada_path_too_long() {
17311        // 1025-byte path — one over the Gateway API HTTPPathMatch.value
17312        // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
17313        // ASCII-alphanumeric body so only the length rule fires.
17314        let mut s = three_member_spec();
17315        let big = format!("/api/{}", "a".repeat(1020));
17316        assert_eq!(big.len(), 1025);
17317        s.entrada.as_mut().unwrap().paths = vec![big.clone()];
17318        let err = s.validate().unwrap_err();
17319        assert!(
17320            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
17321                if path == &big && reason.contains("max length of 1024")),
17322            "got {err:?}"
17323        );
17324    }
17325
17326    #[test]
17327    fn entrada_path_max_length_validates() {
17328        // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
17329        // maxLength cap. Boundary pin: drift in the cap surfaces here
17330        // and at `rejects_entrada_path_too_long` simultaneously.
17331        let mut s = three_member_spec();
17332        let big = format!("/api/{}", "a".repeat(1019));
17333        assert_eq!(big.len(), 1024);
17334        s.entrada.as_mut().unwrap().paths = vec![big];
17335        s.validate().unwrap();
17336    }
17337
17338    #[test]
17339    fn entrada_accepts_canonical_paths() {
17340        // Positive-control sweep — every form the Gateway API
17341        // apiserver accepts must round-trip through validate. Covers
17342        // the root catch-all, plain paths, dot-prefixed segments
17343        // (hidden-file-style, distinct from `.` and `..` segments
17344        // which are rejected), digit-bearing segments, the canonical
17345        // route-template `:param` form (`:` is RFC 3986 reserved-set
17346        // valid in paths), trailing-slash form, percent-encoded
17347        // segments, and an interior `..` *substring* (`/foo..bar` is
17348        // not the `..` segment and is allowed).
17349        for path in [
17350            "/",
17351            "/api/cart",
17352            "/healthz",
17353            "/api/.config",
17354            "/v1/products",
17355            "/products/:id",
17356            "/api/cart/",
17357            "/api/caf%C3%A9",
17358            "/foo..bar",
17359            "/...",
17360        ] {
17361            let mut s = three_member_spec();
17362            s.entrada.as_mut().unwrap().paths = vec![path.into()];
17363            s.validate()
17364                .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
17365        }
17366    }
17367
17368    #[test]
17369    fn entrada_path_empty_takes_precedence_over_invalid() {
17370        // Ordering pin: `EntradaPathEmpty` is the more self-locating
17371        // diagnostic on `""` and must lead — `validate_entrada_path`
17372        // is only reached after the empty-check fires at the call
17373        // site. (The predicate itself defends against direct
17374        // invocation by returning the same error on `""`.)
17375        let mut s = three_member_spec();
17376        s.entrada.as_mut().unwrap().paths = vec![String::new()];
17377        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
17378    }
17379
17380    #[test]
17381    fn entrada_path_not_absolute_takes_precedence_over_invalid() {
17382        // Ordering pin: a path without a leading `/` surfaces the
17383        // narrower `EntradaPathNotAbsolute` diagnostic first; the
17384        // value-shape gate is only consulted on paths that already
17385        // satisfy the absolute-prefix invariant.
17386        let mut s = three_member_spec();
17387        // `bad path` would fire the whitespace rule under the
17388        // value-shape gate, but missing-leading-`/` is the more
17389        // self-locating diagnostic.
17390        s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
17391        let err = s.validate().unwrap_err();
17392        assert!(
17393            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
17394            "got {err:?}"
17395        );
17396    }
17397
17398    #[test]
17399    fn entrada_path_invalid_fires_before_duplicate_check() {
17400        // Ordering pin: a malformed path on the *first* entry of a
17401        // would-be duplicate pair fires the value-shape gate before
17402        // the duplicate gate, mirroring the
17403        // `placement_cluster_invalid_fires_before_duplicate_check`
17404        // (6cbb900) pattern on the peer axis.
17405        let mut s = three_member_spec();
17406        s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
17407        let err = s.validate().unwrap_err();
17408        assert!(
17409            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
17410            "got {err:?}"
17411        );
17412    }
17413
17414    #[test]
17415    fn entrada_path_diagnostic_carries_offending_path() {
17416        // Diagnostic-shape pin — the offending path + a non-empty
17417        // reason flow through verbatim so the author can grep their
17418        // caixa.lisp for `:paths` and fix it in one edit. Same shape
17419        // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
17420        let mut s = three_member_spec();
17421        s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
17422        let err = s.validate().unwrap_err();
17423        match err {
17424            AplicacaoError::EntradaPathInvalid { path, reason } => {
17425                assert_eq!(path, "/api?q=1");
17426                assert!(!reason.is_empty(), "reason field must be non-empty");
17427            }
17428            other => panic!("expected EntradaPathInvalid, got {other:?}"),
17429        }
17430    }
17431
17432    #[test]
17433    fn rejects_entrada_path_with_curly_brace_template_form() {
17434        // Per-axis pin on the shared `is_gateway_api_http_path`
17435        // reserved-byte arm: the canonical "I wrote an OpenAPI
17436        // path-template `{id}` instead of the Gateway API `:id` form"
17437        // footgun the K8s apiserver would otherwise catch at admission
17438        // time on every `HTTPRoute.spec.rules[].matches[].path.value`
17439        // landing site, far from the caixa.lisp. Surfaces as
17440        // `EntradaPathInvalid` carrying the offending path verbatim
17441        // plus the canonical `%7B`/`%7D` percent-encoding remediation
17442        // — the substrate-side `gateway_api_http_path_rejects_every_
17443        // reserved_printable_ascii_byte` predicate-level sweep pins the
17444        // full eleven-byte set; this per-axis pin confirms the
17445        // diagnostic flows through to the `EntradaPathInvalid` variant.
17446        let mut s = three_member_spec();
17447        s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
17448        let err = s.validate().unwrap_err();
17449        assert!(
17450            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
17451                if path == "/api/cart/{id}"
17452                    && reason.contains("reserved character")
17453                    && reason.contains("'{'")
17454                    && reason.contains("%7B")),
17455            "got {err:?}"
17456        );
17457    }
17458
17459    #[test]
17460    fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
17461        // Per-axis peer of `rejects_entrada_path_with_curly_brace_
17462        // template_form` on the sibling `:contratos :endpoint` axis.
17463        // Same shared `is_gateway_api_http_path` reserved-byte arm
17464        // fires through `ContratoEndpointInvalid`, with the offending
17465        // endpoint + `:de` + `:para` + reason flowing through verbatim.
17466        // Pins that the lifted predicate's tightening lands on both
17467        // caller axes simultaneously — one source of truth for the
17468        // Gateway API HTTPPathMatch.value accepted set.
17469        let err = contrato_endpoint_err("/api/cart/{id}");
17470        assert!(
17471            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
17472                if endpoint == "/api/cart/{id}"
17473                    && reason.contains("reserved character")
17474                    && reason.contains("'{'")
17475                    && reason.contains("%7B")),
17476            "got {err:?}"
17477        );
17478    }
17479
17480    // ── :entrada :host value-shape gate ──────────────────────────────
17481    //
17482    // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
17483    // the sibling `:host` axis. Every authoring footgun the K8s
17484    // Gateway API v1 apiserver would catch at admission time becomes
17485    // a caixa-build-time `EntradaHostInvalid` with the offending
17486    // `:host` named verbatim. Same diagnostic shape as
17487    // `MembroVersaoInvalid` (9888b13).
17488
17489    #[test]
17490    fn rejects_entrada_host_with_scheme() {
17491        // Fail-before-pass-after pin — pre-gate codebases silently
17492        // accepted `https://…` and the apiserver rejected it at apply
17493        // time with no source citation.
17494        let mut s = three_member_spec();
17495        s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
17496        let err = s.validate().unwrap_err();
17497        assert!(
17498            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
17499                if host == "https://checkout.quero.cloud"),
17500            "got {err:?}"
17501        );
17502    }
17503
17504    #[test]
17505    fn rejects_entrada_host_with_port() {
17506        // The `:8080` port suffix is the canonical "I forgot the port
17507        // belongs in `:entrada :port`" footgun. The top-level `:` arm
17508        // (introduced after the per-label loop-only impl silently
17509        // surfaced a deep "label \"cloud:8080\" contains invalid
17510        // character ':'" leak) names the canonical fix verbatim — the
17511        // `:entrada :port` slot.
17512        let mut s = three_member_spec();
17513        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
17514        let err = s.validate().unwrap_err();
17515        assert!(
17516            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
17517                if host == "checkout.quero.cloud:8080"
17518                && reason.contains(":entrada :port")),
17519            "got {err:?}"
17520        );
17521    }
17522
17523    #[test]
17524    fn rejects_entrada_host_with_trailing_colon() {
17525        // Trailing `:` (e.g. an in-progress `:host "example.com:"`
17526        // edit) — the per-label loop would land it as a deep
17527        // "label \"com:\" must start and end with an alphanumeric"
17528        // / "contains invalid character ':'" leak. The top-level
17529        // `:` arm pre-empts with the canonical `:port` slot
17530        // diagnostic.
17531        let mut s = three_member_spec();
17532        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
17533        let err = s.validate().unwrap_err();
17534        assert!(
17535            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
17536                if host == "checkout.quero.cloud:"
17537                && reason.contains(":entrada :port")),
17538            "got {err:?}"
17539        );
17540    }
17541
17542    #[test]
17543    fn rejects_entrada_host_unbracketed_ipv6_literal() {
17544        // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
17545        // literals across the board (peer with `rejects_entrada_host_
17546        // ipv4_literal` above for the four-label-all-digit IPv4 arm).
17547        // Before this top-level `:` arm landed the per-label loop
17548        // surfaced a single-label byte-class diagnostic that named the
17549        // `:` byte but not the IP-literal prohibition. The top-level
17550        // `:` arm names both the `:port` slot and the IP-literal
17551        // prohibition verbatim, so an author whose `:host "2001:..."`
17552        // value lands here gets a self-locating fix either way.
17553        let mut s = three_member_spec();
17554        s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
17555        let err = s.validate().unwrap_err();
17556        assert!(
17557            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
17558                if host == "2001:db8::1"
17559                && reason.contains("IPv6")),
17560            "got {err:?}"
17561        );
17562    }
17563
17564    #[test]
17565    fn rejects_entrada_host_wildcard_with_port() {
17566        // Wildcard host with port suffix — the `*.` strip and the
17567        // per-label loop on `["foo", "quero", "cloud:8080"]` would
17568        // surface the deep byte-class leak. The top-level `:` arm sits
17569        // upstream of the `*.` strip, so it names the canonical `:port`
17570        // fix verbatim regardless of whether the host is wildcard-led.
17571        let mut s = three_member_spec();
17572        s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
17573        let err = s.validate().unwrap_err();
17574        assert!(
17575            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
17576                if host == "*.quero.cloud:8080"
17577                && reason.contains(":entrada :port")),
17578            "got {err:?}"
17579        );
17580    }
17581
17582    #[test]
17583    fn rejects_entrada_host_with_path() {
17584        let mut s = three_member_spec();
17585        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
17586        let err = s.validate().unwrap_err();
17587        assert!(
17588            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
17589                if host == "checkout.quero.cloud/api"),
17590            "got {err:?}"
17591        );
17592    }
17593
17594    #[test]
17595    fn rejects_entrada_host_with_uppercase() {
17596        // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
17597        // rejected, not silently lower-cased.
17598        let mut s = three_member_spec();
17599        s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
17600        let err = s.validate().unwrap_err();
17601        assert!(
17602            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17603                if reason.contains("uppercase")),
17604            "got {err:?}"
17605        );
17606    }
17607
17608    #[test]
17609    fn rejects_entrada_host_with_underscore() {
17610        // RFC 1123 allows `[a-z0-9-]` only; underscore is the
17611        // canonical "I'm thinking of HTTP cookies / SRV records" leak.
17612        let mut s = three_member_spec();
17613        s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
17614        let err = s.validate().unwrap_err();
17615        assert!(
17616            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17617                if reason.contains('_')),
17618            "got {err:?}"
17619        );
17620    }
17621
17622    #[test]
17623    fn rejects_entrada_host_ipv4_literal() {
17624        // Gateway API v1 explicitly forbids IP literals as Hostnames.
17625        let mut s = three_member_spec();
17626        s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
17627        let err = s.validate().unwrap_err();
17628        assert!(
17629            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17630                if reason.contains("IPv4")),
17631            "got {err:?}"
17632        );
17633    }
17634
17635    #[test]
17636    fn rejects_entrada_host_with_trailing_dot() {
17637        // The Gateway API regex anchors at end-of-string with no
17638        // trailing `.` allowance — the FQDN root-dot form is rejected.
17639        let mut s = three_member_spec();
17640        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
17641        let err = s.validate().unwrap_err();
17642        assert!(
17643            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
17644                if host == "checkout.quero.cloud."),
17645            "got {err:?}"
17646        );
17647    }
17648
17649    #[test]
17650    fn rejects_entrada_host_with_leading_dot() {
17651        let mut s = three_member_spec();
17652        s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
17653        let err = s.validate().unwrap_err();
17654        assert!(
17655            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17656                if reason.contains("empty label")),
17657            "got {err:?}"
17658        );
17659    }
17660
17661    #[test]
17662    fn rejects_entrada_host_with_consecutive_dots() {
17663        let mut s = three_member_spec();
17664        s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
17665        let err = s.validate().unwrap_err();
17666        assert!(
17667            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17668                if reason.contains("empty label")),
17669            "got {err:?}"
17670        );
17671    }
17672
17673    #[test]
17674    fn rejects_entrada_host_with_leading_hyphen_label() {
17675        let mut s = three_member_spec();
17676        s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
17677        let err = s.validate().unwrap_err();
17678        assert!(
17679            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17680                if reason.contains("alphanumeric")),
17681            "got {err:?}"
17682        );
17683    }
17684
17685    #[test]
17686    fn rejects_entrada_host_with_trailing_hyphen_label() {
17687        let mut s = three_member_spec();
17688        s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
17689        let err = s.validate().unwrap_err();
17690        assert!(
17691            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17692                if reason.contains("alphanumeric")),
17693            "got {err:?}"
17694        );
17695    }
17696
17697    #[test]
17698    fn rejects_entrada_host_with_inner_wildcard() {
17699        // Gateway API allows `*` only as the first label (`*.foo`);
17700        // any inner or trailing `*` is rejected.
17701        let mut s = three_member_spec();
17702        s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
17703        let err = s.validate().unwrap_err();
17704        assert!(
17705            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17706                if reason.contains("wildcard")),
17707            "got {err:?}"
17708        );
17709    }
17710
17711    #[test]
17712    fn rejects_entrada_host_bare_wildcard() {
17713        // `*.` with no domain is meaningless; Gateway API rejects it.
17714        let mut s = three_member_spec();
17715        s.entrada.as_mut().unwrap().host = "*.".into();
17716        let err = s.validate().unwrap_err();
17717        assert!(
17718            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17719                if reason.contains("wildcard")),
17720            "got {err:?}"
17721        );
17722    }
17723
17724    #[test]
17725    fn rejects_entrada_host_with_whitespace() {
17726        let mut s = three_member_spec();
17727        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
17728        let err = s.validate().unwrap_err();
17729        assert!(
17730            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17731                if reason.contains("whitespace")),
17732            "got {err:?}"
17733        );
17734    }
17735
17736    #[test]
17737    fn rejects_entrada_host_space_names_offending_byte() {
17738        // Embedded space in the `:entrada :host` axis surfaces the
17739        // byte-naming diagnostic through the lifted
17740        // `find_ascii_whitespace_byte` predicate. Peer with the
17741        // sibling `parse_rejects_leading_whitespace` pins on
17742        // `supervisor::duration_codec` (a7ae622) — same "the
17743        // diagnostic carries the offending byte's `0x{b:02x}` shape"
17744        // discipline extended from the shared duration codec to the
17745        // Gateway API v1 Hostname axis.
17746        let mut s = three_member_spec();
17747        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
17748        let err = s.validate().unwrap_err();
17749        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
17750            panic!("expected EntradaHostInvalid, got {err:?}");
17751        };
17752        assert!(
17753            reason.contains("ASCII whitespace byte"),
17754            "expected byte-naming diagnostic, got {reason:?}"
17755        );
17756        assert!(
17757            reason.contains("0x20"),
17758            "expected offending space byte 0x20, got {reason:?}"
17759        );
17760    }
17761
17762    #[test]
17763    fn rejects_entrada_host_tab_names_offending_byte() {
17764        // Embedded tab byte in the `:entrada :host` axis — the
17765        // canonical paste-from-YAML-block-scalar / paste-from-
17766        // indented-doc footgun. Pins that the lifted predicate covers
17767        // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
17768        // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
17769        // not just the leading-space case the pre-lift `.bytes().any`
17770        // arm's opaque "must not contain whitespace" reason already
17771        // covered. Peer with `parse_rejects_tab_byte` on
17772        // `supervisor::duration_codec` (a7ae622).
17773        let mut s = three_member_spec();
17774        s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
17775        let err = s.validate().unwrap_err();
17776        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
17777            panic!("expected EntradaHostInvalid, got {err:?}");
17778        };
17779        assert!(
17780            reason.contains("ASCII whitespace byte"),
17781            "expected byte-naming diagnostic, got {reason:?}"
17782        );
17783        assert!(
17784            reason.contains("0x09"),
17785            "expected offending tab byte 0x09, got {reason:?}"
17786        );
17787    }
17788
17789    #[test]
17790    fn rejects_entrada_host_lf_names_offending_byte() {
17791        // Embedded LF byte in the `:entrada :host` axis — the
17792        // canonical paste-from-shell-heredoc / paste-from-multiline-
17793        // doc footgun the caixa-mesh YAML emitter would silently
17794        // reinterpret at the Gateway API v1 HTTPRoute admission
17795        // layer (an embedded LF byte in a YAML plain scalar either
17796        // truncates the value at the emitter or crashes the parser
17797        // on the k8s-apiserver side). Pins the third representative
17798        // of the full ASCII-whitespace set through the shared
17799        // predicate.
17800        let mut s = three_member_spec();
17801        s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
17802        let err = s.validate().unwrap_err();
17803        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
17804            panic!("expected EntradaHostInvalid, got {err:?}");
17805        };
17806        assert!(
17807            reason.contains("ASCII whitespace byte"),
17808            "expected byte-naming diagnostic, got {reason:?}"
17809        );
17810        assert!(
17811            reason.contains("0x0a"),
17812            "expected offending LF byte 0x0a, got {reason:?}"
17813        );
17814    }
17815
17816    #[test]
17817    fn rejects_entrada_host_nbsp_names_offending_codepoint() {
17818        // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
17819        // axis — the canonical paste-from-typography /
17820        // paste-from-word-processor footgun. Before the non-ASCII
17821        // Unicode `White_Space` scan lifted through the shared
17822        // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
17823        // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
17824        // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
17825        // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
17826        // with the far-from-source `label "…" must start and end
17827        // with an alphanumeric` diagnostic — burying the
17828        // paste-from-typography origin under a label-shape leak.
17829        // Peer with the sibling non-ASCII-whitespace pins at
17830        // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
17831        // — 1b75b38), `limits::parse_duration`,
17832        // `limits::parse_millicores`, and the shared duration codec
17833        // — same "the diagnostic carries the offending Unicode
17834        // codepoint's `U+XXXX` shape" discipline extended from every
17835        // typed-magnitude codec to the Gateway API v1 Hostname axis.
17836        let mut s = three_member_spec();
17837        s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
17838        let err = s.validate().unwrap_err();
17839        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
17840            panic!("expected EntradaHostInvalid, got {err:?}");
17841        };
17842        assert!(
17843            reason.contains("non-ASCII Unicode whitespace character"),
17844            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
17845        );
17846        assert!(
17847            reason.contains("U+00A0"),
17848            "expected offending NBSP codepoint U+00A0, got {reason:?}"
17849        );
17850    }
17851
17852    #[test]
17853    fn rejects_entrada_host_line_separator_names_offending_codepoint() {
17854        // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
17855        // `:entrada :host` axis — the canonical paste-from-web-doc /
17856        // paste-from-published-HTML footgun. `char::is_whitespace`
17857        // returns true for `U+2028` per the Unicode `White_Space`
17858        // property, so `str::trim` at any downstream site would
17859        // silently strip it — same drift class as NBSP but on a
17860        // different codepoint region. Pins the second representative
17861        // (non-Latin-1 `char::is_whitespace` member) through the
17862        // shared predicate. Peer with
17863        // `parse_byte_size_rejects_internal_line_separator` on
17864        // `limits::parse_byte_size` (1b75b38).
17865        let mut s = three_member_spec();
17866        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
17867        let err = s.validate().unwrap_err();
17868        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
17869            panic!("expected EntradaHostInvalid, got {err:?}");
17870        };
17871        assert!(
17872            reason.contains("non-ASCII Unicode whitespace character"),
17873            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
17874        );
17875        assert!(
17876            reason.contains("U+2028"),
17877            "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
17878        );
17879    }
17880
17881    #[test]
17882    fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
17883        // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
17884        // labels in the `:entrada :host` axis — the canonical
17885        // paste-from-CJK-typography footgun (CJK IMEs default to
17886        // full-width whitespace when the space bar is pressed in
17887        // Japanese / Chinese input modes). Pins the third
17888        // representative of the non-ASCII Unicode `White_Space` set
17889        // through the shared predicate: the CJK block, distinct from
17890        // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
17891        // SEPARATOR `U+2028` — covering the same axis breadth the
17892        // sibling `parse_byte_size_rejects_trailing_ideographic_space`
17893        // (1b75b38) pins on `limits::parse_byte_size`.
17894        let mut s = three_member_spec();
17895        s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
17896        let err = s.validate().unwrap_err();
17897        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
17898            panic!("expected EntradaHostInvalid, got {err:?}");
17899        };
17900        assert!(
17901            reason.contains("non-ASCII Unicode whitespace character"),
17902            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
17903        );
17904        assert!(
17905            reason.contains("U+3000"),
17906            "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
17907        );
17908    }
17909
17910    #[test]
17911    fn rejects_entrada_host_too_long() {
17912        // Total length cap = 253; build a 254-byte host out of two
17913        // 63-byte labels + one 62-byte label + dots.
17914        let mut s = three_member_spec();
17915        let big = format!(
17916            "{}.{}.{}.{}",
17917            "a".repeat(63),
17918            "b".repeat(63),
17919            "c".repeat(63),
17920            "d".repeat(254 - 63 * 3 - 3)
17921        );
17922        assert_eq!(big.len(), 254);
17923        s.entrada.as_mut().unwrap().host = big;
17924        let err = s.validate().unwrap_err();
17925        assert!(
17926            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17927                if reason.contains("max length of 253")),
17928            "got {err:?}"
17929        );
17930    }
17931
17932    #[test]
17933    fn rejects_entrada_host_label_too_long() {
17934        let mut s = three_member_spec();
17935        // 64-byte label — one over the per-label cap.
17936        s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
17937        let err = s.validate().unwrap_err();
17938        assert!(
17939            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17940                if reason.contains("label max length of 63")),
17941            "got {err:?}"
17942        );
17943    }
17944
17945    #[test]
17946    fn entrada_host_diagnostic_carries_offending_host() {
17947        // Diagnostic-shape pin — the offending host + a non-empty
17948        // reason flow through verbatim so the author can grep their
17949        // caixa.lisp for `:host "<host>"` and fix it in one edit.
17950        let mut s = three_member_spec();
17951        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
17952        let err = s.validate().unwrap_err();
17953        match err {
17954            AplicacaoError::EntradaHostInvalid { host, reason } => {
17955                assert_eq!(host, "checkout.quero.cloud:8080");
17956                assert!(!reason.is_empty(), "reason field must be non-empty");
17957            }
17958            other => panic!("expected EntradaHostInvalid, got {other:?}"),
17959        }
17960    }
17961
17962    // Equivalence pin for the [`AplicacaoError::entrada_host_invalid`]
17963    // substrate primitive that folds the fourteen
17964    // `AplicacaoError::EntradaHostInvalid { host: host.to_string(),
17965    // reason: <expr> }` wire-up sites at [`validate_entrada_host`] onto
17966    // one dispatch — peer with the sixteen equivalence pins the
17967    // [`crate::LayoutError`] `_violation` constructor family carries in
17968    // `layout::tests::*_ctor_matches_struct_literal_wrap` (131ca0d). The
17969    // fixture host + reason are fixed `&'static str`s so both fields of
17970    // both constructed variants pin verbatim: the `host` axis is pinned
17971    // through the shared `host.to_string()` wrap (the ctor's uniform
17972    // one-slot construction) and the `reason` axis is pinned through
17973    // the shared `reason.into()` wrap (the ctor's `impl Into<String>`
17974    // routing). Any future regression on the lift (an extra field
17975    // introduced without updating the ctor, a diverging string
17976    // conversion at either arm) surfaces at this pin's diagnostic
17977    // rather than at a per-wire-up struct-literal reintroduction.
17978    #[test]
17979    fn entrada_host_invalid_ctor_matches_struct_literal_wrap() {
17980        let host = "checkout.quero.cloud:8080";
17981        let reason = "sample reason text";
17982        assert_eq!(
17983            AplicacaoError::entrada_host_invalid(host, reason),
17984            AplicacaoError::EntradaHostInvalid {
17985                host: host.to_string(),
17986                reason: reason.to_string(),
17987            },
17988            "generated constructor must produce byte-equal AplicacaoError to open-coded struct-literal wrap",
17989        );
17990    }
17991
17992    // Routing pin — the ctor's `host: &str` argument threads through
17993    // `.to_string()` verbatim on the `host` field, so the constructed
17994    // variant carries the offending host bytes without any wrapper-
17995    // side transformation (no `.to_ascii_lowercase()` normalization,
17996    // no `.trim()` strip, no truncation) — the same "diagnostic carries
17997    // the offending value verbatim so the author can grep their
17998    // caixa.lisp" discipline every peer typed-slot ctor at this
17999    // altitude carries.
18000    #[test]
18001    fn entrada_host_invalid_ctor_routes_host_through_to_string() {
18002        // Uppercase + trailing whitespace + port suffix — three
18003        // wrapper-side transformations the ctor must *not* apply.
18004        let host = " Checkout.quero.CLOUD:8080 ";
18005        let err = AplicacaoError::entrada_host_invalid(host, "sample");
18006        match err {
18007            AplicacaoError::EntradaHostInvalid { host: h, .. } => {
18008                assert_eq!(h, host, "host must thread through `.to_string()` verbatim");
18009            }
18010            other => panic!("expected EntradaHostInvalid, got {other:?}"),
18011        }
18012    }
18013
18014    // Routing pin — the ctor's `reason: impl Into<String>` accepts both
18015    // `&str` literals and `format!(…)` outputs identically and both
18016    // route through `Into::into` verbatim onto the `reason` field.
18017    // Pins both codepaths against the same host to prove the two
18018    // shapes the fourteen wire-up sites use at their per-arm diagnostic
18019    // (ten `&str` literals — some with `.to_string()` at the caller,
18020    // some without — plus four `format!(…)` outputs) each produce
18021    // byte-equal `reason` fields against the same offending host.
18022    #[test]
18023    fn entrada_host_invalid_ctor_routes_reason_through_into() {
18024        let host = "checkout.quero.cloud";
18025        // `&str` literal — the ctor's `impl Into<String>` accepts it
18026        // without a caller-side `.to_string()`.
18027        let from_literal = AplicacaoError::entrada_host_invalid(host, "literal reason text");
18028        // Owned `String` from `format!` — the peer `format!(…)`-shaped
18029        // wire-up arm.
18030        let from_format =
18031            AplicacaoError::entrada_host_invalid(host, format!("{} reason text", "literal"));
18032        // `String` from `.to_string()` on a literal — the peer
18033        // `"literal".to_string()`-shaped wire-up arm the pre-lift
18034        // sites carried.
18035        let from_to_string =
18036            AplicacaoError::entrada_host_invalid(host, "literal reason text".to_string());
18037        match (&from_literal, &from_format, &from_to_string) {
18038            (
18039                AplicacaoError::EntradaHostInvalid {
18040                    reason: r_lit,
18041                    host: h_lit,
18042                },
18043                AplicacaoError::EntradaHostInvalid {
18044                    reason: r_fmt,
18045                    host: h_fmt,
18046                },
18047                AplicacaoError::EntradaHostInvalid {
18048                    reason: r_ts,
18049                    host: h_ts,
18050                },
18051            ) => {
18052                assert_eq!(r_lit, "literal reason text");
18053                assert_eq!(r_fmt, "literal reason text");
18054                assert_eq!(r_ts, "literal reason text");
18055                assert_eq!(h_lit, host);
18056                assert_eq!(h_fmt, host);
18057                assert_eq!(h_ts, host);
18058            }
18059            _ => panic!("expected three EntradaHostInvalid variants"),
18060        }
18061        // Cross-arm equivalence — the three shapes must produce
18062        // byte-equal `AplicacaoError` values, so the fourteen wire-up
18063        // sites' mixed per-arm shapes fold onto one canonical form.
18064        assert_eq!(from_literal, from_format);
18065        assert_eq!(from_literal, from_to_string);
18066    }
18067
18068    // Equivalence pins for the six sibling
18069    // [`aplicacao_field_reason_ctors!`]-generated constructors that
18070    // fold the peer `{ <field>: String, reason: String }` variants
18071    // onto the same substrate-primitive family
18072    // `entrada_host_invalid` (17dd504) already carries pins for.
18073    // Each ctor's fixture pair (a fixed `&'static str` value and a
18074    // fixed `&'static str` reason) pins both fields verbatim so any
18075    // future regression on the macro (an extra field introduced
18076    // without updating the macro, a diverging string conversion at
18077    // either arm, a field-name typo on one variant that dropped it
18078    // off the shared shape) surfaces at the affected variant's pin
18079    // rather than at a per-wire-up struct-literal reintroduction. Peer
18080    // discipline of the sixteen `LayoutError` _violation ctor pins in
18081    // `layout::tests::*_ctor_matches_struct_literal_wrap` (131ca0d)
18082    // and the paired
18083    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
18084    // `contrato_missing_target_ctor_matches_struct_literal_wrap`
18085    // (14b81d5) / `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
18086    // (8580068) equivalence pins on the sibling `AplicacaoError`
18087    // ctor macros.
18088    #[test]
18089    fn membro_caixa_invalid_ctor_matches_struct_literal_wrap() {
18090        let caixa = "cart-svc";
18091        let reason = "sample reason text";
18092        assert_eq!(
18093            AplicacaoError::membro_caixa_invalid(caixa, reason),
18094            AplicacaoError::MembroCaixaInvalid {
18095                caixa: caixa.to_string(),
18096                reason: reason.to_string(),
18097            },
18098        );
18099    }
18100
18101    #[test]
18102    fn entrada_para_invalid_ctor_matches_struct_literal_wrap() {
18103        let para = "checkout";
18104        let reason = "sample reason text";
18105        assert_eq!(
18106            AplicacaoError::entrada_para_invalid(para, reason),
18107            AplicacaoError::EntradaParaInvalid {
18108                para: para.to_string(),
18109                reason: reason.to_string(),
18110            },
18111        );
18112    }
18113
18114    #[test]
18115    fn entrada_path_invalid_ctor_matches_struct_literal_wrap() {
18116        let path = "/api/cart";
18117        let reason = "sample reason text";
18118        assert_eq!(
18119            AplicacaoError::entrada_path_invalid(path, reason),
18120            AplicacaoError::EntradaPathInvalid {
18121                path: path.to_string(),
18122                reason: reason.to_string(),
18123            },
18124        );
18125    }
18126
18127    #[test]
18128    fn placement_cluster_invalid_ctor_matches_struct_literal_wrap() {
18129        let cluster = "rio";
18130        let reason = "sample reason text";
18131        assert_eq!(
18132            AplicacaoError::placement_cluster_invalid(cluster, reason),
18133            AplicacaoError::PlacementClusterInvalid {
18134                cluster: cluster.to_string(),
18135                reason: reason.to_string(),
18136            },
18137        );
18138    }
18139
18140    #[test]
18141    fn placement_affinity_invalid_ctor_matches_struct_literal_wrap() {
18142        let affinity = "data-locality";
18143        let reason = "sample reason text";
18144        assert_eq!(
18145            AplicacaoError::placement_affinity_invalid(affinity, reason),
18146            AplicacaoError::PlacementAffinityInvalid {
18147                affinity: affinity.to_string(),
18148                reason: reason.to_string(),
18149            },
18150        );
18151    }
18152
18153    #[test]
18154    fn shard_key_invalid_ctor_matches_struct_literal_wrap() {
18155        let shard_key = "tenantId";
18156        let reason = "sample reason text";
18157        assert_eq!(
18158            AplicacaoError::shard_key_invalid(shard_key, reason),
18159            AplicacaoError::ShardKeyInvalid {
18160                shard_key: shard_key.to_string(),
18161                reason: reason.to_string(),
18162            },
18163        );
18164    }
18165
18166    // Pin the three-slot per-`:contratos <slot>` sibling of the
18167    // two-slot `aplicacao_field_reason_ctors!` family — the sole
18168    // per-axis ctor carrying the extra `slot: &'static str` axis-tag
18169    // distinguishing the two-arm `:de` / `:para` cascade. Sweeps both
18170    // canonical author-side slot tags through the ctor and asserts
18171    // byte-equality against the pre-lift struct-literal shape so no
18172    // per-arm wrapper transformation drifts in against the sole
18173    // in-crate wire-up.
18174    #[test]
18175    fn contrato_caixa_invalid_ctor_matches_struct_literal_wrap() {
18176        let caixa = "cart-svc";
18177        let reason = "sample reason text";
18178        for slot in [
18179            crate::render::CONTRATO_AUTHOR_KEY_DE,
18180            crate::render::CONTRATO_AUTHOR_KEY_PARA,
18181        ] {
18182            assert_eq!(
18183                AplicacaoError::contrato_caixa_invalid(slot, caixa, reason),
18184                AplicacaoError::ContratoCaixaInvalid {
18185                    slot,
18186                    caixa: caixa.to_string(),
18187                    reason: reason.to_string(),
18188                },
18189            );
18190        }
18191    }
18192
18193    // The `reason: impl Into<String>` bound accepts both a `&str`
18194    // literal and a `format!(…)` owned-`String` output verbatim,
18195    // matching the peer `aplicacao_field_reason_ctors!` family's
18196    // reason-axis invariance so the sole in-crate wire-up's
18197    // `require_valid_dns_1123_label`-delivered owned-`String` return
18198    // and any future `&str` literal caller land on the same variant.
18199    #[test]
18200    fn contrato_caixa_invalid_ctor_routes_reason_through_into_uniformly() {
18201        let via_literal = "literal reason text";
18202        let via_format = format!("{} reason text", "literal");
18203        for slot in [
18204            crate::render::CONTRATO_AUTHOR_KEY_DE,
18205            crate::render::CONTRATO_AUTHOR_KEY_PARA,
18206        ] {
18207            assert_eq!(
18208                AplicacaoError::contrato_caixa_invalid(slot, "c", via_literal),
18209                AplicacaoError::contrato_caixa_invalid(slot, "c", via_format.clone()),
18210            );
18211        }
18212    }
18213
18214    // Pin the paired one-slot empty-arm sibling of the three-slot
18215    // `contrato_caixa_invalid` per-`:contratos <slot>` ctor — the sole
18216    // closure-form empty-arm on the shared
18217    // [`crate::render::require_valid_dns_1123_label`] two-closure
18218    // cascade at [`validate_contrato_caixa`], carrying the same
18219    // `slot: &'static str` axis-tag that distinguishes the two-arm
18220    // `:de` / `:para` cascade. Sweeps both canonical author-side slot
18221    // tags through the ctor and asserts byte-equality against the
18222    // pre-lift struct-literal shape so no per-arm wrapper transformation
18223    // drifts in against the sole in-crate wire-up. Peer of the sibling
18224    // [`crate::behavior::BehaviorError::empty_path`] one-slot
18225    // `{ slot: &'static str }` equivalence pin on the paired
18226    // `BehaviorError` envelope's four-arm sandboxed-lisp-path cascade
18227    // ([`crate::render::require_sandboxed_lisp_path`]) — extended here
18228    // onto the sibling `AplicacaoError` envelope's two-arm
18229    // DNS-1123-label cascade so both empty-arm axes carry a
18230    // substrate-primitive equivalence pin rather than the pre-lift
18231    // hand-open struct-literal.
18232    #[test]
18233    fn contrato_caixa_empty_ctor_matches_struct_literal_wrap() {
18234        for slot in [
18235            crate::render::CONTRATO_AUTHOR_KEY_DE,
18236            crate::render::CONTRATO_AUTHOR_KEY_PARA,
18237        ] {
18238            assert_eq!(
18239                AplicacaoError::contrato_caixa_empty(slot),
18240                AplicacaoError::ContratoCaixaEmpty { slot },
18241                "generated contrato_caixa_empty ctor must produce \
18242                 byte-equal AplicacaoError to the open-coded \
18243                 struct-literal wrap on the same &'static str fixture \
18244                 (slot = {slot:?})",
18245            );
18246        }
18247    }
18248
18249    // Cross-axis pin: sweep the constructor's single input axis (`slot:
18250    // &'static str`) through every canonical
18251    // [`crate::render::CONTRATO_AUTHOR_KEY_*`] tag *plus* a non-canonical
18252    // `&'static str` value (`":phantom"`), so any wrapper-side lowercase
18253    // / trim / truncate / re-order / fixed-slot substitution on the
18254    // one-field construction surfaces here rather than at a downstream
18255    // diagnostic-shape mismatch. The non-canonical arm proves the
18256    // constructor does not silently clamp `slot` to the `:de` /
18257    // `:para` roster (a future third `:contratos <slot>` axis lands on
18258    // this ctor without a per-arm rewrite), matching the discipline the
18259    // sibling [`Self::contrato_caixa_invalid`] ctor's tri-slot sweep
18260    // establishes at
18261    // `contrato_caixa_invalid_ctor_matches_struct_literal_wrap`
18262    // (18114) on the paired three-slot invalid-arm envelope.
18263    #[test]
18264    fn contrato_caixa_empty_ctor_routes_slot_verbatim_across_both_axes() {
18265        for slot in [
18266            crate::render::CONTRATO_AUTHOR_KEY_DE,
18267            crate::render::CONTRATO_AUTHOR_KEY_PARA,
18268            ":phantom",
18269        ] {
18270            assert_eq!(
18271                AplicacaoError::contrato_caixa_empty(slot),
18272                AplicacaoError::ContratoCaixaEmpty { slot },
18273            );
18274        }
18275    }
18276
18277    // End-to-end wire-up pin: `AplicacaoSpec::validate` on an empty
18278    // `:contratos :de` value must surface a diagnostic byte-equal to
18279    // the substrate primitive `AplicacaoError::contrato_caixa_empty`'s
18280    // output on the same slot fixture. Proves the sole in-crate
18281    // closure-form wire-up inside [`validate_contrato_caixa`]'s
18282    // [`crate::render::require_valid_dns_1123_label`] empty-arm routes
18283    // through the ctor rather than the pre-lift open-coded
18284    // struct-literal block, matching the sibling per-arm
18285    // `end_to_end_wire_up_routes_through_ctor` discipline the peer
18286    // per-envelope ctor pins the recent
18287    // [`Self::policy_rate_limit_cannot_admit_retry_burst`] (9703bd6),
18288    // [`Self::policy_breaker_trips_before_retries_exhausted`] (f54c539),
18289    // [`Self::policy_breaker_cannot_trip_under_rate_limit`] (6bb4e46),
18290    // and [`Self::policy_breaker_window_below_timeout`] (9b30c07)
18291    // cross-axis Policy* variants carry. Complements the two axis-tag
18292    // arms already pinned above the `:contratos` value-shape gate
18293    // block (`rejects_contrato_de_empty`, `rejects_contrato_para_empty`)
18294    // which anchor via the shape; this pin additionally verifies the
18295    // ctor is the exclusive construction path.
18296    #[test]
18297    fn contrato_caixa_empty_end_to_end_wire_up_routes_through_ctor() {
18298        // Empty `:de` — the sole in-crate wire-up hits the empty-arm
18299        // closure at the first `:contratos` value-shape gate, threading
18300        // the `CONTRATO_AUTHOR_KEY_DE` label through the ctor.
18301        let mut s_de = three_member_spec();
18302        s_de.contratos.push(contract_http("", "catalog", "/x"));
18303        assert_eq!(
18304            s_de.validate().unwrap_err(),
18305            AplicacaoError::contrato_caixa_empty(crate::render::CONTRATO_AUTHOR_KEY_DE),
18306        );
18307        // Symmetric arm: an empty `:para` on a valid `:de` fires the
18308        // same closure with the `CONTRATO_AUTHOR_KEY_PARA` label.
18309        let mut s_para = three_member_spec();
18310        s_para.contratos.push(contract_http("cart", "", "/x"));
18311        assert_eq!(
18312            s_para.validate().unwrap_err(),
18313            AplicacaoError::contrato_caixa_empty(crate::render::CONTRATO_AUTHOR_KEY_PARA),
18314        );
18315    }
18316
18317    // Cross-family invariance pin — the six sibling ctors and
18318    // `entrada_host_invalid` all route `reason: impl Into<String>` +
18319    // `<field>: &str` verbatim onto their respective typed variants
18320    // through the shared [`aplicacao_field_reason_ctors!`] macro.
18321    // Sweeps a fixture pair (`&str` literal, `format!` output) against
18322    // every ctor to pin that no per-arm wrapper transformation drifted
18323    // in against the uniform macro-generated body.
18324    #[test]
18325    fn aplicacao_field_reason_ctors_route_reason_through_into_uniformly() {
18326        let via_literal = "literal reason text";
18327        let via_format = format!("{} reason text", "literal");
18328        assert_eq!(
18329            AplicacaoError::membro_caixa_invalid("m", via_literal),
18330            AplicacaoError::membro_caixa_invalid("m", via_format.clone()),
18331        );
18332        assert_eq!(
18333            AplicacaoError::entrada_para_invalid("p", via_literal),
18334            AplicacaoError::entrada_para_invalid("p", via_format.clone()),
18335        );
18336        assert_eq!(
18337            AplicacaoError::entrada_path_invalid("/a", via_literal),
18338            AplicacaoError::entrada_path_invalid("/a", via_format.clone()),
18339        );
18340        assert_eq!(
18341            AplicacaoError::placement_cluster_invalid("c", via_literal),
18342            AplicacaoError::placement_cluster_invalid("c", via_format.clone()),
18343        );
18344        assert_eq!(
18345            AplicacaoError::placement_affinity_invalid("a", via_literal),
18346            AplicacaoError::placement_affinity_invalid("a", via_format.clone()),
18347        );
18348        assert_eq!(
18349            AplicacaoError::shard_key_invalid("k", via_literal),
18350            AplicacaoError::shard_key_invalid("k", via_format.clone()),
18351        );
18352        assert_eq!(
18353            AplicacaoError::entrada_host_invalid("h", via_literal),
18354            AplicacaoError::entrada_host_invalid("h", via_format),
18355        );
18356    }
18357
18358    #[test]
18359    fn entrada_host_empty_takes_precedence_over_invalid() {
18360        // Ordering pin: `EmptyEntradaHost` is the more self-locating
18361        // diagnostic on `""` and must lead — `validate_entrada_host`
18362        // is only reached after the empty-check fires at the call
18363        // site. (The predicate itself defends against direct
18364        // invocation by returning the same error on `""`.)
18365        let mut s = three_member_spec();
18366        s.entrada.as_mut().unwrap().host = String::new();
18367        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
18368    }
18369
18370    #[test]
18371    fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
18372        // Ordering pin: a missing :para member is the more
18373        // self-locating diagnostic and fires before the host gate.
18374        let mut s = three_member_spec();
18375        let e = s.entrada.as_mut().unwrap();
18376        e.para = "ghost".into();
18377        e.host = "BAD HOST".into();
18378        let err = s.validate().unwrap_err();
18379        assert!(
18380            matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
18381            "got {err:?}"
18382        );
18383    }
18384
18385    #[test]
18386    fn entrada_host_invalid_fires_before_port_zero() {
18387        // Ordering pin: the host gate fires before the port gate so
18388        // a malformed host is named even when the port is also wrong.
18389        let mut s = three_member_spec();
18390        let e = s.entrada.as_mut().unwrap();
18391        e.host = "Checkout.quero.cloud".into();
18392        e.port = 0;
18393        let err = s.validate().unwrap_err();
18394        assert!(
18395            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
18396                if host == "Checkout.quero.cloud"),
18397            "got {err:?}"
18398        );
18399    }
18400
18401    #[test]
18402    fn entrada_accepts_canonical_hosts() {
18403        // Positive-control sweep — every form the Gateway API
18404        // apiserver accepts must round-trip through validate. Covers
18405        // a plain DNS subdomain, a leading wildcard, a single-label
18406        // host (cluster-internal), a max-length-edge label, a
18407        // hyphen-bearing label, and a Punycode IDN label.
18408        for host in [
18409            "checkout.quero.cloud",
18410            "*.quero.cloud",
18411            "checkout",
18412            // 63-byte label — exactly the per-label cap.
18413            "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
18414            "foo-bar.quero.cloud",
18415            // Punycode IDN — valid because the author pre-encoded.
18416            "xn--bcher-kva.example.com",
18417        ] {
18418            let mut s = three_member_spec();
18419            s.entrada.as_mut().unwrap().host = host.into();
18420            s.validate()
18421                .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
18422        }
18423    }
18424
18425    #[test]
18426    fn entrada_host_max_length_validates() {
18427        // 253-byte host is the cap exactly — must validate. Build a
18428        // 253-byte host out of three 63-byte labels + one 61-byte
18429        // label + 3 dots = 252 bytes, then pad one byte to 253.
18430        let mut s = three_member_spec();
18431        let host = format!(
18432            "{}.{}.{}.{}",
18433            "a".repeat(63),
18434            "b".repeat(63),
18435            "c".repeat(63),
18436            "d".repeat(253 - 63 * 3 - 3)
18437        );
18438        assert_eq!(host.len(), 253);
18439        s.entrada.as_mut().unwrap().host = host;
18440        s.validate().unwrap();
18441    }
18442
18443    #[test]
18444    fn entrada_host_total_length_cap_threads_lifted_render_const() {
18445        // Cross-crate-side pin: the aplicacao-side `:entrada :host`
18446        // total-length gate now reads the K8s Gateway API v1 Hostname
18447        // `maxLength: 253` cap from the lifted
18448        // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
18449        // of truth — the same constant every future Gateway-API-Hostname
18450        // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
18451        // materializer's per-host validator, the future per-`Certificate`
18452        // SAN emitter for cert-manager, the multi-`:entrada`
18453        // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
18454        // from. Before the lift, the aplicacao-side reader consumed a
18455        // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
18456        // 253-byte value as the peer render-side canonical bounds
18457        // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
18458        // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
18459        // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
18460        // module boundary — a future 253-byte drift on either side would
18461        // silently split into two axes' worth of admission-schema mismatch
18462        // without a build-time signal. Pin the cap through a fresh 254-
18463        // byte host that hits the total-length arm, then read the reason
18464        // for the exact byte count the shared constant carries: any future
18465        // regression on the lift (a private alias reintroduced, a hard-
18466        // coded literal at the arm, a mismatch between the aplicacao-side
18467        // and render-side canonicals) surfaces as this pin's diagnostic
18468        // failing to match, not as a per-cluster admission rejection far
18469        // from the caixa.lisp source line.
18470        let mut s = three_member_spec();
18471        let over_cap = format!(
18472            "{}.{}.{}.{}",
18473            "a".repeat(63),
18474            "b".repeat(63),
18475            "c".repeat(63),
18476            "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
18477        );
18478        assert_eq!(
18479            over_cap.len(),
18480            crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
18481        );
18482        s.entrada.as_mut().unwrap().host = over_cap;
18483        let err = s.validate().unwrap_err();
18484        match err {
18485            AplicacaoError::EntradaHostInvalid { reason, .. } => {
18486                let needle = format!(
18487                    "max length of {} bytes",
18488                    crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
18489                );
18490                assert!(
18491                    reason.contains(&needle),
18492                    "diagnostic must name the lifted \
18493                     GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
18494                );
18495            }
18496            other => panic!("expected EntradaHostInvalid, got {other:?}"),
18497        }
18498    }
18499
18500    #[test]
18501    fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
18502        // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
18503        // on the per-label-cap axis. Before the lift, the aplicacao-side
18504        // per-label arm consumed a private const alias
18505        // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
18506        // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
18507        // split from it at the module boundary — every `.`-separated
18508        // label in a Gateway API v1 Hostname is a DNS-1123 label under
18509        // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
18510        // so the private alias's 63 and the canonical const's 63 were
18511        // pinning the same underlying rule twice. Pin the cap through a
18512        // 64-byte label that hits the per-label arm, then read the reason
18513        // for the exact byte count the shared constant carries: any
18514        // future drift on either side (a private alias reintroduced, a
18515        // hard-coded literal at the arm, a mismatch between the two
18516        // 63-byte pins) surfaces at this pin's diagnostic rather than at
18517        // a per-cluster admission rejection whose "field is invalid"
18518        // opacity misframes the root cause.
18519        let mut s = three_member_spec();
18520        let over_cap_label = format!(
18521            "{}.quero.cloud",
18522            "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
18523        );
18524        s.entrada.as_mut().unwrap().host = over_cap_label;
18525        let err = s.validate().unwrap_err();
18526        match err {
18527            AplicacaoError::EntradaHostInvalid { reason, .. } => {
18528                let needle = format!(
18529                    "label max length of {} bytes",
18530                    crate::render::DNS_1123_LABEL_MAX_LEN,
18531                );
18532                assert!(
18533                    reason.contains(&needle),
18534                    "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
18535                     cap verbatim on the per-label arm, got: {reason:?}",
18536                );
18537            }
18538            other => panic!("expected EntradaHostInvalid, got {other:?}"),
18539        }
18540    }
18541
18542    #[test]
18543    fn entrada_with_empty_paths_validates() {
18544        // Empty `:paths` is the documented "match every path" form;
18545        // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
18546        let mut s = three_member_spec();
18547        s.entrada.as_mut().unwrap().paths = vec![];
18548        s.validate().unwrap();
18549    }
18550
18551    #[test]
18552    fn entrada_root_path_validates() {
18553        // The author-supplied bare-root `:entrada :paths` entry is the
18554        // same byte-shape the peer emit-side catch-all constant
18555        // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
18556        // the author's `:paths` list is empty — sweeping the test-side
18557        // probe literal onto the lifted const closes the two-axis pin
18558        // (author-side admit + emit-side canonical fallback) around
18559        // one `&'static str`, so a future rebrand of the catch-all
18560        // reaches both consumers by construction. Peer to
18561        // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
18562        // on the canonical-literal pin surface.
18563        let mut s = three_member_spec();
18564        s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
18565        s.validate().unwrap();
18566    }
18567
18568    #[test]
18569    fn placement_strategy_variants_round_trip() {
18570        for s in [
18571            PlacementStrategy::SingleNode,
18572            PlacementStrategy::Replicated,
18573            PlacementStrategy::Sharded,
18574        ] {
18575            let p = Placement {
18576                estrategia: s,
18577                clusters: vec!["rio".into()],
18578                affinity: None,
18579                // Route the paired `:shard-key` fixture-builder through the
18580                // typed cross-slot invariant predicate
18581                // [`PlacementStrategy::requires_shard_key`] rather than the
18582                // [`gen_platform::IsVariant`]-derived [`Self::is_sharded`]
18583                // arm-identity predicate — the two answer the same
18584                // question under today's closed accept-set but a future
18585                // arm addition that consumed `:shard-key` under a
18586                // non-`Sharded` name would silently mis-attach the
18587                // fixture's `:shard-key` if the builder read through the
18588                // arm-identity predicate. The cross-slot-invariant
18589                // predicate migrates through one caixa-core edit on any
18590                // future arm addition; the fixture keeps producing a
18591                // `validate()`-passing round-trip by construction.
18592                shard_key: if s.requires_shard_key() {
18593                    Some("$key".into())
18594                } else {
18595                    None
18596                },
18597            };
18598            let json = serde_json::to_string(&p).unwrap();
18599            let back: Placement = serde_json::from_str(&json).unwrap();
18600            assert_eq!(back, p);
18601        }
18602    }
18603
18604    #[test]
18605    fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
18606        // The fail-before-pass-after pin: pre-lift there was no
18607        // single-source binding between the [`PlacementStrategy`]
18608        // variant name the `Serialize` derive emits and the byte-
18609        // string every downstream cluster-side dispatcher (the
18610        // `lareira-fleet-programs` aggregator's per-entry strategy
18611        // branch, the future `app-operator` reconciler, the M3
18612        // Adaptive compression pass's per-strategy weighting) probes
18613        // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
18614        // future `#[serde(rename_all = "kebab-case")]` attribute on
18615        // the enum — or a variant rename in the source — would
18616        // silently rebrand the emitted scalar under one spelling
18617        // while every downstream dispatcher still probed the other,
18618        // with the failure surfacing at the aggregator's dispatch
18619        // step or the operator's reconcile posture (workloads coming
18620        // up under the `default()` `Replicated` arm rather than the
18621        // typed slot's declared strategy) far from the source
18622        // rebrand commit and with no field naming the drift. Pinning
18623        // the two paths (the `Serialize` derive's serialized string
18624        // AND the [`PlacementStrategy::as_str`] helper) to the same
18625        // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
18626        // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
18627        // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
18628        // makes any future drift on either endpoint fail here at
18629        // caixa-core build time.
18630        for (variant, expected) in [
18631            (
18632                PlacementStrategy::SingleNode,
18633                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
18634            ),
18635            (
18636                PlacementStrategy::Replicated,
18637                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
18638            ),
18639            (
18640                PlacementStrategy::Sharded,
18641                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
18642            ),
18643        ] {
18644            let json = serde_json::to_string(&variant).unwrap();
18645            assert_eq!(
18646                json,
18647                format!("\"{expected}\""),
18648                "PlacementStrategy::{variant:?} must serialize to {expected:?}"
18649            );
18650            assert_eq!(
18651                variant.as_str(),
18652                expected,
18653                "PlacementStrategy::{variant:?}.as_str() must return the lifted \
18654                 M3_PLACEMENT_ESTRATEGIA_* constant"
18655            );
18656        }
18657    }
18658
18659    #[test]
18660    fn m3_placement_estrategia_consts_are_pairwise_distinct() {
18661        // Cross-arm drift-detection pin on the M3
18662        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
18663        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
18664        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
18665        // scalar-value pentad: a future collapse of two canonical
18666        // variant byte-strings onto the same value (an accidental
18667        // copy-paste flip of
18668        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
18669        // read `"SingleNode"`, a per-arm rebrand that lands one const
18670        // without touching its paired peer) would silently reroute
18671        // every downstream operator's per-strategy dispatch onto the
18672        // sibling arm's reconcile branch and pass every
18673        // propagation-probe test that expected only the stale arm's
18674        // value — a `Replicated`-declared Aplicacao would come up
18675        // under the `SingleNode` primary-and-standby reconcile
18676        // posture, so every-cluster active-active workload would
18677        // silently collapse onto one-cluster-runs-at-a-time takeover
18678        // semantics against its declared strategy, with no field
18679        // naming the strategy-value drift root cause. Peer of the
18680        // sibling
18681        // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
18682        // (09ffb2d) /
18683        // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
18684        // (ccdf955) /
18685        // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
18686        // (d739850) distinctness pins on the sibling OTP-shape /
18687        // caixa-kind closed-set typed-enum discriminator axes — the
18688        // fourth (and structurally the M3 mesh-primitive-defining)
18689        // closed-set typed-enum axis to converge on the same
18690        // "pairwise-distinct-by-construction" discipline.
18691        //
18692        // Fail-before-pass-after locally verified by mutating
18693        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
18694        // also read `"SingleNode"` — this pin fires as expected;
18695        // restoring passes.
18696        let all = [
18697            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
18698            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
18699            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
18700        ];
18701        for (i, a) in all.iter().enumerate() {
18702            for (j, b) in all.iter().enumerate() {
18703                if i != j {
18704                    assert_ne!(
18705                        a, b,
18706                        "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
18707                         distinct — got duplicate {a:?} at indices {i} and {j}",
18708                    );
18709                }
18710            }
18711        }
18712    }
18713
18714    #[test]
18715    fn placement_strategy_display_routes_through_as_str_helper() {
18716        // The fail-before-pass-after pin: pre-lift the sibling
18717        // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
18718        // / [`crate::supervisor::RestartPolicy`] both carried a stable
18719        // [`std::fmt::Display`] surface via their
18720        // `#[discriminant(also_display)]` gen-platform derive, but
18721        // [`PlacementStrategy`] did not — every consumer reaching for
18722        // a strategy byte-string past the wire format had to pick
18723        // between three paths ([`PlacementStrategy::as_str`], the
18724        // `Serialize` derive's serialized string, or `format!("{v:?}")`
18725        // on the `Debug` derive), any two of which a future variant
18726        // rename or `#[serde(rename_all = "kebab-case")]` attribute
18727        // would silently desynchronize. Wiring [`std::fmt::Display`]
18728        // through [`PlacementStrategy::as_str`] closes the third path:
18729        // every `format!("{v}")` call reaches the same lifted
18730        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
18731        // and the [`PlacementStrategy::as_str`] helper already route
18732        // through, so a future variant rename lands at exactly one
18733        // place. Pin the routing here so a future
18734        // `impl std::fmt::Display for PlacementStrategy` reimplementation
18735        // that hand-rolls the arms instead of delegating to
18736        // [`PlacementStrategy::as_str`] fails at caixa-core build time.
18737        for variant in [
18738            PlacementStrategy::SingleNode,
18739            PlacementStrategy::Replicated,
18740            PlacementStrategy::Sharded,
18741        ] {
18742            assert_eq!(
18743                variant.to_string(),
18744                variant.as_str(),
18745                "PlacementStrategy::{variant:?} Display must route through \
18746                 PlacementStrategy::as_str (single source of truth: the lifted \
18747                 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
18748            );
18749        }
18750    }
18751
18752    #[test]
18753    fn placement_strategy_display_matches_serialized_wire_byte_string() {
18754        // The fail-before-pass-after pin on the second half of the
18755        // three-path convergence: `Display` (user-facing text) agrees
18756        // byte-for-byte with the `Serialize` derive's wire format
18757        // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
18758        // scalar) on every variant. Pre-lift the two paths were
18759        // structurally independent — a future
18760        // `#[serde(rename_all = "kebab-case")]` attribute on the enum
18761        // would silently rebrand the emitted wire scalar
18762        // (`single-node`, `replicated`, `sharded`) while every consumer
18763        // that pretty-prints the strategy (the M3 diagnostic templates,
18764        // the future `feira app graph` per-Aplicacao strategy line,
18765        // the future M4 CR materializer's admission-webhook rejection
18766        // body) would still emit the TitleCase form the `as_str` /
18767        // `Display` route returns, with the mismatch surfacing at
18768        // consumer parse time / operator dispatch time far from the
18769        // source rebrand commit. Pin the two paths byte-for-byte here
18770        // so any future serde-attribute or variant-rename drift is a
18771        // caixa-core-build-time test failure at this call, not a
18772        // silent per-consumer dispatch miss.
18773        for variant in [
18774            PlacementStrategy::SingleNode,
18775            PlacementStrategy::Replicated,
18776            PlacementStrategy::Sharded,
18777        ] {
18778            let wire = serde_json::to_string(&variant).unwrap();
18779            // Strip the outer `"…"` the JSON string form carries — the
18780            // wire scalar the K8s / YAML apiserver consumes is the
18781            // enclosed byte-string, not the quote wrapper.
18782            let unquoted = wire
18783                .strip_prefix('"')
18784                .and_then(|s| s.strip_suffix('"'))
18785                .expect("serialized PlacementStrategy is a JSON string");
18786            assert_eq!(
18787                variant.to_string(),
18788                unquoted,
18789                "PlacementStrategy::{variant:?} Display byte-string must match the \
18790                 Serialize derive's wire byte-string (three-path convergence: \
18791                 Display + as_str + Serialize all resolve to the same \
18792                 M3_PLACEMENT_ESTRATEGIA_* const)"
18793            );
18794        }
18795    }
18796
18797    #[test]
18798    fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
18799        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
18800        // derive on [`PlacementStrategy`]: for each of the three variants
18801        // exactly one of the generated `is_single_node` / `is_replicated`
18802        // / `is_sharded` predicates returns `true` and the other two
18803        // return `false`. Prior to this derive the three per-arm
18804        // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
18805        // (the `placement_strategy_variants_round_trip` fixture, the
18806        // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
18807        // fixture, and the
18808        // `validate_placement_reads_through_lifted_estrategia_accessor`
18809        // fixture) each open-coded a per-arm PartialEq compare against
18810        // the enum variant — three sites that expressed no compile-time
18811        // link back to the closed-set typed dispatch a future fourth
18812        // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
18813        // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
18814        // would have to thread through in lockstep or one fixture would
18815        // silently disagree with the others on which arms consume the
18816        // `:shard-key` axis. Peer of the sibling
18817        // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
18818        // / [`crate::supervisor::RestartPolicy`] /
18819        // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
18820        // the sibling closed-set typed-enum discriminator axes — extends
18821        // the same one-typed-dispatch-per-variant discipline onto the
18822        // fifth (and only remaining) closed-set typed-enum discriminator
18823        // on the caixa surface, closing the axis on the M3 mesh-slot
18824        // family.
18825        let rows: [(PlacementStrategy, [bool; 3]); 3] = [
18826            (PlacementStrategy::SingleNode, [true, false, false]),
18827            (PlacementStrategy::Replicated, [false, true, false]),
18828            (PlacementStrategy::Sharded, [false, false, true]),
18829        ];
18830        for (variant, expected) in rows {
18831            let observed = [
18832                variant.is_single_node(),
18833                variant.is_replicated(),
18834                variant.is_sharded(),
18835            ];
18836            assert_eq!(
18837                observed, expected,
18838                "PlacementStrategy::{variant:?} is_* predicates must partition \
18839                 the arm set (single_node, replicated, sharded); got {observed:?}"
18840            );
18841        }
18842    }
18843
18844    #[test]
18845    fn placement_strategy_is_variant_predicates_are_const_fn() {
18846        // The [`gen_platform::IsVariant`] derive emits `const fn`
18847        // predicates on the peer [`crate::CaixaKind`] +
18848        // [`crate::upgrade::UpgradeInstruction`] +
18849        // [`crate::supervisor::RestartStrategy`] +
18850        // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
18851        // pin the same posture on [`PlacementStrategy`] so a future
18852        // accidental downgrade to non-`const` (an added runtime helper
18853        // reachable only from a non-`const` context, a manual hand-rolled
18854        // `impl` that shadows the derive-generated method) trips at
18855        // caixa-core build time rather than surfacing as a downstream
18856        // `const`-context regression far from the derive declaration.
18857        //
18858        // The pin lives inside a `const { assert!(..) }` block so the
18859        // compiler enforces both halves (arm predicate is `const`-
18860        // callable AND returns `true` for the matching arm) at
18861        // caixa-core compile time — peer to the sibling
18862        // [`crate::CaixaKind::is_*`] + [`WitTarget::is_*`] const-block
18863        // pins on the closed-set typed enum arm-predicate const-
18864        // callability axis.
18865        const {
18866            assert!(PlacementStrategy::SingleNode.is_single_node());
18867            assert!(PlacementStrategy::Replicated.is_replicated());
18868            assert!(PlacementStrategy::Sharded.is_sharded());
18869        }
18870    }
18871
18872    #[test]
18873    fn placement_strategy_requires_shard_key_partitions_the_arm_set() {
18874        // Fail-before-pass-after pin on the substrate-lifted
18875        // [`PlacementStrategy::requires_shard_key`] cross-slot-invariant
18876        // per-arm predicate: for each variant in the closed accept-set the
18877        // predicate returns `true` iff the variant consumes the paired
18878        // [`Placement::shard_key`] axis under
18879        // [`AplicacaoSpec::validate_placement`]'s `Sharded` ↔ non-`Sharded`
18880        // partition. Today the accept-set is the singleton `{Sharded}` —
18881        // `Sharded` is the Akka-style hash-keyed distribution arm
18882        // (MESH-COMPOSITION §II.4), `SingleNode` (Erlang/OTP takeover —
18883        // §II.1) and `Replicated` (active-active) refuse the axis through
18884        // [`AplicacaoError::ShardKeyOnNonSharded`].
18885        //
18886        // Pins the per-arm truth-table so a future arm addition (an
18887        // `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint the
18888        // roadmap names, a `WeightedShard` promotion the future M5
18889        // adaptive-placement engine acknowledges) that landed a variant
18890        // without extending this predicate's arm-set would surface as a
18891        // caixa-core build-time exhaustiveness error at the
18892        // `match self { … }` arm-fan below rather than a silent per-consumer
18893        // mis-classification at renderer emit time. The paired
18894        // [`Self::is_sharded`] `gen_platform::IsVariant`-derived arm-identity
18895        // predicate stays a distinct question — arm-identity (which the
18896        // sibling
18897        // [`placement_strategy_is_variant_predicates_partition_the_arm_set`]
18898        // pin already locks) is not cross-slot-invariant consumption; today
18899        // they trip on the same singleton but the pair migrates through
18900        // one caixa-core edit on any future arm addition.
18901        //
18902        // Peer of the sibling per-arm classifier pins
18903        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
18904        // (7b97d26) on the [`WitContract`] pre-projection WIT-shape axis
18905        // and the [`WitTarget::is_capability`] `gen_platform::IsVariant`-
18906        // derived paired predicate on the post-projection typed-view axis
18907        // — same "per-arm semantic-classification predicate paired with
18908        // the arm-identity predicate the derive already emits" discipline
18909        // extended onto the M3 mesh-slot `:placement :estrategia` ↔
18910        // `:placement :shard-key` cross-slot-invariant axis.
18911        let rows: [(PlacementStrategy, bool); 3] = [
18912            (PlacementStrategy::SingleNode, false),
18913            (PlacementStrategy::Replicated, false),
18914            (PlacementStrategy::Sharded, true),
18915        ];
18916        for (variant, expected) in rows {
18917            assert_eq!(
18918                variant.requires_shard_key(),
18919                expected,
18920                "PlacementStrategy::{variant:?}.requires_shard_key() must \
18921                 be {expected} (the substrate-canonical cross-slot invariant \
18922                 on the :placement :shard-key axis; today `Sharded` is the \
18923                 singleton consuming arm — MESH-COMPOSITION §II.4)",
18924            );
18925        }
18926    }
18927
18928    #[test]
18929    fn placement_strategy_requires_shard_key_is_const_fn() {
18930        // The [`PlacementStrategy::requires_shard_key`] cross-slot-
18931        // invariant per-arm predicate is declared `#[must_use] pub const
18932        // fn` — pin the `const`-eval posture here so a future accidental
18933        // downgrade to non-`const` (an added runtime helper reachable
18934        // only from a non-`const` context, a manual hand-rolled `impl`
18935        // that shadows the current three-arm `match self { … }` dispatch)
18936        // trips at caixa-core build time rather than surfacing as a
18937        // downstream `const`-context regression far from the declaration.
18938        // Same shape as the sibling
18939        // [`placement_strategy_is_variant_predicates_are_const_fn`] pin on
18940        // the peer [`gen_platform::IsVariant`]-derived arm-identity
18941        // predicate axis, but here the load-bearing assertions live in
18942        // module-scope `const _: () = assert!(…)` items so a violation
18943        // fails at compile time (const-eval trip) rather than test time —
18944        // strictly stronger than the runtime `assert!(CONST)` pattern the
18945        // sibling pin uses, and side-steps the
18946        // `clippy::assertions_on_constants` lint the runtime pattern
18947        // otherwise accumulates on the module baseline.
18948        //
18949        // The test body simply witnesses that the module-scope items
18950        // compiled and the runtime dispatch agrees with the const-eval
18951        // dispatch on every arm — the runtime read gives the test a
18952        // failure surface (rather than an empty test body clippy would
18953        // flag as a no-op).
18954        const REQUIRES_SINGLE_NODE: bool = PlacementStrategy::SingleNode.requires_shard_key();
18955        const REQUIRES_REPLICATED: bool = PlacementStrategy::Replicated.requires_shard_key();
18956        const REQUIRES_SHARDED: bool = PlacementStrategy::Sharded.requires_shard_key();
18957        assert_eq!(
18958            [REQUIRES_SINGLE_NODE, REQUIRES_REPLICATED, REQUIRES_SHARDED,],
18959            [
18960                PlacementStrategy::SingleNode.requires_shard_key(),
18961                PlacementStrategy::Replicated.requires_shard_key(),
18962                PlacementStrategy::Sharded.requires_shard_key(),
18963            ],
18964            "runtime and const-eval dispatch on \
18965             PlacementStrategy::requires_shard_key must agree on every arm",
18966        );
18967    }
18968
18969    #[test]
18970    fn placement_estrategia_accessor_is_const_fn() {
18971        // The [`Placement::estrategia`] per-`:placement` distribution-
18972        // strategy `Copy`-return scalar accessor is declared
18973        // `#[must_use] pub const fn` — matching the peer M3 mesh-slot
18974        // `Copy`-return accessor family ([`MeshPolicy::timeout`] /
18975        // [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
18976        // [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`]
18977        // on the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`]
18978        // / [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
18979        // [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
18980        // [`RateLimit`], every one a `pub const fn`). Pin the
18981        // `const`-eval posture here so a future accidental downgrade to
18982        // non-`const` (an added runtime helper reachable only from a
18983        // non-`const` context, a slot promotion to a non-`Copy` return
18984        // that would silently drop the `const` qualifier, a manual
18985        // hand-rolled shadow) trips at caixa-core build time rather
18986        // than surfacing as a downstream `const`-context regression far
18987        // from the declaration.
18988        //
18989        // Same shape as the sibling
18990        // [`placement_strategy_requires_shard_key_is_const_fn`] pin on
18991        // the peer [`PlacementStrategy::requires_shard_key`] `const fn`
18992        // predicate axis — the load-bearing witness lives in the
18993        // module-scope `const fn` wrapper `estrategia_via_const_fn`
18994        // below: a body that calls [`Placement::estrategia`] under a
18995        // `const fn` signature is well-formed only when the callee is
18996        // itself `const fn`, so any future accidental downgrade of
18997        // [`Placement::estrategia`] to non-`const` fails at caixa-core
18998        // build time (const-eval E0015 / E0658 depending on the arm),
18999        // strictly stronger than a runtime `assert!(CONST)` and
19000        // side-stepping the destructor-in-const restriction that
19001        // blocks direct `const _: PlacementStrategy = FIXTURE.estrategia()`
19002        // items on `Placement`'s `Vec<String>` / `Option<String>`
19003        // carriers.
19004        //
19005        // The runtime body witnesses that the const-eval-shaped
19006        // wrapper agrees with a direct call on every closed-set arm.
19007        const fn estrategia_via_const_fn(p: &Placement) -> PlacementStrategy {
19008            p.estrategia()
19009        }
19010        for estrategia in [
19011            PlacementStrategy::SingleNode,
19012            PlacementStrategy::Replicated,
19013            PlacementStrategy::Sharded,
19014        ] {
19015            let placement = Placement {
19016                estrategia,
19017                clusters: Vec::new(),
19018                affinity: None,
19019                shard_key: None,
19020            };
19021            assert_eq!(
19022                estrategia_via_const_fn(&placement),
19023                placement.estrategia(),
19024                "const-fn-wrapped and direct dispatch on \
19025                 Placement::estrategia must agree for {estrategia:?}",
19026            );
19027        }
19028    }
19029
19030    #[test]
19031    fn entrada_port_accessor_is_const_fn() {
19032        // The [`Entrada::port`] per-`:entrada` L4-port `Copy`-return
19033        // scalar accessor is declared `#[must_use] pub const fn` —
19034        // matching the peer M3 mesh-slot `Copy`-return accessor family
19035        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`] /
19036        // [`MeshPolicy::mtls_required`] / [`MeshPolicy::rate_limit`] /
19037        // [`MeshPolicy::circuit_breaker`] on the parent [`MeshPolicy`],
19038        // [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
19039        // on the sibling [`CircuitBreaker`], [`RateLimit::rate`] /
19040        // [`RateLimit::window`] on the sibling [`RateLimit`], the
19041        // sibling per-`:placement` [`Placement::estrategia`] pinned by
19042        // [`placement_estrategia_accessor_is_const_fn`] above — every
19043        // one a `pub const fn`). Pin the `const`-eval posture here so
19044        // a future accidental downgrade to non-`const` (an added
19045        // runtime helper reachable only from a non-`const` context, an
19046        // `Option<u16>`-shape migration once the substrate grows
19047        // per-`:membros` heterogeneous listener ports that would
19048        // silently drop the `const` qualifier, a manual hand-rolled
19049        // shadow) trips at caixa-core build time rather than surfacing
19050        // as a downstream `const`-context regression far from the
19051        // declaration.
19052        //
19053        // Same shape as the sibling
19054        // [`placement_estrategia_accessor_is_const_fn`] pin above — the
19055        // load-bearing witness lives in the module-scope `const fn`
19056        // wrapper `port_via_const_fn`: a body that calls
19057        // [`Entrada::port`] under a `const fn` signature is well-formed
19058        // only when the callee is itself `const fn`, side-stepping the
19059        // destructor-in-const restriction that would otherwise block a
19060        // direct `const _: u16 = FIXTURE.port()` item on `Entrada`'s
19061        // `String` / `Vec<String>` carriers.
19062        //
19063        // The runtime body sweeps a representative port set spanning
19064        // the [`SERVICO_PORT_MIN`] floor, the substrate-canonical
19065        // [`DEFAULT_SERVICO_PORT`] default, and the top-edge `u16::MAX`
19066        // ceiling — the const-fn-wrapped call must agree with a direct
19067        // call on every fixture (a violation trips the test) and every
19068        // returned scalar must byte-equal the input `port` (a violation
19069        // means the accessor stopped being a raw field-return copy).
19070        const fn port_via_const_fn(e: &Entrada) -> u16 {
19071            e.port()
19072        }
19073        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, u16::MAX] {
19074            let entrada = Entrada {
19075                host: String::new(),
19076                para: String::new(),
19077                port,
19078                paths: Vec::new(),
19079            };
19080            assert_eq!(
19081                port_via_const_fn(&entrada),
19082                entrada.port(),
19083                "const-fn-wrapped and direct dispatch on Entrada::port \
19084                 must agree for port={port}",
19085            );
19086            assert_eq!(
19087                entrada.port(),
19088                port,
19089                "Entrada::port must return the storage-side u16 verbatim \
19090                 for port={port}",
19091            );
19092        }
19093    }
19094
19095    #[test]
19096    fn validate_placement_admits_paired_shape_iff_strategy_requires_shard_key() {
19097        // Load-bearing cross-slot-partition pin closing the loop between
19098        // the substrate-lifted
19099        // [`PlacementStrategy::requires_shard_key`] per-arm predicate on
19100        // the closed-set typed enum and the actual
19101        // [`AplicacaoSpec::validate_placement`] runtime behavior across
19102        // the paired `:placement :shard-key` axis: every validated
19103        // [`Placement`] past [`AplicacaoSpec::validate_placement`]
19104        // satisfies `placement.shard_key().is_some() ==
19105        // placement.estrategia().requires_shard_key()`. The four-cell
19106        // shape witness sweeps every combination of (variant in the
19107        // closed accept-set, `:shard-key` Some/None) and pins:
19108        //
19109        //   * variant.requires_shard_key() && shard_key.is_some() →
19110        //     validate() passes; the paired shape is the sole
19111        //     `requires_shard_key` arm-family accepted shape.
19112        //   * variant.requires_shard_key() && shard_key.is_none() →
19113        //     validate() fails with [`AplicacaoError::ShardedWithoutKey`];
19114        //     the paired shape is the refused missing-key shape on
19115        //     Sharded-family arms.
19116        //   * !variant.requires_shard_key() && shard_key.is_some() →
19117        //     validate() fails with
19118        //     [`AplicacaoError::ShardKeyOnNonSharded`]; the paired shape
19119        //     is the refused declared-but-inert shape on non-Sharded-
19120        //     family arms.
19121        //   * !variant.requires_shard_key() && shard_key.is_none() →
19122        //     validate() passes; the paired shape is the sole
19123        //     non-`requires_shard_key` arm-family accepted shape.
19124        //
19125        // The compile-time-exhaustive `match p.estrategia()` dispatch at
19126        // [`AplicacaoSpec::validate_placement`] preserves its structural
19127        // arm-fan (a future arm addition still surfaces a build-time
19128        // exhaustiveness error there); this pin closes the semantic loop
19129        // between the arm-fan's shape-gate cascades and the substrate-
19130        // canonical predicate every downstream consumer of the paired
19131        // shape reads through. Fail-before-pass-after locally verified by
19132        // mutating the predicate's `Sharded => true` arm to `false` — the
19133        // truthy `expects_ok` cell for `Sharded` + `Some` trips the
19134        // `validate() must pass` assertion; restoring passes. Same "close
19135        // the loop between the typed predicate and the runtime behavior"
19136        // discipline as the sibling
19137        // [`wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant`]
19138        // (7b97d26) cross-projection pin on the peer [`WitTarget`]
19139        // per-arm classifier axis.
19140        for variant in [
19141            PlacementStrategy::SingleNode,
19142            PlacementStrategy::Replicated,
19143            PlacementStrategy::Sharded,
19144        ] {
19145            for present in [false, true] {
19146                let mut spec = three_member_spec();
19147                spec.placement.estrategia = variant;
19148                spec.placement.shard_key = present.then(|| "tenantId".into());
19149                let expects_ok = variant.requires_shard_key() == present;
19150                let result = spec.validate();
19151                match (expects_ok, &result) {
19152                    (true, Ok(())) => {}
19153                    (false, Err(err)) => {
19154                        // Cross-check the refusal diagnostic names the
19155                        // right cell of the four-cell shape witness — the
19156                        // `requires_shard_key && !present` cell must trip
19157                        // [`AplicacaoError::ShardedWithoutKey`]; the
19158                        // `!requires_shard_key && present` cell must trip
19159                        // [`AplicacaoError::ShardKeyOnNonSharded`].
19160                        match (variant.requires_shard_key(), present, err) {
19161                            (true, false, AplicacaoError::ShardedWithoutKey) => {}
19162                            (
19163                                false,
19164                                true,
19165                                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. },
19166                            ) => {
19167                                assert_eq!(
19168                                    *e, variant,
19169                                    "ShardKeyOnNonSharded.estrategia must byte-equal \
19170                                     the paired PlacementStrategy",
19171                                );
19172                            }
19173                            _ => panic!(
19174                                "unexpected refusal for estrategia={variant:?} \
19175                                 present={present}: {err:?}"
19176                            ),
19177                        }
19178                    }
19179                    (true, Err(err)) => panic!(
19180                        "validate() must pass for estrategia={variant:?} \
19181                         present={present} (requires_shard_key={} == present={present}), \
19182                         got {err:?}",
19183                        variant.requires_shard_key(),
19184                    ),
19185                    (false, Ok(())) => panic!(
19186                        "validate() must fail for estrategia={variant:?} \
19187                         present={present} (requires_shard_key={} != present={present})",
19188                        variant.requires_shard_key(),
19189                    ),
19190                }
19191            }
19192        }
19193    }
19194
19195    #[test]
19196    fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
19197        // Pin the M3 diagnostic template routes through the typed
19198        // [`PlacementStrategy`] Display byte-string (rebound from the
19199        // prior `{estrategia:?}` `Debug` route). Pre-lift the two
19200        // routes emitted identical bytes (the `Debug` derive on a
19201        // unit variant emits the variant name verbatim, exactly what
19202        // `as_str` returns), but the two paths were structurally
19203        // independent — a future `#[serde(rename_all = "…")]`
19204        // attribute or variant rename would coordinate the wire /
19205        // `Display` / `as_str` triple through the lifted const but
19206        // leave the `Debug` route on the compiler-derived variant name,
19207        // silently desynchronizing the diagnostic byte-string from the
19208        // wire byte-string. Rebinding the template onto `Display`
19209        // ties the diagnostic to the same lifted
19210        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
19211        // emits — drift becomes structurally impossible. Pin the
19212        // byte-string here so a future edit that reverts the template
19213        // to `{estrategia:?}` is caught at caixa-core test time, not
19214        // at consumer dispatch time.
19215        for (variant, expected_scalar) in [
19216            (
19217                PlacementStrategy::SingleNode,
19218                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
19219            ),
19220            (
19221                PlacementStrategy::Replicated,
19222                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
19223            ),
19224            (
19225                PlacementStrategy::Sharded,
19226                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
19227            ),
19228        ] {
19229            let err = AplicacaoError::PlacementWithoutClusters {
19230                estrategia: variant,
19231            };
19232            let msg = err.to_string();
19233            assert!(
19234                msg.starts_with(&format!(":placement {expected_scalar} requires")),
19235                "PlacementWithoutClusters diagnostic for {variant:?} must open \
19236                 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
19237            );
19238        }
19239    }
19240
19241    #[test]
19242    fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
19243        // Peer of
19244        // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
19245        // on the second M3 diagnostic that carries the typed
19246        // [`PlacementStrategy`] in its `#[error(…)]` template. Both
19247        // diagnostics now route the strategy scalar through the same
19248        // [`std::fmt::Display`] surface, tying the diagnostic
19249        // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
19250        // const set the wire format also emits. The two non-Sharded
19251        // arms are exercised here (the diagnostic exists to flag a
19252        // `:shard-key` slot the current strategy will never consume);
19253        // the peer `Sharded` arm never reaches this diagnostic (the
19254        // `Sharded` strategy consumes `:shard-key` — the
19255        // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
19256        // slot instead).
19257        for (variant, expected_scalar) in [
19258            (
19259                PlacementStrategy::SingleNode,
19260                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
19261            ),
19262            (
19263                PlacementStrategy::Replicated,
19264                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
19265            ),
19266        ] {
19267            let err = AplicacaoError::ShardKeyOnNonSharded {
19268                estrategia: variant,
19269                shard_key: "$tenantId".into(),
19270            };
19271            let msg = err.to_string();
19272            assert!(
19273                msg.starts_with(&format!(":placement {expected_scalar} carries")),
19274                "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
19275                 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
19276            );
19277        }
19278    }
19279
19280    #[test]
19281    fn placement_strategy_all_enumerates_every_variant_once() {
19282        // Fail-before-pass-after pin on the [`PlacementStrategy::ALL`]
19283        // exhaustive-iteration surface: every variant appears exactly
19284        // once, and the slice length matches the arm count of the
19285        // closed set. Every consumer that walks the accepted-strategy
19286        // set (a future `feira app placement --list` CLI-side surfacing,
19287        // a future M4 admission-webhook's rejection body naming the
19288        // accepted-strategy list, the [`PlacementStrategy::from_wire`]
19289        // reverse-projection consumers that iterate the accept-set for
19290        // a "did you mean" hint) reads through this slice, so a future
19291        // variant addition (an `Anycast` mesh-anycast arm the
19292        // MESH-COMPOSITION §II.5 hint names as a trajectory item) that
19293        // grows the enum but forgets to grow [`Self::ALL`] silently
19294        // truncates every downstream consumer's accept-set at the same
19295        // pre-addition boundary — this pin fails at caixa-core build
19296        // time on the pairwise-distinct + arm-count invariants.
19297        //
19298        // Peer of the sibling [`RateLimitUnit::ALL`] (6bce03d) /
19299        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
19300        // pins on the peer closed-set typed-enum axes.
19301        let all: &[PlacementStrategy] = PlacementStrategy::ALL;
19302        assert_eq!(
19303            all.len(),
19304            3,
19305            "PlacementStrategy::ALL must enumerate every variant of the \
19306             three-arm closed set (SingleNode, Replicated, Sharded); got {all:?}"
19307        );
19308        for (i, a) in all.iter().enumerate() {
19309            for (j, b) in all.iter().enumerate() {
19310                if i != j {
19311                    assert_ne!(
19312                        a, b,
19313                        "PlacementStrategy::ALL must carry every variant exactly \
19314                         once — got duplicate {a:?} at indices {i} and {j}"
19315                    );
19316                }
19317            }
19318        }
19319        for variant in [
19320            PlacementStrategy::SingleNode,
19321            PlacementStrategy::Replicated,
19322            PlacementStrategy::Sharded,
19323        ] {
19324            assert!(
19325                all.contains(&variant),
19326                "PlacementStrategy::ALL must contain {variant:?} — a future variant \
19327                 addition that grows the enum but forgets to grow the ALL slice \
19328                 silently truncates every downstream consumer's accept-set at the \
19329                 pre-addition boundary"
19330            );
19331        }
19332    }
19333
19334    #[test]
19335    fn placement_strategy_from_wire_accepts_every_lifted_constant() {
19336        // Fail-before-pass-after pin on the forward accept-set of the
19337        // [`PlacementStrategy::from_wire`] reverse projection: every
19338        // canonical [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
19339        // constant the [`PlacementStrategy::as_str`] emitter walks
19340        // parses back to its paired variant. Any future arm addition
19341        // that grows the emitter's `as_str` match but forgets to grow
19342        // the parser's `from_str` match silently splits the two halves
19343        // of the round-trip — the wire byte-string one non-serde
19344        // consumer parses from the one the emitter wrote — with the
19345        // failure surfacing at parse time far from the rebrand commit.
19346        // Pinning the three-arm accept-set here catches the drift at
19347        // caixa-core build time.
19348        //
19349        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
19350        // + [`RateLimitUnit::from_suffix`] accept-set pins on the peer
19351        // closed-set typed-enum `str → Self` axes.
19352        for (wire, expected) in [
19353            (
19354                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
19355                PlacementStrategy::SingleNode,
19356            ),
19357            (
19358                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
19359                PlacementStrategy::Replicated,
19360            ),
19361            (
19362                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
19363                PlacementStrategy::Sharded,
19364            ),
19365        ] {
19366            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
19367                panic!(
19368                    "PlacementStrategy::from_wire({wire:?}) must accept every \
19369                     M3_PLACEMENT_ESTRATEGIA_* constant — got None for the \
19370                     lifted canonical byte-string that PlacementStrategy::{expected:?} \
19371                     serializes as under M3_PLACEMENT_KEY_ESTRATEGIA"
19372                )
19373            });
19374            assert_eq!(
19375                parsed, expected,
19376                "PlacementStrategy::from_wire({wire:?}) must return \
19377                 PlacementStrategy::{expected:?}; got PlacementStrategy::{parsed:?}"
19378            );
19379        }
19380    }
19381
19382    #[test]
19383    fn placement_strategy_from_wire_round_trips_through_as_str() {
19384        // Fail-before-pass-after pin on the closed round-trip between
19385        // the forward [`PlacementStrategy::as_str`] emitter and the
19386        // reverse [`PlacementStrategy::from_wire`] parser: for every
19387        // variant in [`PlacementStrategy::ALL`], parsing the emitter's
19388        // output must return exactly the same variant. Any per-arm
19389        // divergence — a future arm added to `as_str` but not
19390        // `from_str`, an accidental copy-paste flip in one but not the
19391        // other — silently splits the emit and parse halves and the
19392        // failure surfaces at consumer parse time far from the drift
19393        // site. The `ALL`-iterating shape means a future variant
19394        // addition picks up the coverage by construction.
19395        //
19396        // Peer of the sibling [`crate::kind::tests`] round-trip pin on
19397        // [`crate::CaixaKind::from_wire`] and the
19398        // [`super::tests::rate_limit_unit_from_suffix_round_trips_through_as_suffix`]
19399        // sibling round-trip pin on [`RateLimitUnit`].
19400        for &variant in PlacementStrategy::ALL {
19401            let wire = variant.as_str();
19402            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
19403                panic!(
19404                    "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
19405                     must be Some({variant:?}) — the two halves of the round-trip \
19406                     dispatch on the same lifted M3_PLACEMENT_ESTRATEGIA_* consts; \
19407                     got None on wire byte-string {wire:?}"
19408                )
19409            });
19410            assert_eq!(
19411                parsed, variant,
19412                "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
19413                 must round-trip to the same variant; got {parsed:?}"
19414            );
19415        }
19416    }
19417
19418    #[test]
19419    fn placement_strategy_from_wire_rejects_unknown_byte_strings() {
19420        // Fail-before-pass-after pin on the closed-set refusal
19421        // discipline of [`PlacementStrategy::from_wire`]: every
19422        // byte-string outside the three-arm accept-set returns `None`
19423        // rather than silently collapsing onto the [`Default`]
19424        // (`Replicated`) arm or an arbitrary neighbor. The refusal set
19425        // exercised here sweeps the load-bearing drift shapes: the
19426        // empty string (a stripped serde-attribute drift), an all-
19427        // whitespace string (the canonical text-editor accidental
19428        // padding shape), the lowercased kebab-case forms a future
19429        // `#[serde(rename_all = "kebab-case")]` attribute would emit
19430        // (`"single-node"`, `"replicated"`, `"sharded"` — the last two
19431        // coincidentally match the accepted canonical scalars, so only
19432        // `"single-node"` fires as a refusal, but pinning the case-
19433        // sensitivity of the accepted arms via the peer [`SingleNode`]
19434        // assertion in the round-trip pin makes the discipline
19435        // structurally clear), the lowercased single-word forms
19436        // (`"singlenode"`), the padded canonical scalar
19437        // (`" Sharded "`), the trailing-comma / trailing-newline shapes
19438        // (`"Sharded\n"`), and a pointer-different `&'static str` that
19439        // happens to alias a canonical byte-string by content but not
19440        // by identity (validated implicitly by the emitter's routing
19441        // through `crate::render::M3_PLACEMENT_ESTRATEGIA_*`, whose
19442        // identity a paired [`crate::assert_str_reexport_identity`] pin
19443        // in caixa-core's per-const declaration surface would catch).
19444        //
19445        // Peer of the sibling
19446        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
19447        // (2aa6d23) refusal pin on [`crate::CaixaKind::from_wire`].
19448        for bad in [
19449            "",
19450            " ",
19451            "\n",
19452            "\t",
19453            "single-node",
19454            "singlenode",
19455            "SingleNodes",
19456            "single_node",
19457            "single node",
19458            "SINGLENODE",
19459            "SingleNode ",
19460            " SingleNode",
19461            " Sharded ",
19462            "Sharded\n",
19463            "replicated ",
19464            "sharded",
19465            "REPLICATED",
19466            "Anycast",
19467            "Global",
19468            "?",
19469        ] {
19470            assert!(
19471                PlacementStrategy::from_wire(bad).is_none(),
19472                "PlacementStrategy::from_wire({bad:?}) must return None — the \
19473                 parser's accept-set is exactly the three PlacementStrategy::as_str \
19474                 outputs (SingleNode, Replicated, Sharded), and this byte-string \
19475                 is outside that closed set"
19476            );
19477        }
19478    }
19479
19480    #[test]
19481    fn placement_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
19482        // Fail-before-pass-after pin on the third path of the four-path
19483        // convergence: `from_str` (the reverse projection) inverts the
19484        // `Serialize` derive's wire byte-string on every variant.
19485        // Together with the pre-existing three-path convergence
19486        // (`Display` + `as_str` + `Serialize` all resolve to the same
19487        // lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const, pinned by
19488        // the peer
19489        // [`placement_strategy_display_matches_serialized_wire_byte_string`])
19490        // this closes the round-trip: the wire byte-string the
19491        // `Serialize` derive emits parses back to the same variant
19492        // through `from_str`, so any future serde-attribute or variant-
19493        // rename drift on the emit half now surfaces as a matched drift
19494        // on the parse half at caixa-core build time — the two halves
19495        // migrate as a unit through the lifted consts on any future
19496        // rename, and the round-trip cannot silently split.
19497        //
19498        // Peer of the sibling
19499        // [`placement_strategy_display_matches_serialized_wire_byte_string`]
19500        // wire-format pin — extends the three-path convergence
19501        // (`Display` + `as_str` + `Serialize`) onto the fourth path
19502        // (`from_str`), closing the `str ↔ Self` round-trip on the
19503        // M3 `:placement :estrategia` closed-set axis.
19504        for &variant in PlacementStrategy::ALL {
19505            let wire = serde_json::to_string(&variant).unwrap();
19506            let unquoted = wire
19507                .strip_prefix('"')
19508                .and_then(|s| s.strip_suffix('"'))
19509                .expect("serialized PlacementStrategy is a JSON string");
19510            let parsed = PlacementStrategy::from_wire(unquoted).unwrap_or_else(|| {
19511                panic!(
19512                    "PlacementStrategy::from_wire({unquoted:?}) must accept the \
19513                     Serialize derive's wire byte-string for \
19514                     PlacementStrategy::{variant:?} — the four-path convergence \
19515                     (Display + as_str + Serialize + from_str) resolves through \
19516                     the same lifted M3_PLACEMENT_ESTRATEGIA_* const; got None"
19517                )
19518            });
19519            assert_eq!(
19520                parsed, variant,
19521                "PlacementStrategy::from_wire of the Serialize derive's wire \
19522                 byte-string for PlacementStrategy::{variant:?} must round-trip \
19523                 to the same variant; got {parsed:?}"
19524            );
19525        }
19526    }
19527
19528    #[test]
19529    fn rejects_zero_policy_timeout() {
19530        let mut s = three_member_spec();
19531        s.politicas.timeout = Some(Duration::ZERO);
19532        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
19533    }
19534
19535    #[test]
19536    fn rejects_zero_policy_retries() {
19537        let mut s = three_member_spec();
19538        s.politicas.retries = Some(0);
19539        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
19540    }
19541
19542    #[test]
19543    fn rejects_policy_retries_above_cap() {
19544        // The fail-before-pass-after pin: `Some(11)` is structurally
19545        // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
19546        // passed validate on every pre-gate codebase because the
19547        // typed slot's only check was the zero-floor arm. The
19548        // thundering-herd amplification vector only surfaced at the
19549        // runtime substrate (Envoy / Cilium L7 retry overlay)
19550        // far from the source caixa.lisp with no field naming the
19551        // offending policy.
19552        let mut s = three_member_spec();
19553        s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
19554        assert_eq!(
19555            s.validate().unwrap_err(),
19556            AplicacaoError::PolicyRetriesExceedsCap {
19557                retries: POLICY_RETRIES_MAX + 1
19558            }
19559        );
19560    }
19561
19562    #[test]
19563    fn rejects_policy_retries_far_above_cap() {
19564        // The `u32::MAX` worst case — the four-billion-retry policy
19565        // a typo (`(:retries 4294967295)`) or struct-literal
19566        // copy-paste lands in the slot. Pin the cap arm's coverage
19567        // explicitly across the full `u32` overflow so a future
19568        // relaxation that drops the upper bound surfaces here.
19569        let mut s = three_member_spec();
19570        s.politicas.retries = Some(u32::MAX);
19571        assert_eq!(
19572            s.validate().unwrap_err(),
19573            AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
19574        );
19575    }
19576
19577    #[test]
19578    fn accepts_policy_retries_at_cap() {
19579        // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
19580        // must validate. The cap is inclusive on the top edge,
19581        // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
19582        // discipline on the sibling [`crate::LimitsSpec::memory`]
19583        // axis. Pin the boundary explicitly so a future off-by-one
19584        // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
19585        // surfaces here as a test failure rather than a silent
19586        // contract narrowing.
19587        let mut s = three_member_spec();
19588        s.politicas.retries = Some(POLICY_RETRIES_MAX);
19589        s.validate()
19590            .expect("retries == POLICY_RETRIES_MAX must validate");
19591    }
19592
19593    #[test]
19594    fn accepts_policy_retries_typical_values() {
19595        // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
19596        // every value in the validated set must pass. The
19597        // Envoy / Istio production-playbook recommendation band
19598        // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
19599        // (`maxRetries ≤ 10`) both lie within this set.
19600        for r in 1..=POLICY_RETRIES_MAX {
19601            let mut s = three_member_spec();
19602            s.politicas.retries = Some(r);
19603            s.validate()
19604                .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
19605        }
19606    }
19607
19608    #[test]
19609    fn policy_retries_zero_takes_precedence_over_cap() {
19610        // The cross-arm ordering pin: `Some(0)` is structurally
19611        // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
19612        // (cap), but the zero-floor diagnostic is the more
19613        // self-locating one (it directly names the omit-axis
19614        // remediation), so the validate gate must fire on zero
19615        // first. Pin the order so a future refactor that reorders
19616        // the arms surfaces here as a test failure rather than a
19617        // silent diagnostic regression. Same shape every other
19618        // zero-then-shape ordering on this surface uses
19619        // ([`AplicacaoError::PolicyTimeoutZero`] then
19620        // [`AplicacaoError::PolicyTimeoutNotCanonical`];
19621        // [`AplicacaoError::PolicyBreakerZeroWindow`] then
19622        // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
19623        let mut s = three_member_spec();
19624        s.politicas.retries = Some(0);
19625        assert_eq!(
19626            s.validate().unwrap_err(),
19627            AplicacaoError::PolicyRetriesZero,
19628            "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
19629        );
19630    }
19631
19632    #[test]
19633    fn policy_retries_cap_diagnostic_carries_offending_value() {
19634        // The diagnostic-shape pin: the offending `u32` is carried
19635        // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
19636        // variant so the surfaced error message names the value the
19637        // author wrote (`":politicas :retries (47) exceeds the
19638        // mesh-policy ceiling …"`), not just the cap. Same
19639        // self-locating diagnostic shape every other typed-cap arm
19640        // on this surface carries
19641        // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
19642        // offending byte count verbatim).
19643        let mut s = three_member_spec();
19644        s.politicas.retries = Some(47);
19645        let err = s.validate().unwrap_err();
19646        assert!(
19647            matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
19648            "got {err:?}"
19649        );
19650        let msg = err.to_string();
19651        assert!(
19652            msg.contains("47"),
19653            ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
19654        );
19655    }
19656
19657    #[test]
19658    fn policy_retries_cap_is_aws_app_mesh_aligned() {
19659        // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
19660        // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
19661        // schema cap — the only upstream mesh-policy schema that
19662        // documents an explicit hard cap. Pinning the literal value
19663        // here surfaces a future drift (a relaxation to 20, a
19664        // tightening to 5) as a deliberate test edit, not a silent
19665        // contract narrowing.
19666        assert_eq!(POLICY_RETRIES_MAX, 10);
19667    }
19668
19669    #[test]
19670    fn rejects_circuit_breaker_zero_max_failures() {
19671        let mut s = three_member_spec();
19672        s.politicas.circuit_breaker = Some(CircuitBreaker {
19673            max_failures: 0,
19674            window: Duration::from_secs(60),
19675        });
19676        assert_eq!(
19677            s.validate().unwrap_err(),
19678            AplicacaoError::PolicyBreakerZeroFailures
19679        );
19680    }
19681
19682    #[test]
19683    fn rejects_circuit_breaker_max_failures_above_cap() {
19684        // The fail-before-pass-after pin: `1001` is structurally one
19685        // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
19686        // silently passed validate on every pre-gate codebase
19687        // because the typed slot's only check was the zero-floor
19688        // arm. The breaker-no-op vector only surfaced at the runtime
19689        // substrate (Envoy / Cilium L7 outlier-detection overlay)
19690        // far from the source caixa.lisp with no field naming the
19691        // offending policy.
19692        let mut s = three_member_spec();
19693        s.politicas.circuit_breaker = Some(CircuitBreaker {
19694            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
19695            window: Duration::from_secs(60),
19696        });
19697        assert_eq!(
19698            s.validate().unwrap_err(),
19699            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
19700                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
19701            }
19702        );
19703    }
19704
19705    #[test]
19706    fn rejects_circuit_breaker_max_failures_far_above_cap() {
19707        // The `u32::MAX` worst case — the four-billion-failure
19708        // threshold a typo (`(:max-failures 4294967295)`) or a
19709        // struct-literal copy-paste lands in the slot. Pin the cap
19710        // arm's coverage explicitly across the full `u32` overflow
19711        // so a future relaxation that drops the upper bound surfaces
19712        // here.
19713        let mut s = three_member_spec();
19714        s.politicas.circuit_breaker = Some(CircuitBreaker {
19715            max_failures: u32::MAX,
19716            window: Duration::from_secs(60),
19717        });
19718        assert_eq!(
19719            s.validate().unwrap_err(),
19720            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
19721                max_failures: u32::MAX,
19722            }
19723        );
19724    }
19725
19726    #[test]
19727    fn accepts_circuit_breaker_max_failures_at_cap() {
19728        // The boundary value — exactly
19729        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
19730        // cap is inclusive on the top edge, matching the
19731        // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
19732        // discipline on the sibling capped axes. Pin the boundary
19733        // explicitly so a future off-by-one tightening
19734        // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
19735        // surfaces here as a test failure rather than a silent
19736        // contract narrowing.
19737        let mut s = three_member_spec();
19738        s.politicas.circuit_breaker = Some(CircuitBreaker {
19739            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
19740            window: Duration::from_secs(60),
19741        });
19742        s.validate()
19743            .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
19744    }
19745
19746    #[test]
19747    fn accepts_circuit_breaker_max_failures_typical_values() {
19748        // The documented production-playbook band positive-control
19749        // sweep — every value Hystrix / Istio / Envoy / Polly /
19750        // Resilience4j recommend (5..=50) must pass, plus a sweep
19751        // through the hyperscale band (100, 500, 1000) the cap
19752        // accepts. Pin the inclusive validated set explicitly so a
19753        // future tightening of the ceiling surfaces here.
19754        //
19755        // Clears the fixture's `:retries` (which is `Some(3)`) so this
19756        // per-axis sweep is pure: the sibling cross-axis
19757        // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
19758        // gate rejects any `max_failures <= retries` pair, so the
19759        // `max_failures = 1` boundary at the head of the sweep would
19760        // otherwise trip on the fixture-inherited retry policy rather
19761        // than the per-axis boundary this test names. Same discipline
19762        // the sibling per-axis `accepts_circuit_breaker_window_*`
19763        // sweeps take against the fixture's `:timeout` for the
19764        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`]
19765        // cross-axis arm.
19766        for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
19767            let mut s = three_member_spec();
19768            s.politicas.retries = None;
19769            s.politicas.circuit_breaker = Some(CircuitBreaker {
19770                max_failures: n,
19771                window: Duration::from_secs(60),
19772            });
19773            s.validate()
19774                .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
19775        }
19776    }
19777
19778    #[test]
19779    fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
19780        // The cross-arm ordering pin: `0` is structurally outside
19781        // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
19782        // (cap), but the zero-floor diagnostic is the more
19783        // self-locating one (it directly names the omit-axis
19784        // remediation), so the validate gate must fire on zero
19785        // first. Same shape every other zero-then-shape ordering on
19786        // this surface uses
19787        // ([`AplicacaoError::PolicyRetriesZero`] then
19788        // [`AplicacaoError::PolicyRetriesExceedsCap`];
19789        // [`AplicacaoError::PolicyTimeoutZero`] then
19790        // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
19791        let mut s = three_member_spec();
19792        s.politicas.circuit_breaker = Some(CircuitBreaker {
19793            max_failures: 0,
19794            window: Duration::from_secs(60),
19795        });
19796        assert_eq!(
19797            s.validate().unwrap_err(),
19798            AplicacaoError::PolicyBreakerZeroFailures,
19799            "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
19800        );
19801    }
19802
19803    #[test]
19804    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
19805        // The cross-arm ordering pin between the cap and the
19806        // sibling `:window` gates (zero-window, canonical-window).
19807        // A breaker carrying both an over-cap `max_failures` AND a
19808        // structurally invalid window (zero, sub-ms) must surface
19809        // the cap diagnostic first — the cap arm is wired
19810        // immediately after the zero-failure arm and strictly
19811        // before the window arms, so the offending value the
19812        // diagnostic names matches the order the author would
19813        // discover the gates by reading top-to-bottom through
19814        // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
19815        // future refactor that reorders the arms surfaces here as a
19816        // test failure rather than a silent diagnostic regression.
19817        let mut s = three_member_spec();
19818        s.politicas.circuit_breaker = Some(CircuitBreaker {
19819            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
19820            window: Duration::ZERO,
19821        });
19822        assert_eq!(
19823            s.validate().unwrap_err(),
19824            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
19825                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
19826            },
19827            "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
19828        );
19829    }
19830
19831    #[test]
19832    fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
19833        // The diagnostic-shape pin: the offending `u32` is carried
19834        // verbatim into the
19835        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
19836        // variant so the surfaced error message names the value the
19837        // author wrote (`":politicas :circuit-breaker :max-failures
19838        // (50000) exceeds the mesh-policy ceiling …"`), not just
19839        // the cap. Same self-locating diagnostic shape every other
19840        // typed-cap arm on this surface carries
19841        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
19842        // offending retry count verbatim,
19843        // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
19844        // offending byte count verbatim).
19845        let mut s = three_member_spec();
19846        s.politicas.circuit_breaker = Some(CircuitBreaker {
19847            max_failures: 50_000,
19848            window: Duration::from_secs(60),
19849        });
19850        let err = s.validate().unwrap_err();
19851        assert!(
19852            matches!(
19853                err,
19854                AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
19855                    max_failures: 50_000
19856                }
19857            ),
19858            "got {err:?}"
19859        );
19860        let msg = err.to_string();
19861        assert!(
19862            msg.contains("50000"),
19863            ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
19864        );
19865    }
19866
19867    #[test]
19868    fn policy_breaker_max_failures_cap_pins_canonical_value() {
19869        // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
19870        // value at 1000 — an order of magnitude above every
19871        // documented production-playbook recommendation band
19872        // (Hystrix `requestVolumeThreshold` default 20, Istio
19873        // `outlierDetection.consecutive5xxErrors` default 5, Envoy
19874        // `outlier_detection.consecutive_5xx` default 5, Polly /
19875        // Resilience4j typical 5..=50) and below the
19876        // clearly-pathological "effectively no protection" floor
19877        // (10_000, 100_000, u32::MAX). Pinning the literal value
19878        // here surfaces a future drift (a relaxation to 10_000, a
19879        // tightening to 100) as a deliberate test edit, not a
19880        // silent contract narrowing.
19881        assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
19882    }
19883
19884    #[test]
19885    fn rejects_circuit_breaker_zero_window() {
19886        let mut s = three_member_spec();
19887        s.politicas.circuit_breaker = Some(CircuitBreaker {
19888            max_failures: 5,
19889            window: Duration::ZERO,
19890        });
19891        assert_eq!(
19892            s.validate().unwrap_err(),
19893            AplicacaoError::PolicyBreakerZeroWindow
19894        );
19895    }
19896
19897    #[test]
19898    fn rejects_zero_rate_limit() {
19899        let mut s = three_member_spec();
19900        s.politicas.rate_limit = Some(RateLimit {
19901            rate: 0,
19902            window: Duration::from_secs(1),
19903        });
19904        assert_eq!(
19905            s.validate().unwrap_err(),
19906            AplicacaoError::PolicyRateLimitZero
19907        );
19908    }
19909
19910    #[test]
19911    fn rejects_rate_limit_zero_window() {
19912        // `RateLimit { rate: 100, window: Duration::ZERO }` is
19913        // constructible programmatically (the typed `Duration` field
19914        // imposes no nonzero invariant) but renders through
19915        // `rate_limit_codec::render` as `"100/0s"` — a fragment the
19916        // codec's `parse` rejects as `unknown rate-limit window unit
19917        // "0s"`. Until this validate-time gate landed the typed slot
19918        // accepted the value silently and the round-trip break only
19919        // surfaced at deserialize time (potentially in a downstream
19920        // consumer that never re-validates). Pin the rejection at
19921        // `AplicacaoSpec::validate` so the typed slot's valid set
19922        // matches the codec's round-trippable set structurally.
19923        let mut s = three_member_spec();
19924        s.politicas.rate_limit = Some(RateLimit {
19925            rate: 100,
19926            window: Duration::ZERO,
19927        });
19928        assert_eq!(
19929            s.validate().unwrap_err(),
19930            AplicacaoError::PolicyRateLimitWindowNotCanonical {
19931                window: Duration::ZERO
19932            }
19933        );
19934    }
19935
19936    #[test]
19937    fn rejects_rate_limit_arbitrary_seconds_window() {
19938        // 45 seconds is a valid `Duration` but not one of the three
19939        // canonical rate-limit windows the codec round-trips
19940        // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
19941        // refuses on round-trip — same round-trip-break shape the
19942        // zero-window arm above pins, with a non-zero magnitude to
19943        // guard against a future "reject only zero" half-measure.
19944        let mut s = three_member_spec();
19945        let window = Duration::from_secs(45);
19946        s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
19947        assert_eq!(
19948            s.validate().unwrap_err(),
19949            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
19950        );
19951    }
19952
19953    #[test]
19954    fn rejects_rate_limit_two_minute_window() {
19955        // 120 seconds = 2 minutes is a "looks-canonical" but
19956        // not-canonical window: it's a clean integer multiple of the
19957        // minute unit, but the codec only round-trips the
19958        // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
19959        // A `Duration::from_secs(120)` window renders as `"100/120s"`
19960        // which the parser rejects. Pinning this case rules out a
19961        // future "accept any clean multiple of s/m/h" relaxation
19962        // that would silently break the codec contract.
19963        let mut s = three_member_spec();
19964        let window = Duration::from_secs(120);
19965        s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
19966        assert_eq!(
19967            s.validate().unwrap_err(),
19968            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
19969        );
19970    }
19971
19972    #[test]
19973    fn rejects_rate_limit_subsecond_window() {
19974        // A sub-second window (e.g. 500ms) is a valid `Duration` but
19975        // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
19976        // Pin the rejection so a future relaxation can't silently
19977        // admit fractional-second windows that the codec can't
19978        // round-trip.
19979        let mut s = three_member_spec();
19980        let window = Duration::from_millis(500);
19981        s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
19982        assert_eq!(
19983            s.validate().unwrap_err(),
19984            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
19985        );
19986    }
19987
19988    #[test]
19989    fn rejects_policy_rate_limit_above_cap() {
19990        // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
19991        // is structurally one past the cap and silently passed
19992        // validate on every pre-gate codebase because the typed slot's
19993        // only `rate` check was the zero-floor arm. The no-op-limiter
19994        // shape only surfaced at the runtime substrate (Envoy's
19995        // `local_rate_limit.token_bucket.max_tokens`, the future
19996        // Cilium L7 rate-limit overlay) far from the source caixa.lisp
19997        // with no field naming the offending policy.
19998        let mut s = three_member_spec();
19999        s.politicas.rate_limit = Some(RateLimit {
20000            rate: POLICY_RATE_LIMIT_MAX + 1,
20001            window: Duration::from_secs(1),
20002        });
20003        assert_eq!(
20004            s.validate().unwrap_err(),
20005            AplicacaoError::PolicyRateLimitExceedsCap {
20006                rate: POLICY_RATE_LIMIT_MAX + 1
20007            }
20008        );
20009    }
20010
20011    #[test]
20012    fn rejects_policy_rate_limit_far_above_cap() {
20013        // The `u32::MAX` worst case — the four-billion-token rate-limit
20014        // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
20015        // copy-paste lands in the slot. Pin the cap arm's coverage
20016        // explicitly across the full `u32` overflow so a future
20017        // relaxation that drops the upper bound surfaces here. Peer to
20018        // `rejects_policy_retries_far_above_cap` on the sibling
20019        // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
20020        // on the sibling `:max-failures` axis.
20021        let mut s = three_member_spec();
20022        s.politicas.rate_limit = Some(RateLimit {
20023            rate: u32::MAX,
20024            window: Duration::from_secs(1),
20025        });
20026        assert_eq!(
20027            s.validate().unwrap_err(),
20028            AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
20029        );
20030    }
20031
20032    #[test]
20033    fn accepts_policy_rate_limit_at_cap() {
20034        // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
20035        // must validate. The cap is inclusive on the top edge, matching
20036        // every other typed upper bound in this crate
20037        // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
20038        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
20039        // across all three canonical windows so a future off-by-one
20040        // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
20041        // window-conditional cap surfaces here as a test failure rather
20042        // than a silent contract narrowing.
20043        for secs in [1u64, 60, 3600] {
20044            let mut s = three_member_spec();
20045            s.politicas.rate_limit = Some(RateLimit {
20046                rate: POLICY_RATE_LIMIT_MAX,
20047                window: Duration::from_secs(secs),
20048            });
20049            s.validate().unwrap_or_else(|e| {
20050                panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
20051            });
20052        }
20053    }
20054
20055    #[test]
20056    fn accepts_policy_rate_limit_typical_values() {
20057        // The documented production-playbook recommendation band —
20058        // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
20059        // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
20060        // Enterprise ~1M per-hour. Every value in the validated set
20061        // must pass; pin the band explicitly so a future tightening
20062        // surfaces here.
20063        //
20064        // Clears the fixture's `:retries` (which is `Some(3)`) so this
20065        // per-axis sweep is pure: the sibling cross-axis
20066        // [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] gate
20067        // rejects any `rate <= retries` pair, so the `rate = 1`
20068        // boundary at the head of the sweep would otherwise trip on the
20069        // fixture-inherited retry policy rather than the per-axis
20070        // boundary this test names. Same discipline the sibling per-axis
20071        // `accepts_circuit_breaker_max_failures_typical_values` sweep
20072        // takes against the fixture's `:retries` for the peer cross-axis
20073        // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
20074        // arm.
20075        for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
20076            for secs in [1u64, 60, 3600] {
20077                let mut s = three_member_spec();
20078                s.politicas.retries = None;
20079                s.politicas.rate_limit = Some(RateLimit {
20080                    rate,
20081                    window: Duration::from_secs(secs),
20082                });
20083                s.validate().unwrap_or_else(|e| {
20084                    panic!("rate={rate} window={secs}s must validate; got {e:?}")
20085                });
20086            }
20087        }
20088    }
20089
20090    #[test]
20091    fn policy_rate_limit_zero_takes_precedence_over_cap() {
20092        // The cross-arm ordering pin: `rate == 0` is structurally
20093        // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
20094        // (cap), but the zero-floor diagnostic is the more
20095        // self-locating one (it directly names the omit-axis
20096        // remediation). Pin the order so a future refactor that
20097        // reorders the arms surfaces here as a test failure rather
20098        // than a silent diagnostic regression. Same shape every other
20099        // zero-then-cap ordering on this surface uses
20100        // ([`AplicacaoError::PolicyRetriesZero`] then
20101        // [`AplicacaoError::PolicyRetriesExceedsCap`];
20102        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
20103        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
20104        let mut s = three_member_spec();
20105        s.politicas.rate_limit = Some(RateLimit {
20106            rate: 0,
20107            window: Duration::from_secs(1),
20108        });
20109        assert_eq!(
20110            s.validate().unwrap_err(),
20111            AplicacaoError::PolicyRateLimitZero,
20112            "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
20113        );
20114    }
20115
20116    #[test]
20117    fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
20118        // Two-axis-bad pin: rate above cap *and* window non-canonical.
20119        // The validate gate must fire on the rate cap first — the
20120        // amplification-shape (no-op limiter) diagnostic is the more
20121        // fundamental one; the window-canonical diagnostic is the
20122        // narrower codec-round-trip shape. Pin the ordering so a future
20123        // refactor that reorders the rate-then-window check arms
20124        // surfaces here as a test failure rather than a silent
20125        // diagnostic regression.
20126        let mut s = three_member_spec();
20127        s.politicas.rate_limit = Some(RateLimit {
20128            rate: POLICY_RATE_LIMIT_MAX + 1,
20129            window: Duration::from_secs(45),
20130        });
20131        assert_eq!(
20132            s.validate().unwrap_err(),
20133            AplicacaoError::PolicyRateLimitExceedsCap {
20134                rate: POLICY_RATE_LIMIT_MAX + 1
20135            },
20136            "above-cap rate must surface the cap diagnostic, not the window diagnostic"
20137        );
20138    }
20139
20140    #[test]
20141    fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
20142        // The diagnostic-shape pin: the offending `u32` is carried
20143        // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
20144        // variant so the surfaced error message names the value the
20145        // author wrote (`":politicas :rate-limit rate (5000000) exceeds
20146        // the mesh-policy ceiling …"`), not just the cap. Same
20147        // self-locating diagnostic shape every other typed-cap arm on
20148        // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
20149        // carries the offending retries count verbatim,
20150        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
20151        // the offending failure count verbatim).
20152        let mut s = three_member_spec();
20153        s.politicas.rate_limit = Some(RateLimit {
20154            rate: 5_000_000,
20155            window: Duration::from_secs(1),
20156        });
20157        let err = s.validate().unwrap_err();
20158        assert!(
20159            matches!(
20160                err,
20161                AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
20162            ),
20163            "got {err:?}"
20164        );
20165        let msg = err.to_string();
20166        assert!(
20167            msg.contains("5000000"),
20168            ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
20169        );
20170    }
20171
20172    #[test]
20173    fn policy_rate_limit_cap_pins_canonical_value() {
20174        // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
20175        // 1_000_000 — two-to-three orders of magnitude above every
20176        // documented production-playbook recommendation band (Envoy /
20177        // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
20178        // Gateway 10_000..=100_000 per-minute) and below the
20179        // clearly-pathological "paste-from-binary blob" floor
20180        // (100_000_000, u32::MAX). Pinning the literal value here
20181        // surfaces a future drift (a relaxation to 10_000_000, a
20182        // tightening to 100_000) as a deliberate test edit, not a
20183        // silent contract narrowing.
20184        assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
20185    }
20186
20187    #[test]
20188    fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
20189        // Both axes are invalid here: rate == 0 *and* window is
20190        // non-canonical. The validate gate must fire on rate first
20191        // (matching the existing `rejects_zero_rate_limit` ordering),
20192        // so the existing diagnostic continues to lead with the
20193        // simpler "zero rate" framing. Pinning the order of checks
20194        // so a future refactor that reorders the arms surfaces here
20195        // as a test failure rather than a silent diagnostic
20196        // regression.
20197        let mut s = three_member_spec();
20198        s.politicas.rate_limit = Some(RateLimit {
20199            rate: 0,
20200            window: Duration::from_secs(45),
20201        });
20202        assert_eq!(
20203            s.validate().unwrap_err(),
20204            AplicacaoError::PolicyRateLimitZero
20205        );
20206    }
20207
20208    #[test]
20209    fn rate_limit_canonical_windows_validate() {
20210        // The three canonical windows the codec round-trips
20211        // losslessly — 1s / 60s / 3600s — must all pass `validate()`
20212        // unchanged. Pin the full canonical set as a positive case
20213        // (the existing `rate_limit_round_trip_seconds` /
20214        // `rate_limit_round_trip_minutes` tests pin the
20215        // serialize-then-deserialize property at the codec layer; this
20216        // test pins the validate-side complement so a future tightening
20217        // of the canonical set — e.g. dropping `:hour` — surfaces here
20218        // as a test failure rather than a silent contract narrowing).
20219        for secs in [1u64, 60, 3600] {
20220            let mut s = three_member_spec();
20221            s.politicas.rate_limit = Some(RateLimit {
20222                rate: 100,
20223                window: Duration::from_secs(secs),
20224            });
20225            s.validate().expect("canonical window must validate");
20226        }
20227    }
20228
20229    #[test]
20230    fn rate_limit_validated_value_round_trips_through_codec() {
20231        // The structural property the validate gate enforces:
20232        // every `RateLimit` past `AplicacaoSpec::validate` round-trips
20233        // losslessly through the `rate_limit_codec` (serialize → string
20234        // → deserialize → equal value). Pin this end-to-end so a future
20235        // change to either side (the validate gate's accepted window
20236        // set, the codec's parse/render unit set) that breaks the
20237        // alignment surfaces here. The previous-state shape (typed
20238        // slot accepts arbitrary `Duration`, codec only round-trips
20239        // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
20240        // window — the validate gate now forecloses that.
20241        for secs in [1u64, 60, 3600] {
20242            let mut s = three_member_spec();
20243            s.politicas.rate_limit = Some(RateLimit {
20244                rate: 250,
20245                window: Duration::from_secs(secs),
20246            });
20247            s.validate().unwrap();
20248            let json = serde_json::to_string(&s.politicas).unwrap();
20249            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
20250            assert_eq!(
20251                back.rate_limit, s.politicas.rate_limit,
20252                "every validated :rate-limit must round-trip losslessly through the codec"
20253            );
20254        }
20255    }
20256
20257    #[test]
20258    fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
20259        // The hour-window canonical form (`"<n>/h"`) was missing from
20260        // the prior `rate_limit_round_trip_seconds` / `_minutes` test
20261        // pair. Now that the validate gate pins 3600s as part of the
20262        // canonical set, pin its serialize-side render shape too so
20263        // the third leg of the s/m/h tripod is explicitly tested.
20264        let policy = MeshPolicy {
20265            rate_limit: Some(RateLimit {
20266                rate: 10000,
20267                window: Duration::from_secs(3600),
20268            }),
20269            ..Default::default()
20270        };
20271        let json = serde_json::to_string(&policy).unwrap();
20272        assert!(
20273            json.contains("\"10000/h\""),
20274            "hour-window canonical form must render with `h` suffix (got: {json})"
20275        );
20276        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
20277        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
20278    }
20279
20280    #[test]
20281    fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
20282        // Pin the substrate-primitive [`RateLimit::canonical_unit`]
20283        // typed accessor's accepted-window set against the codec's
20284        // accepted set explicitly. A future addition to the codec
20285        // (e.g. accepting `:day`/`:week` as authoring units) must be
20286        // accompanied by a parallel addition here, and a regression
20287        // that drops one of the three canonical units from either
20288        // side surfaces as a test failure. The accessor is the
20289        // single source of truth for the canonical-window set —
20290        // [`AplicacaoSpec::validate_politicas`]'s canonical-window
20291        // gate and [`rate_limit_codec::render`]'s canonical arm both
20292        // read through it — this test enshrines that its
20293        // `Duration → Option<RateLimitUnit>` projection matches the
20294        // codec's parse / render arms' accepted-window set exactly.
20295        //
20296        // Predecessor: this pin previously read the module-private
20297        // free helper `is_canonical_rate_limit_window` — a delegate
20298        // that composed [`RateLimitUnit::from_window`] with `.is_some()`
20299        // — but the helper had no production consumers left after the
20300        // validate-gate migration onto [`RateLimit::canonical_unit`]
20301        // and was deleted; the closed-set arm-window bijection now
20302        // lives on exactly one typed dispatch on the substrate
20303        // primitive.
20304        let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
20305            RateLimit { rate: 1, window }.canonical_unit()
20306        };
20307        assert!(canonical_unit(Duration::from_secs(1)).is_some());
20308        assert!(canonical_unit(Duration::from_secs(60)).is_some());
20309        assert!(canonical_unit(Duration::from_secs(3600)).is_some());
20310        // Non-canonical windows the accessor rejects.
20311        assert!(canonical_unit(Duration::ZERO).is_none());
20312        assert!(canonical_unit(Duration::from_secs(2)).is_none());
20313        assert!(canonical_unit(Duration::from_secs(30)).is_none());
20314        assert!(canonical_unit(Duration::from_secs(120)).is_none());
20315        assert!(canonical_unit(Duration::from_secs(86400)).is_none());
20316        // Sub-second windows: even `Duration::from_millis(1000)` is
20317        // exactly 1s and accepted; `Duration::from_millis(500)` is
20318        // sub-second and rejected.
20319        assert!(canonical_unit(Duration::from_millis(1000)).is_some());
20320        assert!(canonical_unit(Duration::from_millis(500)).is_none());
20321        assert!(canonical_unit(Duration::from_millis(1500)).is_none());
20322    }
20323
20324    #[test]
20325    fn rate_limit_unit_table_projections_are_mutual_inverses() {
20326        // Bidirection pin against the closed-set typed enum
20327        // [`RateLimitUnit`] arm-table (the canonical
20328        // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
20329        // of the rate-limit unit surface reads from). The two
20330        // projection directions [`RateLimitUnit::from_suffix`] /
20331        // [`RateLimitUnit::window`] (str → Duration, exposed as one
20332        // typed dispatch through [`RateLimitUnit::window_from_suffix`])
20333        // and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
20334        // (Duration → str, exposed as one typed dispatch through
20335        // [`RateLimit::canonical_unit`] composed with
20336        // [`RateLimitUnit::as_suffix`]) are the substrate primitives the
20337        // codec's parse arm ([`rate_limit_codec::parse`] via
20338        // [`RateLimitUnit::window_from_suffix`]), the codec's render arm
20339        // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
20340        // and the validate gate ([`AplicacaoSpec::validate_politicas`]
20341        // via [`RateLimit::canonical_unit`]) all key off. A future
20342        // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
20343        // sub-second window) is one variant + one arm per method on the
20344        // closed-set enum; the compiler-enforced exhaustiveness on
20345        // every consumer's `match self` arms picks it up by
20346        // construction. This pin enshrines that both projection
20347        // directions agree on every canonical arm row and neither
20348        // leaks a spurious entry the other doesn't recognize.
20349        //
20350        // Predecessor: this test previously read the two vestigial
20351        // module-private free helpers `rate_limit_window_unit` and
20352        // `rate_limit_window_from_unit` on the `Duration → &str` and
20353        // `&str → Duration` axes; the former was deleted after its
20354        // sole production consumer ([`rate_limit_codec::render`])
20355        // migrated onto [`RateLimit::canonical_unit`] (61421a6), and
20356        // the latter is folded here into the substrate primitive
20357        // [`RateLimitUnit::window_from_suffix`] so both projection
20358        // directions live on the closed-set enum's arm-table.
20359        for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
20360            let window = super::RateLimitUnit::window_from_suffix(unit)
20361                .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
20362            assert_eq!(
20363                window,
20364                Duration::from_secs(secs),
20365                "unit {unit:?} must resolve to {secs}s"
20366            );
20367            let projected_suffix = RateLimit { rate: 1, window }
20368                .canonical_unit()
20369                .map(super::RateLimitUnit::as_suffix);
20370            assert_eq!(
20371                projected_suffix,
20372                Some(unit),
20373                "Duration({secs}s) must render as {unit:?} \
20374                 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
20375            );
20376        }
20377        // Non-table units yield None on the `unit → Duration`
20378        // projection — a future `"d"` addition to the table would
20379        // flip this arm; today it pins the current three-row table's
20380        // rejection semantics.
20381        assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
20382        assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
20383        assert!(super::RateLimitUnit::window_from_suffix("").is_none());
20384        // Non-table Durations yield None on the `Duration → unit`
20385        // projection — pins that the two projections agree on the
20386        // "not in the table" semantic too, so a drift where the
20387        // parse-side accepts a value the render-side can't emit is
20388        // a build error at the two-arm pair, not a silent codec
20389        // round-trip break.
20390        let projected_suffix = |window: Duration| -> Option<&'static str> {
20391            RateLimit { rate: 1, window }
20392                .canonical_unit()
20393                .map(super::RateLimitUnit::as_suffix)
20394        };
20395        assert!(projected_suffix(Duration::from_secs(2)).is_none());
20396        assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
20397        assert!(projected_suffix(Duration::from_millis(1500)).is_none());
20398    }
20399
20400    #[test]
20401    fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
20402        // Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
20403        // substrate-primitive `&str → Duration` associated method the
20404        // codec's parse arm ([`rate_limit_codec::parse`]) now routes
20405        // through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
20406        // to the same [`Duration`] the two-step composition
20407        // [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
20408        // returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
20409        // `"MIN"`) must project to [`None`] on both paths. A future
20410        // implementation of `window_from_suffix` that took a shortcut
20411        // through a per-suffix `match` table (bypassing the arm-table's
20412        // `Self::from_suffix` scan and the arm-table's `Self::window`
20413        // dispatch) would silently split the accept-set — the parse
20414        // arm would accept a suffix the enum's arm-table doesn't know,
20415        // or reject a suffix the enum's arm-table does; this pin
20416        // surfaces that drift at caixa-core build time rather than at a
20417        // downstream serde round-trip audit on a live `MeshPolicy`.
20418        //
20419        // Same byte-parity discipline the sibling
20420        // [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
20421        // pin carries on the peer `Duration → RateLimitUnit` axis via
20422        // [`RateLimit::canonical_unit`], and the peer
20423        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
20424        // carries on the bidirectional arm-table axis — extended here
20425        // onto the fifth (and last unlifted) projection axis on the
20426        // closed-set enum's arm-table.
20427        let composition = |suffix: &str| -> Option<Duration> {
20428            super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
20429        };
20430        for suffix in ["s", "m", "h"] {
20431            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
20432            let via_composition = composition(suffix);
20433            assert_eq!(
20434                via_method, via_composition,
20435                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
20436                 from_suffix({suffix:?}).map(window) — the substrate-primitive \
20437                 method must delegate to the arm-table's two typed dispatches, \
20438                 not shortcut through a per-suffix match table"
20439            );
20440            assert!(
20441                via_method.is_some(),
20442                "canonical suffix {suffix:?} must resolve to Some(Duration) via \
20443                 RateLimitUnit::window_from_suffix"
20444            );
20445        }
20446        for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
20447            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
20448            let via_composition = composition(suffix);
20449            assert_eq!(
20450                via_method, via_composition,
20451                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
20452                 from_suffix({suffix:?}).map(window) on the non-arm rejection \
20453                 axis too"
20454            );
20455            assert!(
20456                via_method.is_none(),
20457                "non-arm suffix {suffix:?} must project to None via \
20458                 RateLimitUnit::window_from_suffix — a future extension that \
20459                 accepted this suffix without a corresponding arm on the enum \
20460                 would split the codec's parse-accepted set from the enum's \
20461                 arm-table"
20462            );
20463        }
20464        // And the codec's parse arm now reads through this method: a
20465        // canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
20466        // the same `Duration` the method returns for its unit, closing
20467        // the two-consumer drift surface (the codec's parse arm and the
20468        // enum's arm-table) with one typed dispatch on the substrate
20469        // primitive.
20470        for suffix in ["s", "m", "h"] {
20471            let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
20472            let mp: MeshPolicy = serde_json::from_str(&wire)
20473                .unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
20474            let parsed = mp.rate_limit().expect("rate_limit payload present");
20475            let via_method = super::RateLimitUnit::window_from_suffix(suffix)
20476                .unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
20477            assert_eq!(
20478                parsed.window(),
20479                via_method,
20480                "codec parse arm on {wire:?} must resolve the window through \
20481                 RateLimitUnit::window_from_suffix, not a divergent path"
20482            );
20483        }
20484    }
20485
20486    #[test]
20487    fn rate_limit_unit_all_enumerates_every_arm_once() {
20488        // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
20489        // enumerate every arm of the closed-set enum exactly once, in
20490        // the canonical shortest-to-longest window order (Second before
20491        // Minute before Hour) — the same order the sibling
20492        // [`crate::supervisor::RestartStrategy`] /
20493        // [`crate::supervisor::RestartPolicy`] /
20494        // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
20495        // typed enums carry (the arm declared first is the arm listed
20496        // first). A future variant addition that extends the enum
20497        // without appending to [`RateLimitUnit::ALL`] leaves the
20498        // exhaustive iteration surface silently short one arm — the
20499        // codec's parse arm would then reject the new suffix even
20500        // though the enum knows it. This pin closes the drift.
20501        assert_eq!(
20502            super::RateLimitUnit::ALL,
20503            &[
20504                super::RateLimitUnit::Second,
20505                super::RateLimitUnit::Minute,
20506                super::RateLimitUnit::Hour,
20507            ],
20508            "RateLimitUnit::ALL must enumerate every arm exactly once, \
20509             in canonical shortest-to-longest window order"
20510        );
20511    }
20512
20513    #[test]
20514    fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
20515        // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
20516        // every arm's [`RateLimitUnit::as_suffix`] output must parse
20517        // back through [`RateLimitUnit::from_suffix`] to the same
20518        // variant. A future arm addition that lands `as_suffix` but
20519        // forgets `from_suffix` (`from_suffix` iterates
20520        // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
20521        // is the load-bearing carrier of the round-trip; the sibling
20522        // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
20523        // the `ALL` half) trips here at caixa-core build time rather
20524        // than surfacing as a codec round-trip miss (a `render` emit
20525        // that lands a suffix the paired `parse` cannot decode).
20526        for unit in super::RateLimitUnit::ALL {
20527            let suffix = unit.as_suffix();
20528            let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
20529                panic!(
20530                    "RateLimitUnit::from_suffix({suffix:?}) must accept every \
20531                     RateLimitUnit::as_suffix output — got None for {unit:?}"
20532                )
20533            });
20534            assert_eq!(
20535                parsed, *unit,
20536                "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
20537                 must return RateLimitUnit::{unit:?}"
20538            );
20539        }
20540    }
20541
20542    #[test]
20543    fn rate_limit_unit_from_window_and_window_round_trip() {
20544        // Total round-trip pin on the `(from_window, window)` pair:
20545        // every arm's [`RateLimitUnit::window`] output must parse back
20546        // through [`RateLimitUnit::from_window`] to the same variant.
20547        // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
20548        // on the peer `Duration` axis — the two round-trip pins
20549        // together enshrine that both projections of the typed
20550        // canonical-unit bijection are total on the arm-set.
20551        for unit in super::RateLimitUnit::ALL {
20552            let window = unit.window();
20553            let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
20554                panic!(
20555                    "RateLimitUnit::from_window({window:?}) must accept every \
20556                     RateLimitUnit::window output — got None for {unit:?}"
20557                )
20558            });
20559            assert_eq!(
20560                parsed, *unit,
20561                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
20562                 must return RateLimitUnit::{unit:?}"
20563            );
20564        }
20565    }
20566
20567    #[test]
20568    fn rate_limit_unit_from_window_accessor_is_const_fn() {
20569        // Fail-before-pass-after pin: witnesses the
20570        // [`RateLimitUnit::from_window`] `const`-eval posture via a
20571        // `const fn` wrapper `from_window_via_const_fn(window: Duration)
20572        // -> Option<RateLimitUnit>` whose body calls
20573        // `RateLimitUnit::from_window(window)`, well-formed only when
20574        // the callee is itself `const fn` (any future downgrade to
20575        // non-`const` fails at caixa-core build time with E0015 `cannot
20576        // call non-const function`, strictly stronger than a runtime
20577        // `assert!`, side-stepping the destructor-in-const restriction
20578        // that blocks direct `const _: Option<RateLimitUnit> =
20579        // RateLimitUnit::from_window(...)` items on `Duration`'s
20580        // carrier). The runtime body sweeps every closed-set
20581        // [`RateLimitUnit::ALL`] arm plus a representative non-canonical
20582        // rejection sample (`Duration::from_millis(500)` sub-second
20583        // residue) and asserts the wrapped and direct dispatches agree
20584        // — a violation means the wrapper stopped compiling under a
20585        // future `const`-posture downgrade, or the reverse resolver's
20586        // arm-set silently split from the peer `Self::window` emitter's
20587        // arm-set. Peer of the sibling
20588        // [`crate::supervisor::tests::child_spec_restart_accessor_is_const_fn`]
20589        // (152c868) /
20590        // [`crate::supervisor::tests::supervisor_spec_estrategia_accessor_is_const_fn`]
20591        // (152c868) /
20592        // [`entrada_port_accessor_is_const_fn`] (bafa004) /
20593        // [`placement_estrategia_accessor_is_const_fn`] (bafa004)
20594        // `const`-eval-surface pins on the peer M2 / M3 substrate-
20595        // primitive `Copy`-return accessor axes, extended onto the
20596        // reverse `Duration → RateLimitUnit` projection axis on the
20597        // M3 mesh-slot rate-limit closed-set typed enum.
20598        const fn from_window_via_const_fn(window: Duration) -> Option<super::RateLimitUnit> {
20599            super::RateLimitUnit::from_window(window)
20600        }
20601        for unit in super::RateLimitUnit::ALL {
20602            let window = unit.window();
20603            let via_wrapper = from_window_via_const_fn(window);
20604            let direct = super::RateLimitUnit::from_window(window);
20605            assert_eq!(
20606                via_wrapper, direct,
20607                "RateLimitUnit::from_window({window:?}) via const fn \
20608                 wrapper must agree with direct dispatch for {unit:?}"
20609            );
20610            assert_eq!(
20611                via_wrapper,
20612                Some(*unit),
20613                "RateLimitUnit::from_window({window:?}) via const fn \
20614                 wrapper must return Some({unit:?}) for the peer \
20615                 window() output"
20616            );
20617        }
20618        assert!(from_window_via_const_fn(Duration::from_millis(500)).is_none());
20619        assert!(from_window_via_const_fn(Duration::from_secs(30)).is_none());
20620    }
20621
20622    #[test]
20623    fn rate_limit_unit_from_window_composes_through_window_accessor() {
20624        // Composition-witness pin on the routing-through-peer discipline:
20625        // [`RateLimitUnit::from_window`]'s per-arm probes each dispatch
20626        // through the peer `pub const fn` [`RateLimitUnit::window`]
20627        // canonical-`Duration` projection rather than a hand-authored
20628        // per-arm second-magnitude literal — a future arm-magnitude edit
20629        // on the sibling `window()` accessor (a `Second → 2s` typo, a
20630        // `Hour → 3599s` off-by-one) must therefore reach this reverse
20631        // resolver by construction. A pin that hard-coded the three
20632        // second-magnitudes here would silently split from the peer
20633        // emitter on any such edit; instead, this pin asserts the
20634        // composition invariant `from_window(u.window()) == Some(u)`
20635        // holds byte-for-byte on every closed-set [`RateLimitUnit::ALL`]
20636        // arm — a violation means either the peer `Self::window`
20637        // accessor drifted (breaking every downstream consumer that
20638        // reads through it), or the reverse resolver stopped routing
20639        // through the peer (introducing a hand-authored literal that
20640        // silently disagrees with the emitter). Either failure is a
20641        // caixa-core-build-time surface, not a downstream renderer
20642        // round-trip regression.
20643        //
20644        // Peer of the sibling
20645        // [`crate::render::assert_str_reexport_identity`] discipline on
20646        // the substrate-primitive `&'static str` re-export axis and the
20647        // [`rate_limit_unit_from_window_and_window_round_trip`]
20648        // round-trip pin on the peer projection direction; extends the
20649        // one-canonical-dispatch-per-projection discipline onto the
20650        // reverse-resolver's per-arm probe axis.
20651        for unit in super::RateLimitUnit::ALL {
20652            let window_via_peer = unit.window();
20653            let resolved = super::RateLimitUnit::from_window(window_via_peer);
20654            assert_eq!(
20655                resolved,
20656                Some(*unit),
20657                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
20658                 must return Some({unit:?}) — the reverse resolver's per-arm \
20659                 probes must route through the peer `Self::window` accessor \
20660                 so any future arm-magnitude edit reaches both projection \
20661                 directions by construction"
20662            );
20663        }
20664    }
20665
20666    #[test]
20667    fn rate_limit_canonical_unit_accessor_is_const_fn() {
20668        // Fail-before-pass-after pin: witnesses the
20669        // [`RateLimit::canonical_unit`] `const`-eval posture via a
20670        // `const fn` wrapper
20671        // `canonical_unit_via_const_fn(rl: &RateLimit) -> Option<RateLimitUnit>`
20672        // whose body calls `rl.canonical_unit()`, well-formed only when
20673        // the callee is itself `const fn` (any future downgrade to
20674        // non-`const` fails at caixa-core build time with E0015 `cannot
20675        // call non-const method`). The runtime body sweeps every
20676        // closed-set [`RateLimitUnit::ALL`] arm — for each arm,
20677        // constructs a typed [`RateLimit`] with the peer `Self::window`
20678        // canonical `Duration`, then asserts both the wrapper and the
20679        // direct dispatch agree and both return `Some(unit)`. Composes
20680        // with the sibling
20681        // [`rate_limit_unit_from_window_accessor_is_const_fn`] pin: the
20682        // typed [`RateLimit`] projection layer's `const`-posture is
20683        // load-bearing on the reverse resolver's `const`-posture, and
20684        // both must migrate together (a downgrade of either surface
20685        // splits the paired `const`-eval-surface pass on the M3
20686        // mesh-slot rate-limit `Duration ↔ Self` bijection).
20687        const fn canonical_unit_via_const_fn(
20688            rl: &super::RateLimit,
20689        ) -> Option<super::RateLimitUnit> {
20690            rl.canonical_unit()
20691        }
20692        for unit in super::RateLimitUnit::ALL {
20693            let rl = super::RateLimit {
20694                rate: 1,
20695                window: unit.window(),
20696            };
20697            let via_wrapper = canonical_unit_via_const_fn(&rl);
20698            let direct = rl.canonical_unit();
20699            assert_eq!(
20700                via_wrapper, direct,
20701                "RateLimit::canonical_unit() via const fn wrapper must \
20702                 agree with direct dispatch for {unit:?}"
20703            );
20704            assert_eq!(
20705                via_wrapper,
20706                Some(*unit),
20707                "RateLimit::canonical_unit() via const fn wrapper must \
20708                 return Some({unit:?}) for a RateLimit whose window is \
20709                 the peer RateLimitUnit::{unit:?}.window() output"
20710            );
20711        }
20712    }
20713
20714    #[test]
20715    fn rate_limit_unit_projections_are_pairwise_distinct() {
20716        // Distinctness pin: [`RateLimitUnit::as_suffix`] and
20717        // [`RateLimitUnit::window`] outputs must be pairwise distinct
20718        // across every arm — an accidental copy-paste flip that
20719        // reroutes one arm's suffix or window to also match another
20720        // silently collapses two arms onto one, so
20721        // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
20722        // (both using `find` on `Self::ALL`) would return whichever
20723        // arm the linear scan lands on first — a match-arm-ordering-
20724        // dependent outcome the closed-set typed-enum shape is meant
20725        // to rule out structurally. Peer of the sibling
20726        // `caixa_kind_wire_consts_are_pairwise_distinct` /
20727        // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
20728        // other closed-set typed-enum discriminator axes.
20729        let all = super::RateLimitUnit::ALL;
20730        for (i, a) in all.iter().enumerate() {
20731            for (j, b) in all.iter().enumerate() {
20732                if i != j {
20733                    assert_ne!(
20734                        a.as_suffix(),
20735                        b.as_suffix(),
20736                        "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
20737                         must be distinct — a collision silently collapses two \
20738                         arms onto one under from_suffix's linear scan"
20739                    );
20740                    assert_ne!(
20741                        a.window(),
20742                        b.window(),
20743                        "RateLimitUnit::{a:?}.window() and {b:?}.window() \
20744                         must be distinct — a collision silently collapses two \
20745                         arms onto one under from_window's linear scan"
20746                    );
20747                }
20748            }
20749        }
20750    }
20751
20752    #[test]
20753    fn rate_limit_unit_display_routes_through_as_suffix() {
20754        // Route pin: [`std::fmt::Display`] must byte-equal
20755        // [`RateLimitUnit::as_suffix`] on every arm — the single
20756        // source of truth for the canonical suffix. A future
20757        // reimplementation that hand-rolls the arms instead of
20758        // delegating to [`RateLimitUnit::as_suffix`] would silently
20759        // desynchronize `format!("{u}")` from the codec's parse arm
20760        // (which uses `as_suffix` to compare suffixes). Peer of the
20761        // sibling `caixa_kind_display_routes_through_as_str_helper` /
20762        // `placement_strategy_display_routes_through_as_str_helper`
20763        // pins on the peer closed-set typed-enum Display axes.
20764        for unit in super::RateLimitUnit::ALL {
20765            assert_eq!(
20766                unit.to_string(),
20767                unit.as_suffix(),
20768                "RateLimitUnit::{unit:?} Display must route through \
20769                 as_suffix (single source of truth: the canonical suffix \
20770                 the codec parses and renders)"
20771            );
20772        }
20773    }
20774
20775    #[test]
20776    fn rate_limit_unit_from_window_rejects_non_canonical() {
20777        // Rejection pin on the parser's accept-set: any Duration
20778        // outside the three-arm [`RateLimitUnit::window`] output set
20779        // (sub-second residue, or a second-magnitude outside `{1, 60,
20780        // 3600}`) must return `None`. A future accidental widening of
20781        // the accept-set (rounding down sub-second residue to the
20782        // nearest arm, admitting `Duration::from_secs(30)` as a
20783        // half-minute unit) would silently drift the parser's accept-
20784        // set from the emitter's — a validated slot with a
20785        // non-canonical window would then round-trip through the
20786        // codec to a canonical form the author never wrote.
20787        assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
20788        assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
20789        assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
20790        assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
20791        assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
20792        assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
20793        assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
20794    }
20795
20796    #[test]
20797    fn rate_limit_unit_from_suffix_rejects_unknown() {
20798        // Rejection pin on the suffix parser's accept-set: any string
20799        // outside the three-arm [`RateLimitUnit::as_suffix`] output
20800        // set must return `None`. Peer of the sibling
20801        // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
20802        // the [`crate::CaixaKind`] `from_wire` accept-set.
20803        for bad in [
20804            "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
20805            " s",
20806        ] {
20807            assert!(
20808                super::RateLimitUnit::from_suffix(bad).is_none(),
20809                "RateLimitUnit::from_suffix({bad:?}) must return None — the \
20810                 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
20811                 outputs"
20812            );
20813        }
20814    }
20815
20816    #[test]
20817    fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
20818        // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
20819        // every canonical `:window` magnitude the validate gate
20820        // accepts must map to the paired [`RateLimitUnit`] arm through
20821        // this accessor. A future validate-gate rebrand that widened
20822        // the accepted-window set without extending [`RateLimitUnit`]
20823        // would silently split the accessor's `Some`-return set from
20824        // the validate gate's accept-set — a slot that satisfies
20825        // validate would land at the accessor with `None`, so a
20826        // consumer past validate that pattern-matches on the returned
20827        // `Some` would silently miss the newly-accepted magnitude.
20828        for (window_secs, expected) in [
20829            (1u64, super::RateLimitUnit::Second),
20830            (60, super::RateLimitUnit::Minute),
20831            (3600, super::RateLimitUnit::Hour),
20832        ] {
20833            let rl = RateLimit {
20834                rate: 100,
20835                window: Duration::from_secs(window_secs),
20836            };
20837            assert_eq!(
20838                rl.canonical_unit(),
20839                Some(expected),
20840                "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
20841                 must return Some({expected:?})"
20842            );
20843        }
20844        // Non-canonical windows the validate gate rejects also return
20845        // None here — the accessor is the typed-enum projection of
20846        // the sibling `is_canonical_rate_limit_window` predicate.
20847        let bad = RateLimit {
20848            rate: 100,
20849            window: Duration::from_secs(30),
20850        };
20851        assert!(
20852            bad.canonical_unit().is_none(),
20853            "RateLimit with a non-canonical window must return None from \
20854             canonical_unit — the validate gate rejects the same set"
20855        );
20856    }
20857
20858    #[test]
20859    fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
20860        // Fail-before-pass-after byte-parity pin: for every canonical
20861        // window the [`rate_limit_codec::render`] arm's emitted string
20862        // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
20863        // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
20864        // the vestigial free helper [`rate_limit_window_unit`] (a
20865        // `find_map`-walked `Duration → &'static str` delegate) onto the
20866        // substrate primitive [`RateLimit::canonical_unit`] typed method
20867        // (a closed-set `match self.window` arm on
20868        // [`RateLimitUnit::from_window`], projected through
20869        // [`RateLimitUnit::as_suffix`] via the enum's
20870        // [`std::fmt::Display`] impl). A future re-routing of the render
20871        // arm through a differently-computed unit projection would break
20872        // this pin at build time rather than as a silent per-consumer
20873        // codec round-trip drift far from the substrate primitive edit.
20874        //
20875        // Sibling to the peer
20876        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
20877        // on the free-helper axis: that pin locks the two projections
20878        // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
20879        // on the closed-set arm table; this pin locks the codec's render
20880        // arm reads through the typed accessor rather than the free
20881        // helper. Two production consumers of the canonical-unit axis
20882        // now key off one typed dispatch on the substrate primitive.
20883        for (window_secs, unit) in [
20884            (1u64, super::RateLimitUnit::Second),
20885            (60, super::RateLimitUnit::Minute),
20886            (3600, super::RateLimitUnit::Hour),
20887        ] {
20888            let rl = RateLimit {
20889                rate: 42,
20890                window: Duration::from_secs(window_secs),
20891            };
20892            let policy = MeshPolicy {
20893                rate_limit: Some(rl),
20894                ..Default::default()
20895            };
20896            let json = serde_json::to_string(&policy).unwrap();
20897            let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
20898            assert!(
20899                json.contains(&expected),
20900                "rate_limit_codec::render must emit {expected} (via \
20901                 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
20902                 for a {window_secs}s window; serialized MeshPolicy was: {json}"
20903            );
20904            // And the accessor route resolves to the same typed unit
20905            // the render arm's Display formatting is asked to produce —
20906            // so a future edit that split the two paths (one through
20907            // the accessor, one through a re-introduced free helper)
20908            // trips this pin.
20909            assert_eq!(
20910                rl.canonical_unit(),
20911                Some(unit),
20912                "RateLimit::canonical_unit must return Some({unit:?}) for a \
20913                 {window_secs}s window; the codec render arm reads the same \
20914                 typed unit through this accessor"
20915            );
20916        }
20917    }
20918
20919    #[test]
20920    fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
20921        // Fail-before-pass-after byte-parity pin on the validate gate's
20922        // canonical-window shape probe: every non-canonical `:window`
20923        // the free-helper predicate [`is_canonical_rate_limit_window`]
20924        // rejects is also rejected by the substrate primitive
20925        // [`RateLimit::canonical_unit`] `.is_none()` route the validate
20926        // gate now reads through, and vice versa on the accepted set
20927        // (the three canonical windows). Locks the migration from the
20928        // free helper onto the substrate primitive: a future re-routing
20929        // of one of the two paths through a differently-computed unit
20930        // projection would silently split the codec's accepted set from
20931        // the validate gate's accepted set — a two-consumer drift the
20932        // codec-round-trip pin
20933        // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
20934        // above closes on the render arm and this pin closes on the
20935        // validate arm.
20936        for canonical_window_secs in [1u64, 60, 3600] {
20937            let mut s = three_member_spec();
20938            let rl = RateLimit {
20939                rate: 100,
20940                window: Duration::from_secs(canonical_window_secs),
20941            };
20942            s.politicas.rate_limit = Some(rl);
20943            assert!(
20944                s.validate().is_ok(),
20945                "canonical {canonical_window_secs}s window must pass \
20946                 validate_politicas — the validate gate now reads \
20947                 RateLimit::canonical_unit().is_none() and the accessor \
20948                 returns Some on every canonical arm"
20949            );
20950            assert!(
20951                rl.canonical_unit().is_some(),
20952                "canonical {canonical_window_secs}s window must resolve to \
20953                 Some on RateLimit::canonical_unit — the validate gate reads \
20954                 this accessor directly"
20955            );
20956        }
20957        for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
20958            let mut s = three_member_spec();
20959            let rl = RateLimit {
20960                rate: 100,
20961                window: Duration::from_secs(non_canonical_window_secs),
20962            };
20963            s.politicas.rate_limit = Some(rl);
20964            assert_eq!(
20965                s.validate().unwrap_err(),
20966                AplicacaoError::PolicyRateLimitWindowNotCanonical {
20967                    window: rl.window(),
20968                },
20969                "non-canonical {non_canonical_window_secs}s window must be \
20970                 rejected by validate_politicas — the validate gate now \
20971                 keys off RateLimit::canonical_unit().is_none()"
20972            );
20973            assert!(
20974                rl.canonical_unit().is_none(),
20975                "non-canonical {non_canonical_window_secs}s window must \
20976                 resolve to None on RateLimit::canonical_unit — the two \
20977                 paths (the free helper the validate gate previously read \
20978                 and the substrate primitive the validate gate now reads) \
20979                 must agree on the same rejected set"
20980            );
20981        }
20982        // And the substrate-primitive [`RateLimit::canonical_unit`]
20983        // accessor's accepted-window set matches the codec's parse arm's
20984        // accepted-suffix set on every canonical / non-canonical shape,
20985        // so a future silent drift between the codec's accepted set and
20986        // the validate gate's accepted set is a build error at test time
20987        // (both consumers key off the same closed-set enum's `match self`
20988        // arms). The predecessor free helper `is_canonical_rate_limit_window`
20989        // — a delegate that composed [`RateLimitUnit::from_window`] with
20990        // `.is_some()` — was deleted after this migration; the
20991        // canonical-window set now lives on exactly one typed dispatch
20992        // on the substrate primitive.
20993        for (secs, expected) in [
20994            (1u64, true),
20995            (60, true),
20996            (3600, true),
20997            (2, false),
20998            (30, false),
20999            (86_400, false),
21000        ] {
21001            let window = Duration::from_secs(secs);
21002            let rl = RateLimit { rate: 1, window };
21003            assert_eq!(
21004                rl.canonical_unit().is_some(),
21005                expected,
21006                "RateLimit::canonical_unit().is_some() must agree with the \
21007                 codec-accepted canonical-window set on {secs}s"
21008            );
21009            let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
21010                1 => "s",
21011                60 => "m",
21012                3600 => "h",
21013                _ => return,
21014            })
21015            .is_some_and(|d| d == window);
21016            if expected {
21017                assert!(
21018                    suffix_from_axis,
21019                    "the codec's `&str → Duration` axis \
21020                     ({secs}s) must round-trip to the same Duration the \
21021                     substrate primitive's accessor returns Some on"
21022                );
21023            }
21024        }
21025    }
21026
21027    #[test]
21028    fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
21029        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
21030        // derive: for each of the three variants, exactly one of the
21031        // generated `is_second` / `is_minute` / `is_hour` predicates
21032        // returns `true` and the other two return `false`. Peer of
21033        // the sibling
21034        // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
21035        // sibling `IsVariant`-derived closed-set typed-enum pins.
21036        let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
21037            (super::RateLimitUnit::Second, [true, false, false]),
21038            (super::RateLimitUnit::Minute, [false, true, false]),
21039            (super::RateLimitUnit::Hour, [false, false, true]),
21040        ];
21041        for (variant, expected) in rows {
21042            let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
21043            assert_eq!(
21044                observed, expected,
21045                "RateLimitUnit::{variant:?} is_* predicates must partition \
21046                 the arm set (second, minute, hour); got {observed:?}"
21047            );
21048        }
21049    }
21050
21051    #[test]
21052    fn rejects_policy_timeout_sub_millisecond() {
21053        // A purely sub-millisecond `Duration` (`from_micros(500)` =
21054        // 500_000 ns) is not the zero `Duration` — the `is_zero()`
21055        // arm passes — but `as_millis() == 0`, so the shared codec's
21056        // `render` arm returns the literal `"0s"`, which the
21057        // codec's `parse` arm then deserializes as `Duration::ZERO`
21058        // and the `PolicyTimeoutZero` zero-floor gate would reject
21059        // on re-validate. Pin the rejection at the typed slot's
21060        // canonical-floor gate so the round-trip break surfaces at
21061        // validate time, naming the offending `Duration`, rather
21062        // than at the next serialize → deserialize round-trip far
21063        // from the source `caixa.lisp`.
21064        let mut s = three_member_spec();
21065        let timeout = Duration::from_micros(500);
21066        s.politicas.timeout = Some(timeout);
21067        assert_eq!(
21068            s.validate().unwrap_err(),
21069            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
21070        );
21071    }
21072
21073    #[test]
21074    fn rejects_policy_timeout_non_integer_millisecond() {
21075        // A `Duration` with non-integer-millisecond residue
21076        // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
21077        // through the shared codec's `render` arm as `"1ms"` (the
21078        // `as_millis()` floor truncates), which the codec's `parse`
21079        // arm then deserializes as `Duration::from_millis(1)` =
21080        // 1_000_000 ns — silently *different* from the original.
21081        // Pin the rejection so this round-trip break surfaces at
21082        // validate time, where the offending `Duration` is named,
21083        // rather than as a silent value-laundered round-trip on the
21084        // next codec round-trip.
21085        let mut s = three_member_spec();
21086        let timeout = Duration::from_micros(1500);
21087        s.politicas.timeout = Some(timeout);
21088        assert_eq!(
21089            s.validate().unwrap_err(),
21090            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
21091        );
21092    }
21093
21094    #[test]
21095    fn accepts_policy_timeout_integer_millisecond_forms() {
21096        // The codec's accepted set — integer multiples of 1ms — is
21097        // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
21098        // `1h` all pass the canonical gate. Pin the canonical-forms
21099        // sweep so a future tightening of the codec's grammar (e.g.
21100        // dropping `:ms`) surfaces here as a test failure rather
21101        // than a silent contract narrowing on the typed slot.
21102        for timeout in [
21103            Duration::from_millis(1),
21104            Duration::from_millis(500),
21105            Duration::from_millis(1500),
21106            Duration::from_secs(30),
21107            Duration::from_secs(120),
21108            Duration::from_secs(3600),
21109        ] {
21110            let mut s = three_member_spec();
21111            s.politicas.timeout = Some(timeout);
21112            s.validate()
21113                .expect("integer-millisecond :timeout must validate");
21114        }
21115    }
21116
21117    #[test]
21118    fn policy_timeout_zero_takes_precedence_over_canonical() {
21119        // `Duration::ZERO` carries `subsec_nanos() == 0` and would
21120        // pass the canonical-millisecond gate; the more self-locating
21121        // `PolicyTimeoutZero` arm (which names the omit-axis
21122        // remediation directly) must fire first. Pin the ordering so
21123        // a future refactor that reorders the arms surfaces here as a
21124        // test failure rather than a silent diagnostic regression.
21125        let mut s = three_member_spec();
21126        s.politicas.timeout = Some(Duration::ZERO);
21127        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
21128    }
21129
21130    #[test]
21131    fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
21132        // The diagnostic envelope carries the offending `Duration`
21133        // verbatim so the author can grep their `caixa.lisp` for
21134        // `:timeout "<value>"` and fix it in one edit. Same
21135        // diagnostic shape every other typed-slot canonical-form
21136        // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
21137        // peer `:rate-limit :window` axis.
21138        let mut s = three_member_spec();
21139        let timeout = Duration::from_nanos(1_000_001);
21140        s.politicas.timeout = Some(timeout);
21141        match s.validate().unwrap_err() {
21142            AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
21143                assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
21144            }
21145            other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
21146        }
21147    }
21148
21149    #[test]
21150    fn rejects_policy_timeout_above_cap() {
21151        // The fail-before-pass-after pin: 3601s = 1h + 1s is
21152        // structurally one canonical-tick past the
21153        // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
21154        // integer-millisecond magnitude the canonical-form arm above
21155        // accepts cleanly, that the codec round-trips losslessly as
21156        // `"3601s"`, and that silently passed validate on every
21157        // pre-gate codebase because the typed slot's only checks were
21158        // the zero-floor and canonical-form arms. The mesh-level
21159        // deadline degenerates only at the runtime substrate (Envoy
21160        // / Cilium L7 timeout overlay) far from the source
21161        // `caixa.lisp` with no field naming the offending policy.
21162        let mut s = three_member_spec();
21163        let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
21164        s.politicas.timeout = Some(timeout);
21165        assert_eq!(
21166            s.validate().unwrap_err(),
21167            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
21168        );
21169    }
21170
21171    #[test]
21172    fn rejects_policy_timeout_one_millisecond_above_cap() {
21173        // Boundary case: exactly 1ms past the cap (the granularity
21174        // the canonical-form gate enforces). Catches a future
21175        // "strictly less than" half-measure and pins the diagnostic
21176        // to name the offending `Duration` verbatim. Peer of
21177        // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
21178        // boundary pin on the sibling `:limits :memory` top edge.
21179        let mut s = three_member_spec();
21180        let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
21181        s.politicas.timeout = Some(timeout);
21182        assert_eq!(
21183            s.validate().unwrap_err(),
21184            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
21185        );
21186    }
21187
21188    #[test]
21189    fn rejects_policy_timeout_far_above_cap() {
21190        // The "obvious authoring footgun" case: a `(:timeout "24h")`
21191        // or `(:timeout "86400s")` — values the canonical-form arm
21192        // accepts as integer-millisecond magnitudes, the codec
21193        // round-trips losslessly through serde, but the mesh-level
21194        // policy cannot honor (a 24-hour synchronous-`:contratos`
21195        // deadline is operationally indistinguishable from
21196        // omit-the-axis). Until this gate landed validate accepted
21197        // it. Pin both common above-cap values (24h, 7d) so a future
21198        // relaxation that drops the upper bound surfaces here.
21199        for timeout in [
21200            Duration::from_secs(86_400),    // 24h
21201            Duration::from_secs(604_800),   // 7d
21202            Duration::from_secs(1_000_000), // ~11.5 days
21203        ] {
21204            let mut s = three_member_spec();
21205            s.politicas.timeout = Some(timeout);
21206            assert_eq!(
21207                s.validate().unwrap_err(),
21208                AplicacaoError::PolicyTimeoutExceedsCap { timeout }
21209            );
21210        }
21211    }
21212
21213    #[test]
21214    fn accepts_policy_timeout_at_cap() {
21215        // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
21216        // must validate. The cap is inclusive on the top edge,
21217        // matching the [`POLICY_RETRIES_MAX`] /
21218        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
21219        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
21220        // sibling capped axes. Pin the boundary explicitly so a
21221        // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
21222        // instead of `>`) surfaces here as a test failure rather
21223        // than a silent contract narrowing.
21224        let mut s = three_member_spec();
21225        s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
21226        s.validate()
21227            .expect("timeout == POLICY_TIMEOUT_MAX must validate");
21228    }
21229
21230    #[test]
21231    fn accepts_policy_timeout_typical_values() {
21232        // The documented production-playbook band positive-control
21233        // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
21234        // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
21235        // plus a sweep through the long-running-workflow band
21236        // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
21237        // validated set explicitly so a future tightening of the
21238        // ceiling surfaces here as a deliberate test edit, not a
21239        // silent contract narrowing.
21240        for timeout in [
21241            Duration::from_millis(1),
21242            Duration::from_millis(500),
21243            Duration::from_secs(1),
21244            Duration::from_secs(10),
21245            Duration::from_secs(15), // Envoy default
21246            Duration::from_secs(30),
21247            Duration::from_secs(60), // AWS App Mesh typical
21248            Duration::from_secs(300),
21249            Duration::from_secs(900),
21250            Duration::from_secs(1800),
21251            Duration::from_secs(3600), // exactly 1h, the cap
21252        ] {
21253            let mut s = three_member_spec();
21254            s.politicas.timeout = Some(timeout);
21255            s.validate()
21256                .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
21257        }
21258    }
21259
21260    #[test]
21261    fn policy_timeout_zero_takes_precedence_over_cap() {
21262        // The cross-arm ordering pin: `Duration::ZERO` is
21263        // structurally outside both `>= 1ms` (zero-floor) and
21264        // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
21265        // diagnostic is the more self-locating one (it directly
21266        // names the omit-axis remediation), so the validate gate
21267        // must fire on zero first. Same shape every other
21268        // zero-then-shape ordering on this surface uses
21269        // ([`AplicacaoError::PolicyRetriesZero`] then
21270        // [`AplicacaoError::PolicyRetriesExceedsCap`];
21271        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
21272        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
21273        let mut s = three_member_spec();
21274        s.politicas.timeout = Some(Duration::ZERO);
21275        assert_eq!(
21276            s.validate().unwrap_err(),
21277            AplicacaoError::PolicyTimeoutZero,
21278            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
21279        );
21280    }
21281
21282    #[test]
21283    fn policy_timeout_canonical_takes_precedence_over_cap() {
21284        // The cross-arm ordering pin: a `Duration` that is *both*
21285        // sub-millisecond (non-canonical-form) and structurally
21286        // above the cap surfaces the canonical-form diagnostic
21287        // first, because the round-trip-shape break is the more
21288        // fundamental issue (the value can't even round-trip
21289        // through the codec, so the cap diagnostic naming
21290        // `1ms..=1h` would be misleading — there's no integer-ms
21291        // form of the offending value). Pin the order so a future
21292        // refactor that reorders the arms surfaces here as a test
21293        // failure rather than a silent diagnostic regression.
21294        let mut s = three_member_spec();
21295        // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
21296        // *and* total magnitude above the 1h cap.
21297        let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
21298        s.politicas.timeout = Some(timeout);
21299        assert_eq!(
21300            s.validate().unwrap_err(),
21301            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
21302            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
21303        );
21304    }
21305
21306    #[test]
21307    fn policy_timeout_cap_diagnostic_carries_offending_value() {
21308        // The diagnostic-shape pin: the offending `Duration` is
21309        // carried verbatim into the
21310        // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
21311        // surfaced error message names the value the author wrote
21312        // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
21313        // exceeds the mesh-policy ceiling …"`), not just the cap.
21314        // Same self-locating diagnostic shape every other typed-cap
21315        // arm on this surface carries
21316        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
21317        // offending retry count verbatim).
21318        let mut s = three_member_spec();
21319        let timeout = Duration::from_secs(7200); // 2h
21320        s.politicas.timeout = Some(timeout);
21321        let err = s.validate().unwrap_err();
21322        assert!(
21323            matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
21324            "got {err:?}"
21325        );
21326        let msg = err.to_string();
21327        assert!(
21328            msg.contains("7200"),
21329            ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
21330        );
21331    }
21332
21333    #[test]
21334    fn policy_timeout_cap_pins_canonical_value() {
21335        // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
21336        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
21337        // the shared duration codec emits as a clean canonical
21338        // string (`"<n>h"`). Pinning the literal value here surfaces
21339        // a future drift (a relaxation to 24h, a tightening to 5m)
21340        // as a deliberate test edit, not a silent contract
21341        // narrowing. Same shape every other typed-cap value pin on
21342        // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
21343        assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
21344        assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
21345    }
21346
21347    #[test]
21348    fn policy_timeout_cap_value_round_trips_through_codec() {
21349        // The codec round-trip property the cap arm preserves: the
21350        // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
21351        // the shared duration codec — every value at the cap renders
21352        // to a clean canonical string (`"1h"`) and parses back to
21353        // the same `Duration`. Pin this so a future drift between
21354        // the cap constant and the codec's largest emitted unit
21355        // surfaces here. Same shape every other typed boundary pin
21356        // on this surface uses
21357        // (`wasm32_memory_cap_matches_parsed_4_gib`).
21358        let policy = MeshPolicy {
21359            timeout: Some(POLICY_TIMEOUT_MAX),
21360            ..Default::default()
21361        };
21362        let json = serde_json::to_string(&policy).unwrap();
21363        // The codec emits `"1h"` for the canonical 1-hour magnitude.
21364        assert!(
21365            json.contains("\"1h\""),
21366            "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
21367        );
21368        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
21369        assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
21370    }
21371
21372    #[test]
21373    fn rejects_circuit_breaker_window_sub_millisecond() {
21374        // Peer of the `:timeout` sub-millisecond arm on the second
21375        // typed-`Duration` `:politicas` axis: a purely sub-ms
21376        // `Duration` (`from_micros(500)`) renders through the shared
21377        // codec as `"0s"`, which the codec parses back to
21378        // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
21379        // zero-floor gate then rejects on re-validate.
21380        let mut s = three_member_spec();
21381        let window = Duration::from_micros(500);
21382        s.politicas.circuit_breaker = Some(CircuitBreaker {
21383            max_failures: 5,
21384            window,
21385        });
21386        assert_eq!(
21387            s.validate().unwrap_err(),
21388            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
21389        );
21390    }
21391
21392    #[test]
21393    fn rejects_circuit_breaker_window_non_integer_millisecond() {
21394        // Peer of the `:timeout` non-integer-ms arm: a `Duration`
21395        // with non-integer-millisecond residue renders through the
21396        // shared codec as the truncated `"<n>ms"` form, parsing back
21397        // to a *different* `Duration` on the next round-trip.
21398        let mut s = three_member_spec();
21399        let window = Duration::from_micros(1500);
21400        s.politicas.circuit_breaker = Some(CircuitBreaker {
21401            max_failures: 5,
21402            window,
21403        });
21404        assert_eq!(
21405            s.validate().unwrap_err(),
21406            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
21407        );
21408    }
21409
21410    #[test]
21411    fn accepts_circuit_breaker_window_integer_millisecond_forms() {
21412        // The canonical-forms sweep on the breaker axis: every
21413        // integer-ms multiple the codec round-trips losslessly
21414        // passes the canonical gate.
21415        //
21416        // Clears `:timeout` from the fixture so this per-axis sweep
21417        // covers windows shorter than the fixture's 30s timeout
21418        // (1ms, 500ms, 1500ms) — the sub-timeout arm is a
21419        // structurally-inert breaker
21420        // ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]) that
21421        // the cross-axis gate at the end of
21422        // [`AplicacaoSpec::validate_politicas`] rejects on the paired
21423        // `(:timeout, :window)` shape, not on the per-axis
21424        // integer-millisecond canonical-form shape this test pins.
21425        // The paired shape is covered by
21426        // `rejects_circuit_breaker_window_below_timeout`.
21427        for window in [
21428            Duration::from_millis(1),
21429            Duration::from_millis(500),
21430            Duration::from_millis(1500),
21431            Duration::from_secs(30),
21432            Duration::from_secs(60),
21433            Duration::from_secs(3600),
21434        ] {
21435            let mut s = three_member_spec();
21436            s.politicas.timeout = None;
21437            s.politicas.circuit_breaker = Some(CircuitBreaker {
21438                max_failures: 5,
21439                window,
21440            });
21441            s.validate()
21442                .expect("integer-millisecond :circuit-breaker :window must validate");
21443        }
21444    }
21445
21446    #[test]
21447    fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
21448        // `Duration::ZERO` would pass the canonical-ms gate (the
21449        // sub-ns residue is zero) but must surface the narrower
21450        // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
21451        // remediation.
21452        let mut s = three_member_spec();
21453        s.politicas.circuit_breaker = Some(CircuitBreaker {
21454            max_failures: 5,
21455            window: Duration::ZERO,
21456        });
21457        assert_eq!(
21458            s.validate().unwrap_err(),
21459            AplicacaoError::PolicyBreakerZeroWindow
21460        );
21461    }
21462
21463    #[test]
21464    fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
21465        // Both axes invalid: max_failures == 0 *and* window is
21466        // sub-ms. The validate gate must fire on max_failures first
21467        // (matching the existing ordering pin
21468        // `rejects_circuit_breaker_zero_max_failures` enshrines), so
21469        // the existing diagnostic continues to lead with the simpler
21470        // "zero threshold" framing.
21471        let mut s = three_member_spec();
21472        s.politicas.circuit_breaker = Some(CircuitBreaker {
21473            max_failures: 0,
21474            window: Duration::from_micros(500),
21475        });
21476        assert_eq!(
21477            s.validate().unwrap_err(),
21478            AplicacaoError::PolicyBreakerZeroFailures
21479        );
21480    }
21481
21482    #[test]
21483    fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
21484        let mut s = three_member_spec();
21485        let window = Duration::from_nanos(60_000_000_001);
21486        s.politicas.circuit_breaker = Some(CircuitBreaker {
21487            max_failures: 5,
21488            window,
21489        });
21490        match s.validate().unwrap_err() {
21491            AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
21492                assert_eq!(w, window, "diagnostic must carry the offending Duration");
21493            }
21494            other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
21495        }
21496    }
21497
21498    #[test]
21499    fn rejects_circuit_breaker_window_above_cap() {
21500        // The fail-before-pass-after pin: 3601s = 1h + 1s is
21501        // structurally one canonical-tick past the
21502        // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
21503        // integer-millisecond magnitude the canonical-form arm above
21504        // accepts cleanly, that the codec round-trips losslessly as
21505        // `"3601s"`, and that silently passed validate on every
21506        // pre-gate codebase because the typed slot's only checks were
21507        // the zero-floor and canonical-form arms. The
21508        // rolling-window-to-lifetime-counter degeneration surfaces
21509        // only at the runtime substrate (Envoy's outlier_detection
21510        // interval, the future CiliumClusterwideEnvoyConfig overlay)
21511        // far from the source `caixa.lisp` with no field naming the
21512        // offending policy.
21513        let mut s = three_member_spec();
21514        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
21515        s.politicas.circuit_breaker = Some(CircuitBreaker {
21516            max_failures: 5,
21517            window,
21518        });
21519        assert_eq!(
21520            s.validate().unwrap_err(),
21521            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
21522        );
21523    }
21524
21525    #[test]
21526    fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
21527        // Boundary case: exactly 1ms past the cap (the granularity the
21528        // canonical-form gate enforces). Catches a future "strictly
21529        // less than" half-measure and pins the diagnostic to name the
21530        // offending `Duration` verbatim. Peer of
21531        // `rejects_policy_timeout_one_millisecond_above_cap` on the
21532        // sibling duration-typed `:politicas :timeout` top edge.
21533        let mut s = three_member_spec();
21534        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
21535        s.politicas.circuit_breaker = Some(CircuitBreaker {
21536            max_failures: 5,
21537            window,
21538        });
21539        assert_eq!(
21540            s.validate().unwrap_err(),
21541            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
21542        );
21543    }
21544
21545    #[test]
21546    fn rejects_circuit_breaker_window_far_above_cap() {
21547        // The "obvious authoring footgun" case: a `(:window "24h")` or
21548        // `(:window "86400s")` — values the canonical-form arm
21549        // accepts as integer-millisecond magnitudes, the codec
21550        // round-trips losslessly through serde, but the
21551        // rolling-window breaker contract cannot honor (a 24-hour
21552        // rolling failure window is operationally a lifetime counter).
21553        // Until this gate landed validate accepted it. Pin both common
21554        // above-cap values (24h, 7d) so a future relaxation that
21555        // drops the upper bound surfaces here.
21556        for window in [
21557            Duration::from_secs(86_400),    // 24h
21558            Duration::from_secs(604_800),   // 7d
21559            Duration::from_secs(1_000_000), // ~11.5 days
21560        ] {
21561            let mut s = three_member_spec();
21562            s.politicas.circuit_breaker = Some(CircuitBreaker {
21563                max_failures: 5,
21564                window,
21565            });
21566            assert_eq!(
21567                s.validate().unwrap_err(),
21568                AplicacaoError::PolicyBreakerWindowExceedsCap { window }
21569            );
21570        }
21571    }
21572
21573    #[test]
21574    fn accepts_circuit_breaker_window_at_cap() {
21575        // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
21576        // (1h) — must validate. The cap is inclusive on the top edge,
21577        // matching the [`POLICY_TIMEOUT_MAX`] /
21578        // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
21579        // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
21580        // sibling capped axes. Pin the boundary explicitly so a
21581        // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
21582        // instead of `>`) surfaces here as a test failure rather than
21583        // a silent contract narrowing.
21584        let mut s = three_member_spec();
21585        s.politicas.circuit_breaker = Some(CircuitBreaker {
21586            max_failures: 5,
21587            window: POLICY_BREAKER_WINDOW_MAX,
21588        });
21589        s.validate()
21590            .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
21591    }
21592
21593    #[test]
21594    fn accepts_circuit_breaker_window_typical_values() {
21595        // The documented production-playbook band positive-control
21596        // sweep — every value Hystrix / resilience4j / Istio / Envoy
21597        // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
21598        // through the long-tail failure-detection band (15m, 30m, 1h)
21599        // the cap accepts. Pin the inclusive validated set explicitly
21600        // so a future tightening of the ceiling surfaces here as a
21601        // deliberate test edit, not a silent contract narrowing.
21602        //
21603        // Clears `:timeout` from the fixture so this per-axis sweep
21604        // covers windows shorter than the fixture's 30s timeout
21605        // (Hystrix's 10s default, resilience4j's 30s, and the
21606        // sub-second warm-up band) — every such value is a
21607        // structurally-inert breaker under the cross-axis gate at the
21608        // end of [`AplicacaoSpec::validate_politicas`]
21609        // ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]), and
21610        // the paired `(:timeout, :window)` shape is covered by
21611        // `rejects_circuit_breaker_window_below_timeout`; this
21612        // per-axis pin ranges only over the per-axis-bracket accept set.
21613        for window in [
21614            Duration::from_millis(1),
21615            Duration::from_millis(500),
21616            Duration::from_secs(1),
21617            Duration::from_secs(10), // Hystrix / Istio / Envoy default
21618            Duration::from_secs(30),
21619            Duration::from_secs(60),  // resilience4j typical
21620            Duration::from_secs(300), // AWS App Mesh typical
21621            Duration::from_secs(900),
21622            Duration::from_secs(1800),
21623            Duration::from_secs(3600), // exactly 1h, the cap
21624        ] {
21625            let mut s = three_member_spec();
21626            s.politicas.timeout = None;
21627            s.politicas.circuit_breaker = Some(CircuitBreaker {
21628                max_failures: 5,
21629                window,
21630            });
21631            s.validate()
21632                .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
21633        }
21634    }
21635
21636    #[test]
21637    fn circuit_breaker_zero_window_takes_precedence_over_cap() {
21638        // The cross-arm ordering pin: `Duration::ZERO` is structurally
21639        // outside both `>= 1ms` (zero-floor) and
21640        // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
21641        // diagnostic is the more self-locating one (it directly names
21642        // the omit-axis remediation), so the validate gate must fire
21643        // on zero first. Same shape every other zero-then-cap
21644        // ordering on this surface uses
21645        // ([`AplicacaoError::PolicyTimeoutZero`] then
21646        // [`AplicacaoError::PolicyTimeoutExceedsCap`];
21647        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
21648        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
21649        let mut s = three_member_spec();
21650        s.politicas.circuit_breaker = Some(CircuitBreaker {
21651            max_failures: 5,
21652            window: Duration::ZERO,
21653        });
21654        assert_eq!(
21655            s.validate().unwrap_err(),
21656            AplicacaoError::PolicyBreakerZeroWindow,
21657            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
21658        );
21659    }
21660
21661    #[test]
21662    fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
21663        // The cross-arm ordering pin: a `Duration` that is *both*
21664        // sub-millisecond (non-canonical-form) and structurally above
21665        // the cap surfaces the canonical-form diagnostic first,
21666        // because the round-trip-shape break is the more fundamental
21667        // issue (the value can't even round-trip through the codec, so
21668        // the cap diagnostic naming `1ms..=1h` would be misleading —
21669        // there's no integer-ms form of the offending value). Pin the
21670        // order so a future refactor that reorders the arms surfaces
21671        // here as a test failure rather than a silent diagnostic
21672        // regression. Peer of
21673        // `policy_timeout_canonical_takes_precedence_over_cap` on the
21674        // sibling duration-typed `:politicas :timeout` axis.
21675        let mut s = three_member_spec();
21676        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
21677        s.politicas.circuit_breaker = Some(CircuitBreaker {
21678            max_failures: 5,
21679            window,
21680        });
21681        assert_eq!(
21682            s.validate().unwrap_err(),
21683            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
21684            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
21685        );
21686    }
21687
21688    #[test]
21689    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
21690        // The cross-arm ordering pin between the two breaker axes: a
21691        // `CircuitBreaker` whose *both* `max_failures` is above its
21692        // cap *and* `window` is above its cap surfaces the
21693        // max-failures cap diagnostic first, because the validate
21694        // gate visits the failures arm before the window arm. Pin the
21695        // order so a future refactor that reorders the breaker arms
21696        // surfaces here.
21697        let mut s = three_member_spec();
21698        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
21699        s.politicas.circuit_breaker = Some(CircuitBreaker {
21700            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
21701            window,
21702        });
21703        assert_eq!(
21704            s.validate().unwrap_err(),
21705            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
21706                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
21707            },
21708            "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
21709        );
21710    }
21711
21712    #[test]
21713    fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
21714        // The diagnostic-shape pin: the offending `Duration` is
21715        // carried verbatim into the
21716        // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
21717        // the surfaced error message names the value the author wrote
21718        // (`":politicas :circuit-breaker :window (Duration { secs:
21719        // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
21720        // just the cap. Same self-locating diagnostic shape every
21721        // other typed-cap arm on this surface carries
21722        // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
21723        // offending `Duration` verbatim).
21724        let mut s = three_member_spec();
21725        let window = Duration::from_secs(7200); // 2h
21726        s.politicas.circuit_breaker = Some(CircuitBreaker {
21727            max_failures: 5,
21728            window,
21729        });
21730        let err = s.validate().unwrap_err();
21731        assert!(
21732            matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
21733            "got {err:?}"
21734        );
21735        let msg = err.to_string();
21736        assert!(
21737            msg.contains("7200"),
21738            ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
21739        );
21740    }
21741
21742    #[test]
21743    fn circuit_breaker_window_cap_pins_canonical_value() {
21744        // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
21745        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
21746        // shared duration codec emits as a clean canonical string
21747        // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
21748        // the sibling duration-typed `:politicas :timeout` axis (the
21749        // two duration-typed `:politicas` axes share a uniform top
21750        // edge). Pinning the literal value here surfaces a future
21751        // drift (a relaxation to 24h, a tightening to 5m) as a
21752        // deliberate test edit, not a silent contract narrowing. Same
21753        // shape every other typed-cap value pin on this surface uses
21754        // (`policy_timeout_cap_pins_canonical_value`).
21755        assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
21756        assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
21757        assert_eq!(
21758            POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
21759            "the two duration-typed `:politicas` caps share the same top edge"
21760        );
21761    }
21762
21763    #[test]
21764    fn circuit_breaker_window_cap_value_round_trips_through_codec() {
21765        // The codec round-trip property the cap arm preserves: the
21766        // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
21767        // through the shared duration codec — every value at the cap
21768        // renders to a clean canonical string (`"1h"`) and parses back
21769        // to the same `Duration`. Pin this so a future drift between
21770        // the cap constant and the codec's largest emitted unit
21771        // surfaces here. Same shape every other typed boundary pin on
21772        // this surface uses
21773        // (`policy_timeout_cap_value_round_trips_through_codec`).
21774        let policy = MeshPolicy {
21775            circuit_breaker: Some(CircuitBreaker {
21776                max_failures: 5,
21777                window: POLICY_BREAKER_WINDOW_MAX,
21778            }),
21779            ..Default::default()
21780        };
21781        let json = serde_json::to_string(&policy).unwrap();
21782        // The codec emits `"1h"` for the canonical 1-hour magnitude.
21783        assert!(
21784            json.contains("\"1h\""),
21785            "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
21786        );
21787        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
21788        assert_eq!(
21789            back.circuit_breaker.unwrap().window,
21790            POLICY_BREAKER_WINDOW_MAX
21791        );
21792    }
21793
21794    #[test]
21795    fn is_integer_millisecond_duration_predicate_tracks_codec() {
21796        // Pin the predicate's accepted set against the codec's
21797        // accepted set explicitly. The codec parses
21798        // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
21799        // accepted value is an integer-millisecond multiple — so the
21800        // predicate must accept exactly that set. Same shape every
21801        // other predicate-on-the-typed-slot helper carries
21802        // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
21803        // Read directly from the codec-owned predicate — the crate's
21804        // single source of truth every typed-`Duration` axis now routes
21805        // through via
21806        // [`crate::render::require_positive_canonical_bounded_duration`].
21807        use super::supervisor::duration_codec::is_integer_millisecond_duration;
21808        assert!(is_integer_millisecond_duration(Duration::ZERO));
21809        assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
21810        assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
21811        assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
21812        assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
21813        assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
21814        // Non-integer-millisecond residue: rejected.
21815        assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
21816        assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
21817        assert!(!is_integer_millisecond_duration(Duration::from_micros(
21818            1500
21819        )));
21820        assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
21821        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
21822            999_999
21823        )));
21824        // The 1-ns-past-1ms boundary: rejected (no longer a clean
21825        // integer-millisecond multiple).
21826        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
21827            1_000_001
21828        )));
21829    }
21830
21831    #[test]
21832    fn policy_timeout_validated_value_round_trips_through_codec() {
21833        // The structural property the canonical-ms gate enforces:
21834        // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
21835        // round-trips losslessly through the shared `duration_codec`
21836        // (serialize → string → deserialize → equal value). Pin this
21837        // end-to-end so a future change to either side (the validate
21838        // gate's accepted granularity, the codec's parse/render unit
21839        // set) that breaks the alignment surfaces here. The
21840        // previous-state shape (typed slot accepts arbitrary
21841        // `Duration`, codec only round-trips integer-ms) would fail
21842        // this test for any `Duration::from_micros(1500)` timeout —
21843        // the validate gate now forecloses that.
21844        for timeout in [
21845            Duration::from_millis(1),
21846            Duration::from_millis(1500),
21847            Duration::from_secs(30),
21848            Duration::from_secs(3600),
21849        ] {
21850            let mut s = three_member_spec();
21851            s.politicas.timeout = Some(timeout);
21852            s.validate().unwrap();
21853            let json = serde_json::to_string(&s.politicas).unwrap();
21854            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
21855            assert_eq!(
21856                back.timeout, s.politicas.timeout,
21857                "every validated :timeout must round-trip losslessly through the codec"
21858            );
21859        }
21860    }
21861
21862    #[test]
21863    fn circuit_breaker_window_validated_value_round_trips_through_codec() {
21864        // Peer of the `:timeout` round-trip property on the breaker
21865        // axis.
21866        //
21867        // Clears `:timeout` from the fixture so the round-trip pin
21868        // ranges over sub-timeout `Duration` values (1ms, 1500ms) the
21869        // cross-axis gate would otherwise reject as structurally-inert
21870        // breakers ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]);
21871        // the paired `(:timeout, :window)` cross-axis relation is
21872        // pinned separately by
21873        // `rejects_circuit_breaker_window_below_timeout`, and this
21874        // property is a pure serde-codec round-trip on the per-axis
21875        // slot.
21876        for window in [
21877            Duration::from_millis(1),
21878            Duration::from_millis(1500),
21879            Duration::from_secs(30),
21880            Duration::from_secs(3600),
21881        ] {
21882            let mut s = three_member_spec();
21883            s.politicas.timeout = None;
21884            s.politicas.circuit_breaker = Some(CircuitBreaker {
21885                max_failures: 5,
21886                window,
21887            });
21888            s.validate().unwrap();
21889            let json = serde_json::to_string(&s.politicas).unwrap();
21890            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
21891            assert_eq!(
21892                back.circuit_breaker.unwrap().window,
21893                window,
21894                "every validated :circuit-breaker :window must round-trip losslessly"
21895            );
21896        }
21897    }
21898
21899    #[test]
21900    fn rejects_circuit_breaker_window_below_timeout() {
21901        // The fail-before-pass-after pin on the cross-axis
21902        // `(:timeout, :circuit-breaker :window)` invariant. Each axis
21903        // is individually well-formed under its own per-axis bracket
21904        // (both integer-millisecond, both above the zero floor, both
21905        // below the cap), but the pair is a structurally-inert
21906        // breaker: a call dispatched at t=0 is declared failed at
21907        // t=30s, by which point the 10s rolling window open at
21908        // dispatch has already rolled twice, so no window can hold
21909        // a timeout-derived failure however high the call volume.
21910        //
21911        // Envoy's `outlier_detection.interval` against the per-route
21912        // request timeout carries the identical relation; Hystrix
21913        // ships the canonical ratio in its defaults (10s window
21914        // against a 1s timeout — a 10× ratio, not a 3× under-ratio).
21915        //
21916        // Pin both the diagnostic arm and the payload values so a
21917        // future re-shape of the arm surfaces here as a deliberate
21918        // test edit.
21919        let mut s = three_member_spec();
21920        s.politicas.timeout = Some(Duration::from_secs(30));
21921        s.politicas.circuit_breaker = Some(CircuitBreaker {
21922            max_failures: 5,
21923            window: Duration::from_secs(10),
21924        });
21925        assert_eq!(
21926            s.validate().unwrap_err(),
21927            AplicacaoError::PolicyBreakerWindowBelowTimeout {
21928                window: Duration::from_secs(10),
21929                timeout: Duration::from_secs(30),
21930            }
21931        );
21932    }
21933
21934    #[test]
21935    fn accepts_circuit_breaker_window_equal_to_timeout() {
21936        // Boundary pin: `:window == :timeout` is the smallest window
21937        // that structurally admits at least one full timeout-derived
21938        // failure before the rolling interval closes (the invariant
21939        // is `:window >= :timeout`, not strict inequality). Catches
21940        // a future off-by-one tightening that would drift the accept
21941        // set away from the codified [`MeshPolicy::breaker_window_
21942        // observes_timeout`] predicate.
21943        let mut s = three_member_spec();
21944        s.politicas.timeout = Some(Duration::from_secs(30));
21945        s.politicas.circuit_breaker = Some(CircuitBreaker {
21946            max_failures: 5,
21947            window: Duration::from_secs(30),
21948        });
21949        s.validate()
21950            .expect("window == timeout is the boundary accept case");
21951    }
21952
21953    #[test]
21954    fn accepts_circuit_breaker_window_above_timeout() {
21955        // Positive-control sweep across the production-playbook band —
21956        // Hystrix (1s timeout / 10s window, 10× ratio), Istio (5s /
21957        // 30s, 6×), Envoy (10s / 60s, 6×), resilience4j (30s / 300s,
21958        // 10×), AWS App Mesh (60s / 300s, 5×). Every pair a real
21959        // playbook recommends must validate under the cross-axis gate.
21960        for (timeout, window) in [
21961            (Duration::from_secs(1), Duration::from_secs(10)),
21962            (Duration::from_secs(5), Duration::from_secs(30)),
21963            (Duration::from_secs(10), Duration::from_secs(60)),
21964            (Duration::from_secs(30), Duration::from_secs(300)),
21965            (Duration::from_secs(60), Duration::from_secs(300)),
21966        ] {
21967            let mut s = three_member_spec();
21968            s.politicas.timeout = Some(timeout);
21969            s.politicas.circuit_breaker = Some(CircuitBreaker {
21970                max_failures: 5,
21971                window,
21972            });
21973            s.validate().unwrap_or_else(|e| {
21974                panic!(
21975                    "production-playbook pair timeout={timeout:?}/window={window:?} must \
21976                     validate; got {e:?}"
21977                )
21978            });
21979        }
21980    }
21981
21982    #[test]
21983    fn circuit_breaker_window_below_timeout_by_one_millisecond_rejected() {
21984        // Off-by-one boundary pin: a window exactly 1ms shy of the
21985        // timeout is still structurally inert under the invariant
21986        // (the dispatch-to-report lag is `timeout`, so the window
21987        // must span at least one such lag). Catches a future
21988        // strict-inequality relaxation that would silently drift
21989        // the accept boundary.
21990        let timeout = Duration::from_secs(30);
21991        let window = Duration::from_millis(29_999);
21992        let mut s = three_member_spec();
21993        s.politicas.timeout = Some(timeout);
21994        s.politicas.circuit_breaker = Some(CircuitBreaker {
21995            max_failures: 5,
21996            window,
21997        });
21998        assert_eq!(
21999            s.validate().unwrap_err(),
22000            AplicacaoError::PolicyBreakerWindowBelowTimeout { window, timeout }
22001        );
22002    }
22003
22004    #[test]
22005    fn cross_axis_gate_vacuous_when_timeout_absent() {
22006        // The predicate is vacuously `true` when `:timeout` is None —
22007        // a `:circuit-breaker` alone declares no relation to a
22008        // substrate-imposed deadline (the failure signal reaches the
22009        // breaker from the transport's own error surface, so no
22010        // dispatch-to-report lag is knowable at author time). Pin so
22011        // a future tightening that made the gate opinionated on
22012        // half-declared pairs surfaces here.
22013        let mut s = three_member_spec();
22014        s.politicas.timeout = None;
22015        s.politicas.circuit_breaker = Some(CircuitBreaker {
22016            max_failures: 5,
22017            window: Duration::from_millis(1),
22018        });
22019        s.validate().expect(
22020            "cross-axis gate must be vacuous when :timeout is None, however small :window is",
22021        );
22022    }
22023
22024    #[test]
22025    fn cross_axis_gate_vacuous_when_circuit_breaker_absent() {
22026        // Peer of the sibling `:timeout`-absent case: a `:timeout`
22027        // without a `:circuit-breaker` declares a per-call deadline
22028        // without any rolling-window failure accounting, so the pair
22029        // is undeclared and the cross-axis gate has nothing to check.
22030        let mut s = three_member_spec();
22031        s.politicas.timeout = Some(Duration::from_secs(3600));
22032        s.politicas.circuit_breaker = None;
22033        s.validate().expect(
22034            "cross-axis gate must be vacuous when :circuit-breaker is None, \
22035             however large :timeout is",
22036        );
22037    }
22038
22039    #[test]
22040    fn cross_axis_gate_runs_after_per_axis_brackets() {
22041        // Ordering pin: a pair whose window is *both* zero-floor-
22042        // violating and structurally below the timeout must surface
22043        // the per-axis zero-floor arm first — the zero-floor
22044        // diagnostic is more self-locating (its omit-axis remediation
22045        // is directly named), where the cross-axis arm would send the
22046        // author to reconcile two values one of which is not a
22047        // meaningful window at all. Same ordering discipline every
22048        // per-axis bracket carries internally (zero-floor before
22049        // canonical-form before cap).
22050        let mut s = three_member_spec();
22051        s.politicas.timeout = Some(Duration::from_secs(30));
22052        s.politicas.circuit_breaker = Some(CircuitBreaker {
22053            max_failures: 5,
22054            window: Duration::ZERO,
22055        });
22056        assert_eq!(
22057            s.validate().unwrap_err(),
22058            AplicacaoError::PolicyBreakerZeroWindow,
22059            "per-axis zero-floor arm must fire before the cross-axis gate"
22060        );
22061    }
22062
22063    #[test]
22064    fn breaker_window_observes_timeout_predicate_matches_gate_semantic() {
22065        // Equivalence pin: the substrate-canonical
22066        // [`MeshPolicy::breaker_window_observes_timeout`] predicate
22067        // and the [`AplicacaoSpec::validate_politicas`] cross-axis
22068        // arm must discriminate the same set on every pair covered
22069        // by their shared invariant. A future refactor of either
22070        // side that breaks the equivalence trips here rather than as
22071        // a divergence between the predicate's Boolean answer and
22072        // the validate gate's Ok/Err arm — the same
22073        // predicate-vs-gate coherence discipline the peer
22074        // [`PlacementStrategy::is_shard_keyed`] predicate carries
22075        // against `AplicacaoSpec::validate_placement`. The sweep
22076        // covers both arms of the invariant (below, equal, above)
22077        // and both vacuous arms (None `:timeout`, None
22078        // `:circuit-breaker`), so the equivalence holds
22079        // exhaustively over the axis-covered accept and reject sets.
22080        let cases: &[(Option<Duration>, Option<Duration>)] = &[
22081            (Some(Duration::from_secs(30)), Some(Duration::from_secs(10))),
22082            (Some(Duration::from_secs(30)), Some(Duration::from_secs(29))),
22083            (Some(Duration::from_secs(30)), Some(Duration::from_secs(30))),
22084            (Some(Duration::from_secs(30)), Some(Duration::from_secs(60))),
22085            (Some(Duration::from_secs(1)), Some(Duration::from_secs(10))),
22086            (None, Some(Duration::from_secs(1))),
22087            (Some(Duration::from_secs(30)), None),
22088            (None, None),
22089        ];
22090        for (timeout, window) in cases.iter().copied() {
22091            let politicas = MeshPolicy {
22092                timeout,
22093                circuit_breaker: window.map(|w| CircuitBreaker {
22094                    max_failures: 5,
22095                    window: w,
22096                }),
22097                ..Default::default()
22098            };
22099            let predicate = politicas.breaker_window_observes_timeout();
22100
22101            let mut s = three_member_spec();
22102            s.politicas = politicas.clone();
22103            let gate_ok = !matches!(
22104                s.validate(),
22105                Err(AplicacaoError::PolicyBreakerWindowBelowTimeout { .. })
22106            );
22107
22108            assert_eq!(
22109                predicate, gate_ok,
22110                "predicate must agree with validate arm on pair \
22111                 (timeout={timeout:?}, window={window:?})"
22112            );
22113        }
22114    }
22115
22116    #[test]
22117    fn rejects_rate_limit_starves_circuit_breaker() {
22118        // The fail-before-pass-after pin on the cross-axis
22119        // `(:rate-limit, :circuit-breaker)` invariant. Each axis is
22120        // individually well-formed under its own per-axis bracket
22121        // (both above the zero floor, both below the cap, rate-limit
22122        // window canonical), but the pair is a structurally-inert
22123        // breaker: the token bucket admits `1 × 10s / 3600s` ≈ 0
22124        // calls per rolling breaker window, so no window can
22125        // accumulate five failures however catastrophic the upstream
22126        // failure rate.
22127        //
22128        // Envoy's `outlier_detection.consecutive_5xx` paired against
22129        // `local_rate_limit.token_bucket.max_tokens` /
22130        // `fill_interval` carries the identical relation; every
22131        // production playbook that pairs the two axes (Envoy, Istio,
22132        // AWS App Mesh, Kong) sizes the rate at or above the
22133        // breaker's minimum-request-volume threshold for exactly this
22134        // reason.
22135        //
22136        // Pin both the diagnostic arm and the payload values so a
22137        // future re-shape of the arm surfaces here as a deliberate
22138        // test edit. Clears `:timeout` so the sibling
22139        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] gate
22140        // does not fire first on the ordering-precedent it holds
22141        // over this arm.
22142        let mut s = three_member_spec();
22143        s.politicas.timeout = None;
22144        s.politicas.circuit_breaker = Some(CircuitBreaker {
22145            max_failures: 5,
22146            window: Duration::from_secs(10),
22147        });
22148        s.politicas.rate_limit = Some(RateLimit {
22149            rate: 1,
22150            window: Duration::from_secs(3600),
22151        });
22152        assert_eq!(
22153            s.validate().unwrap_err(),
22154            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
22155                rate: 1,
22156                rl_window: Duration::from_secs(3600),
22157                max_failures: 5,
22158                cb_window: Duration::from_secs(10),
22159            }
22160        );
22161    }
22162
22163    #[test]
22164    fn accepts_rate_limit_can_trip_circuit_breaker() {
22165        // Positive-control sweep across the production-playbook band
22166        // — every pair a real playbook recommends where the rate
22167        // clearly admits enough calls per breaker window to reach
22168        // `:max-failures` must validate. Envoy default 5 failures
22169        // in 10s with 100/s (1000 calls / window, 200× the threshold),
22170        // Istio 5 in 30s with 50/s (1500 calls, 300×), Hystrix 20 in
22171        // 10s with 1000/s (10000 calls, 500×), AWS App Mesh 5 in
22172        // 300s with 10/s (3000 calls, 600×). Clears `:timeout` so
22173        // the sibling cross-axis arm is vacuous on this sweep.
22174        for (rate, rl_window, max_failures, cb_window) in [
22175            (
22176                100u32,
22177                Duration::from_secs(1),
22178                5u32,
22179                Duration::from_secs(10),
22180            ),
22181            (50, Duration::from_secs(1), 5, Duration::from_secs(30)),
22182            (1000, Duration::from_secs(1), 20, Duration::from_secs(10)),
22183            (10, Duration::from_secs(1), 5, Duration::from_secs(300)),
22184            (5000, Duration::from_secs(60), 50, Duration::from_secs(60)),
22185        ] {
22186            let mut s = three_member_spec();
22187            s.politicas.timeout = None;
22188            s.politicas.circuit_breaker = Some(CircuitBreaker {
22189                max_failures,
22190                window: cb_window,
22191            });
22192            s.politicas.rate_limit = Some(RateLimit {
22193                rate,
22194                window: rl_window,
22195            });
22196            s.validate().unwrap_or_else(|e| {
22197                panic!(
22198                    "production-playbook pair rate={rate}/{rl_window:?} \
22199                     max_failures={max_failures}/{cb_window:?} must validate; got {e:?}"
22200                )
22201            });
22202        }
22203    }
22204
22205    #[test]
22206    fn accepts_rate_limit_exactly_at_trip_threshold_per_cb_window() {
22207        // Boundary pin: `rate × cb_window == max_failures × rl_window`
22208        // is the smallest bucket capacity that structurally admits
22209        // exactly `max_failures` calls per rolling breaker window
22210        // (the invariant is `≥`, not strict inequality). Catches a
22211        // future off-by-one tightening to strict inequality that
22212        // would drift the accept set away from the codified
22213        // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicate.
22214        // 5 calls/s over a 1s breaker window == 5 max_failures.
22215        let mut s = three_member_spec();
22216        s.politicas.timeout = None;
22217        s.politicas.circuit_breaker = Some(CircuitBreaker {
22218            max_failures: 5,
22219            window: Duration::from_secs(1),
22220        });
22221        s.politicas.rate_limit = Some(RateLimit {
22222            rate: 5,
22223            window: Duration::from_secs(1),
22224        });
22225        s.validate()
22226            .expect("rate × cb_window == max_failures × rl_window is the boundary accept case");
22227    }
22228
22229    #[test]
22230    fn rejects_rate_limit_one_call_short_per_cb_window() {
22231        // Off-by-one boundary pin: exactly one call short of the trip
22232        // threshold per breaker window is still structurally inert
22233        // (the invariant is `≥`, so `<` refuses even a one-call
22234        // shortfall). 4 calls/s over a 1s window == 4 admissible
22235        // failures, one shy of the 5-`max_failures` threshold.
22236        // Catches a future strict-inequality relaxation that would
22237        // silently drift the accept boundary.
22238        let mut s = three_member_spec();
22239        s.politicas.timeout = None;
22240        s.politicas.circuit_breaker = Some(CircuitBreaker {
22241            max_failures: 5,
22242            window: Duration::from_secs(1),
22243        });
22244        s.politicas.rate_limit = Some(RateLimit {
22245            rate: 4,
22246            window: Duration::from_secs(1),
22247        });
22248        assert_eq!(
22249            s.validate().unwrap_err(),
22250            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
22251                rate: 4,
22252                rl_window: Duration::from_secs(1),
22253                max_failures: 5,
22254                cb_window: Duration::from_secs(1),
22255            }
22256        );
22257    }
22258
22259    #[test]
22260    fn cross_axis_starve_gate_vacuous_when_rate_limit_absent() {
22261        // The predicate is vacuously `true` when `:rate-limit` is
22262        // None — a `:circuit-breaker` alone declares no relation to
22263        // a substrate-imposed call rate (the failure signal reaches
22264        // the breaker from the transport's own error surface, at
22265        // whatever rate upstream callers push traffic). Pin so a
22266        // future tightening that made the gate opinionated on
22267        // half-declared pairs surfaces here.
22268        let mut s = three_member_spec();
22269        s.politicas.timeout = None;
22270        s.politicas.circuit_breaker = Some(CircuitBreaker {
22271            max_failures: 1000,
22272            window: Duration::from_millis(1),
22273        });
22274        s.politicas.rate_limit = None;
22275        s.validate().expect(
22276            "cross-axis starve gate must be vacuous when :rate-limit is None, \
22277             however high :max-failures and however small :window are",
22278        );
22279    }
22280
22281    #[test]
22282    fn cross_axis_starve_gate_vacuous_when_circuit_breaker_absent() {
22283        // Peer of the sibling `:rate-limit`-absent case: a
22284        // `:rate-limit` without a `:circuit-breaker` declares a
22285        // per-edge token-bucket rate without any failure counter to
22286        // starve, so the pair is undeclared and the cross-axis gate
22287        // has nothing to check.
22288        //
22289        // Also clears the fixture's `:retries` (which is `Some(3)`) so
22290        // the sibling cross-axis
22291        // [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] arm
22292        // (which reasons across the paired `(:retries, :rate-limit)`
22293        // pair independent of `:circuit-breaker`) is vacuous on this
22294        // pin — this test names the *starve* arm's vacuity on the
22295        // `:circuit-breaker`-absent case, not the burst arm's.
22296        let mut s = three_member_spec();
22297        s.politicas.timeout = None;
22298        s.politicas.retries = None;
22299        s.politicas.circuit_breaker = None;
22300        s.politicas.rate_limit = Some(RateLimit {
22301            rate: 1,
22302            window: Duration::from_secs(3600),
22303        });
22304        s.validate().expect(
22305            "cross-axis starve gate must be vacuous when :circuit-breaker is None, \
22306             however low :rate is",
22307        );
22308    }
22309
22310    #[test]
22311    fn cross_axis_starve_gate_runs_after_per_axis_brackets() {
22312        // Ordering pin: a pair whose rate is *both* zero-floor-
22313        // violating and structurally below the trip threshold must
22314        // surface the per-axis zero-floor arm first — the zero-floor
22315        // diagnostic is more self-locating (its omit-axis remediation
22316        // is directly named), where the cross-axis arm would send the
22317        // author to reconcile four values one of which is not a
22318        // meaningful rate at all. Same ordering discipline every
22319        // per-axis bracket carries internally (zero-floor before
22320        // canonical-form before cap), and the sibling cross-axis
22321        // `PolicyBreakerZeroWindow`-before-`PolicyBreakerWindowBelowTimeout`
22322        // ordering pins on the `(:timeout, :window)` pair.
22323        let mut s = three_member_spec();
22324        s.politicas.timeout = None;
22325        s.politicas.circuit_breaker = Some(CircuitBreaker {
22326            max_failures: 5,
22327            window: Duration::from_secs(10),
22328        });
22329        s.politicas.rate_limit = Some(RateLimit {
22330            rate: 0,
22331            window: Duration::from_secs(1),
22332        });
22333        assert_eq!(
22334            s.validate().unwrap_err(),
22335            AplicacaoError::PolicyRateLimitZero,
22336            "per-axis rate zero-floor arm must fire before the cross-axis starve gate"
22337        );
22338    }
22339
22340    #[test]
22341    fn cross_axis_starve_gate_runs_after_sibling_window_below_timeout_gate() {
22342        // Cross-axis ordering pin: a `:politicas` whose axes trip
22343        // BOTH cross-axis arms — `:window < :timeout` (the sibling
22344        // `PolicyBreakerWindowBelowTimeout` invariant) AND
22345        // `:rate-limit` starves the breaker within `:window` (this
22346        // arm) — must surface the timeout-relation diagnostic first.
22347        // The timeout arm is the per-call-deadline invariant every
22348        // synchronous edge carries whether or not `:rate-limit` is
22349        // declared, so its diagnostic is more self-locating; the
22350        // starve arm needs the reader to reason across three axes,
22351        // where the timeout arm names only two.
22352        //
22353        // A `{ timeout: 30s, window: 10s, rate: 1/h, max_failures: 5 }`
22354        // pair trips both: the window is below the timeout, and the
22355        // rate (1 call/hour) admits far fewer than 5 calls per 10s
22356        // breaker window.
22357        let mut s = three_member_spec();
22358        s.politicas.timeout = Some(Duration::from_secs(30));
22359        s.politicas.circuit_breaker = Some(CircuitBreaker {
22360            max_failures: 5,
22361            window: Duration::from_secs(10),
22362        });
22363        s.politicas.rate_limit = Some(RateLimit {
22364            rate: 1,
22365            window: Duration::from_secs(3600),
22366        });
22367        assert_eq!(
22368            s.validate().unwrap_err(),
22369            AplicacaoError::PolicyBreakerWindowBelowTimeout {
22370                window: Duration::from_secs(10),
22371                timeout: Duration::from_secs(30),
22372            },
22373            "sibling :window<:timeout cross-axis arm must fire before the \
22374             starve arm when both apply"
22375        );
22376    }
22377
22378    #[test]
22379    fn breaker_can_trip_under_rate_limit_predicate_matches_gate_semantic() {
22380        // Equivalence pin: the substrate-canonical
22381        // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicate
22382        // and the [`AplicacaoSpec::validate_politicas`] cross-axis
22383        // arm must discriminate the same set on every pair covered
22384        // by their shared invariant. A future refactor of either
22385        // side that breaks the equivalence trips here rather than as
22386        // a divergence between the predicate's Boolean answer and
22387        // the validate gate's Ok/Err arm — the same
22388        // predicate-vs-gate coherence discipline the sibling
22389        // [`MeshPolicy::breaker_window_observes_timeout`] predicate
22390        // carries against `AplicacaoSpec::validate_politicas`. The
22391        // sweep covers both arms of the invariant (strictly below,
22392        // exactly at, strictly above) and both vacuous arms (None
22393        // `:rate-limit`, None `:circuit-breaker`), so the
22394        // equivalence holds exhaustively over the axis-covered
22395        // accept and reject sets. Clears `:timeout` throughout so
22396        // the sibling `:window<:timeout` gate is vacuous on every
22397        // input.
22398        let rl = |rate: u32, secs: u64| {
22399            Some(RateLimit {
22400                rate,
22401                window: Duration::from_secs(secs),
22402            })
22403        };
22404        let cb = |max_failures: u32, secs: u64| {
22405            Some(CircuitBreaker {
22406                max_failures,
22407                window: Duration::from_secs(secs),
22408            })
22409        };
22410        let cases: &[(Option<RateLimit>, Option<CircuitBreaker>)] = &[
22411            // starving pairs (predicate = false, gate = Err)
22412            (rl(1, 3600), cb(5, 10)),
22413            (rl(4, 1), cb(5, 1)),
22414            // boundary + coherent pairs (predicate = true, gate = Ok)
22415            (rl(5, 1), cb(5, 1)),
22416            (rl(100, 1), cb(5, 10)),
22417            // vacuous arms
22418            (None, cb(5, 10)),
22419            (rl(1, 3600), None),
22420            (None, None),
22421        ];
22422        for (rate_limit, circuit_breaker) in cases.iter().copied() {
22423            let politicas = MeshPolicy {
22424                circuit_breaker,
22425                rate_limit,
22426                ..Default::default()
22427            };
22428            let predicate = politicas.breaker_can_trip_under_rate_limit();
22429
22430            let mut s = three_member_spec();
22431            s.politicas = politicas.clone();
22432            s.politicas.timeout = None;
22433            let gate_ok = !matches!(
22434                s.validate(),
22435                Err(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit { .. })
22436            );
22437
22438            assert_eq!(
22439                predicate, gate_ok,
22440                "predicate must agree with validate arm on pair \
22441                 (rate_limit={rate_limit:?}, circuit_breaker={circuit_breaker:?})"
22442            );
22443        }
22444    }
22445
22446    #[test]
22447    fn rejects_retries_saturate_breaker_trip_threshold() {
22448        // The fail-before-pass-after pin on the cross-axis
22449        // `(:retries, :circuit-breaker :max-failures)` invariant. Each
22450        // axis is individually well-formed under its own per-axis
22451        // bracket (both above the zero floor, both below the cap), but
22452        // the pair is a structurally-truncated retry policy: one
22453        // client's `retries + 1 = 4` failing attempts hit the trip
22454        // threshold on the third attempt, the breaker opens, and the
22455        // fourth attempt (the last declared retry) is blocked by the
22456        // open breaker — the substrate declared four attempts and
22457        // structurally allows three.
22458        //
22459        // Envoy's `retry_policy.num_retries` paired against
22460        // `outlier_detection.consecutive_5xx` carries the identical
22461        // relation; every production playbook that pairs the two axes
22462        // (Envoy, Istio, resilience4j, Hystrix) sizes the breaker's
22463        // trip threshold strictly above any single client's retry
22464        // budget so the breaker distinguishes one persistently-failing
22465        // client from sustained multi-client failure.
22466        //
22467        // Pin both the diagnostic arm and the payload values so a
22468        // future re-shape of the arm surfaces here as a deliberate
22469        // test edit. Clears `:timeout` and `:rate-limit` so the
22470        // sibling cross-axis
22471        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] /
22472        // [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`]
22473        // arms do not fire first on the ordering-precedent they hold
22474        // over this arm.
22475        let mut s = three_member_spec();
22476        s.politicas.timeout = None;
22477        s.politicas.retries = Some(3);
22478        s.politicas.circuit_breaker = Some(CircuitBreaker {
22479            max_failures: 3,
22480            window: Duration::from_secs(1),
22481        });
22482        s.politicas.rate_limit = None;
22483        assert_eq!(
22484            s.validate().unwrap_err(),
22485            AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
22486                retries: 3,
22487                max_failures: 3,
22488            }
22489        );
22490    }
22491
22492    #[test]
22493    fn accepts_retries_below_breaker_trip_threshold() {
22494        // Positive-control sweep across the production-playbook band
22495        // — every pair a real playbook recommends where the breaker's
22496        // trip threshold is strictly above the client's retry budget
22497        // must validate. Envoy default `num_retries: 3` with
22498        // `consecutive_5xx: 5` (breaker admits one client's 4 attempts,
22499        // opens on multi-client failures beyond that); Istio
22500        // `attempts: 3` with `consecutive5xxErrors: 5`; Hystrix
22501        // `execution.isolation.thread.timeoutInMilliseconds` + 3
22502        // retries with `requestVolumeThreshold: 20`; AWS App Mesh
22503        // `maxRetries: 5` with a `maxEjectionPercent`-derived threshold
22504        // of 10; resilience4j 2 retries with `slidingWindowSize: 10`.
22505        // Clears `:timeout` and `:rate-limit` so the sibling cross-axis
22506        // arms are vacuous on this sweep.
22507        for (retries, max_failures) in [(1u32, 5u32), (3, 5), (3, 20), (5, 10), (2, 10), (10, 1000)]
22508        {
22509            let mut s = three_member_spec();
22510            s.politicas.timeout = None;
22511            s.politicas.retries = Some(retries);
22512            s.politicas.circuit_breaker = Some(CircuitBreaker {
22513                max_failures,
22514                window: Duration::from_secs(60),
22515            });
22516            s.politicas.rate_limit = None;
22517            s.validate().unwrap_or_else(|e| {
22518                panic!(
22519                    "production-playbook pair retries={retries} \
22520                     max_failures={max_failures} must validate; got {e:?}"
22521                )
22522            });
22523        }
22524    }
22525
22526    #[test]
22527    fn accepts_retries_exactly_at_boundary_below_trip_threshold() {
22528        // Boundary pin: `max_failures == retries + 1` is the smallest
22529        // trip threshold that admits one client's exhausted retries
22530        // through completion (the R+1th failure — the last declared
22531        // retry — trips the breaker exactly as it completes, so
22532        // retries fully executed). The invariant is `>`, not `>=`,
22533        // stated in the coherent direction `max_failures > retries`.
22534        // Catches a future off-by-one tightening to
22535        // `max_failures > retries + 1` that would drift the accept set
22536        // away from the codified
22537        // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]
22538        // predicate.
22539        let mut s = three_member_spec();
22540        s.politicas.timeout = None;
22541        s.politicas.retries = Some(3);
22542        s.politicas.circuit_breaker = Some(CircuitBreaker {
22543            max_failures: 4,
22544            window: Duration::from_secs(60),
22545        });
22546        s.politicas.rate_limit = None;
22547        s.validate()
22548            .expect("max_failures == retries + 1 is the boundary accept case");
22549    }
22550
22551    #[test]
22552    fn rejects_retries_equal_to_breaker_trip_threshold() {
22553        // Off-by-one boundary pin: exactly at the trip threshold is
22554        // still structurally truncating (the invariant is `>`, so `<=`
22555        // refuses even the tight boundary). `retries = 3` with
22556        // `max_failures = 3` means the breaker trips on the third
22557        // failure — the last declared retry attempt is blocked.
22558        // Catches a future relaxation to `>=` that would silently
22559        // drift the accept boundary.
22560        let mut s = three_member_spec();
22561        s.politicas.timeout = None;
22562        s.politicas.retries = Some(3);
22563        s.politicas.circuit_breaker = Some(CircuitBreaker {
22564            max_failures: 3,
22565            window: Duration::from_secs(60),
22566        });
22567        s.politicas.rate_limit = None;
22568        assert_eq!(
22569            s.validate().unwrap_err(),
22570            AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
22571                retries: 3,
22572                max_failures: 3,
22573            }
22574        );
22575    }
22576
22577    #[test]
22578    fn cross_axis_retries_gate_vacuous_when_retries_absent() {
22579        // The predicate is vacuously `true` when `:retries` is None —
22580        // a `:circuit-breaker` alone declares a failure counter whose
22581        // per-client attempt count is unconstrained by the substrate,
22582        // so no per-client saturation bound on failures-per-client-call
22583        // is knowable at author time. The substrate takes no position
22584        // on whether an omitted `:retries` axis means zero retries or
22585        // "the client picks its own retry policy" — either way, the
22586        // pair is undeclared and the cross-axis gate has nothing to
22587        // check. Pin so a future tightening that made the gate
22588        // opinionated on half-declared pairs surfaces here.
22589        let mut s = three_member_spec();
22590        s.politicas.timeout = None;
22591        s.politicas.retries = None;
22592        s.politicas.circuit_breaker = Some(CircuitBreaker {
22593            max_failures: 1,
22594            window: Duration::from_secs(60),
22595        });
22596        s.politicas.rate_limit = None;
22597        s.validate().expect(
22598            "cross-axis retries gate must be vacuous when :retries is None, \
22599             however low :max-failures is",
22600        );
22601    }
22602
22603    #[test]
22604    fn cross_axis_retries_gate_vacuous_when_circuit_breaker_absent() {
22605        // Peer of the sibling `:retries`-absent case: a `:retries`
22606        // without a `:circuit-breaker` declares a client-retry policy
22607        // with no failure counter to trip, so the pair is undeclared
22608        // and the cross-axis gate has nothing to check.
22609        let mut s = three_member_spec();
22610        s.politicas.timeout = None;
22611        s.politicas.retries = Some(POLICY_RETRIES_MAX);
22612        s.politicas.circuit_breaker = None;
22613        s.politicas.rate_limit = None;
22614        s.validate().expect(
22615            "cross-axis retries gate must be vacuous when :circuit-breaker is None, \
22616             however high :retries is",
22617        );
22618    }
22619
22620    #[test]
22621    fn cross_axis_retries_gate_runs_after_per_axis_brackets() {
22622        // Ordering pin: a pair whose retries is *both* zero-floor-
22623        // violating and structurally at-or-below the trip threshold
22624        // must surface the per-axis zero-floor arm first — the
22625        // zero-floor diagnostic is more self-locating (its omit-axis
22626        // remediation is directly named), where the cross-axis arm
22627        // would send the author to reconcile two values one of which
22628        // is not a meaningful retry count at all. Same ordering
22629        // discipline every per-axis bracket carries internally
22630        // (zero-floor before canonical-form before cap), and the
22631        // sibling cross-axis
22632        // `PolicyRateLimitZero`-before-`PolicyBreakerCannotTripUnderRateLimit`
22633        // ordering pins on the `(:rate-limit, :circuit-breaker)` pair.
22634        let mut s = three_member_spec();
22635        s.politicas.timeout = None;
22636        s.politicas.retries = Some(0);
22637        s.politicas.circuit_breaker = Some(CircuitBreaker {
22638            max_failures: 3,
22639            window: Duration::from_secs(60),
22640        });
22641        s.politicas.rate_limit = None;
22642        assert_eq!(
22643            s.validate().unwrap_err(),
22644            AplicacaoError::PolicyRetriesZero,
22645            "per-axis retries zero-floor arm must fire before the cross-axis retries gate"
22646        );
22647    }
22648
22649    #[test]
22650    fn cross_axis_retries_gate_runs_after_sibling_starve_gate() {
22651        // Cross-axis ordering pin: a `:politicas` whose axes trip
22652        // BOTH cross-axis arms — `:rate-limit` starves the breaker
22653        // within `:window` (the sibling
22654        // `PolicyBreakerCannotTripUnderRateLimit` invariant) AND
22655        // `:retries + 1` saturates `:max-failures` (this arm) — must
22656        // surface the rate-limit-starve diagnostic first. The
22657        // rate-limit-starve arm reasons across the token-bucket
22658        // admission axis every rate-limited edge carries whether or
22659        // not `:retries` is declared, so its diagnostic is more
22660        // self-locating; the retries-saturate arm reasons across a
22661        // per-client retry-policy budget the starve arm does not
22662        // touch.
22663        //
22664        // A `{ retries: 5, rate: 1/h, max_failures: 5, cb_window: 10s }`
22665        // pair trips both: the rate structurally cannot deliver 5
22666        // failures per 10s breaker window, and simultaneously
22667        // one client's `retries + 1 = 6` attempts alone would
22668        // saturate the 5-`max_failures` threshold.
22669        let mut s = three_member_spec();
22670        s.politicas.timeout = None;
22671        s.politicas.retries = Some(5);
22672        s.politicas.circuit_breaker = Some(CircuitBreaker {
22673            max_failures: 5,
22674            window: Duration::from_secs(10),
22675        });
22676        s.politicas.rate_limit = Some(RateLimit {
22677            rate: 1,
22678            window: Duration::from_secs(3600),
22679        });
22680        assert_eq!(
22681            s.validate().unwrap_err(),
22682            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
22683                rate: 1,
22684                rl_window: Duration::from_secs(3600),
22685                max_failures: 5,
22686                cb_window: Duration::from_secs(10),
22687            },
22688            "sibling :rate-limit-starve cross-axis arm must fire before the \
22689             retries-saturate arm when both apply"
22690        );
22691    }
22692
22693    #[test]
22694    fn retries_fit_under_breaker_trip_threshold_predicate_matches_gate_semantic() {
22695        // Equivalence pin: the substrate-canonical
22696        // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]
22697        // predicate and the [`AplicacaoSpec::validate_politicas`]
22698        // cross-axis arm must discriminate the same set on every pair
22699        // covered by their shared invariant. A future refactor of
22700        // either side that breaks the equivalence trips here rather
22701        // than as a divergence between the predicate's Boolean answer
22702        // and the validate gate's Ok/Err arm — the same
22703        // predicate-vs-gate coherence discipline the sibling
22704        // [`MeshPolicy::breaker_window_observes_timeout`] and
22705        // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
22706        // carry against `AplicacaoSpec::validate_politicas`. The
22707        // sweep covers both arms of the invariant (strictly below,
22708        // exactly at the boundary, strictly above) and both vacuous
22709        // arms (None `:retries`, None `:circuit-breaker`), so the
22710        // equivalence holds exhaustively over the axis-covered accept
22711        // and reject sets. Clears `:timeout` and `:rate-limit`
22712        // throughout so the sibling cross-axis arms are vacuous on
22713        // every input.
22714        let cb = |max_failures: u32| {
22715            Some(CircuitBreaker {
22716                max_failures,
22717                window: Duration::from_secs(60),
22718            })
22719        };
22720        let cases: &[(Option<u32>, Option<CircuitBreaker>)] = &[
22721            // saturating pairs (predicate = false, gate = Err)
22722            (Some(3), cb(3)),
22723            (Some(3), cb(1)),
22724            (Some(10), cb(5)),
22725            // boundary + coherent pairs (predicate = true, gate = Ok)
22726            (Some(3), cb(4)),
22727            (Some(1), cb(5)),
22728            (Some(3), cb(20)),
22729            // vacuous arms
22730            (None, cb(1)),
22731            (Some(10), None),
22732            (None, None),
22733        ];
22734        for (retries, circuit_breaker) in cases.iter().copied() {
22735            let politicas = MeshPolicy {
22736                retries,
22737                circuit_breaker,
22738                ..Default::default()
22739            };
22740            let predicate = politicas.retries_fit_under_breaker_trip_threshold();
22741
22742            let mut s = three_member_spec();
22743            s.politicas = politicas.clone();
22744            let gate_ok = !matches!(
22745                s.validate(),
22746                Err(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted { .. })
22747            );
22748
22749            assert_eq!(
22750                predicate, gate_ok,
22751                "predicate must agree with validate arm on pair \
22752                 (retries={retries:?}, circuit_breaker={circuit_breaker:?})"
22753            );
22754        }
22755    }
22756
22757    #[test]
22758    fn rejects_rate_limit_cannot_admit_retry_burst() {
22759        // The fail-before-pass-after pin on the cross-axis
22760        // `(:retries, :rate-limit)` invariant. Each axis is
22761        // individually well-formed under its own per-axis bracket (both
22762        // above the zero floor, both below the cap), but the pair is a
22763        // structurally-truncated retry policy: one client's
22764        // `retries + 1 = 6` failing attempts consume 6 tokens from a
22765        // bucket that admits at most 3 per refill window, so the fourth
22766        // attempt onward is 429ed by the local rate limiter and the
22767        // declared retry policy is silently truncated by the same rate
22768        // limiter it feeds through — the substrate declared six
22769        // attempts and structurally allows three.
22770        //
22771        // Envoy's `local_rate_limit.token_bucket.max_tokens` paired
22772        // against `retry_policy.num_retries` carries the identical
22773        // relation; every production playbook that pairs the two axes
22774        // (Envoy, Istio, resilience4j, AWS App Mesh) sizes the bucket
22775        // capacity strictly above any single client's retry budget so
22776        // the limiter distinguishes one client's declared retries from
22777        // sustained multi-client load.
22778        //
22779        // Pin both the diagnostic arm and the payload values so a
22780        // future re-shape of the arm surfaces here as a deliberate
22781        // test edit. Clears `:timeout` and `:circuit-breaker` so the
22782        // sibling cross-axis
22783        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] /
22784        // [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`] /
22785        // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
22786        // arms do not fire first on the ordering-precedent they hold
22787        // over this arm.
22788        let mut s = three_member_spec();
22789        s.politicas.timeout = None;
22790        s.politicas.retries = Some(5);
22791        s.politicas.circuit_breaker = None;
22792        s.politicas.rate_limit = Some(RateLimit {
22793            rate: 3,
22794            window: Duration::from_secs(1),
22795        });
22796        assert_eq!(
22797            s.validate().unwrap_err(),
22798            AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
22799                retries: 5,
22800                rate: 3,
22801            }
22802        );
22803    }
22804
22805    #[test]
22806    fn accepts_rate_limit_admits_retry_burst() {
22807        // Positive-control sweep across the production-playbook band
22808        // — every pair a real playbook recommends where the bucket
22809        // capacity is strictly above the client's retry budget must
22810        // validate. Envoy default `num_retries: 3` with 100/s (100
22811        // tokens per window admits 4 attempts per client with 96 to
22812        // spare); Istio `attempts: 3` with 50/s (50 admits 4);
22813        // resilience4j 2 retries with 10/s (10 admits 3); AWS App
22814        // Mesh `maxRetries: 5` with 1000/s (1000 admits 6); Cloudflare
22815        // Enterprise 3 retries with 1_000_000/h (1M admits 4). Clears
22816        // `:timeout` and `:circuit-breaker` so the sibling cross-axis
22817        // arms are vacuous on this sweep.
22818        for (retries, rate, secs) in [
22819            (3u32, 100u32, 1u64),
22820            (3, 50, 1),
22821            (2, 10, 1),
22822            (5, 1000, 1),
22823            (3, 1_000_000, 3600),
22824            (10, POLICY_RATE_LIMIT_MAX, 1),
22825        ] {
22826            let mut s = three_member_spec();
22827            s.politicas.timeout = None;
22828            s.politicas.retries = Some(retries);
22829            s.politicas.circuit_breaker = None;
22830            s.politicas.rate_limit = Some(RateLimit {
22831                rate,
22832                window: Duration::from_secs(secs),
22833            });
22834            s.validate().unwrap_or_else(|e| {
22835                panic!(
22836                    "production-playbook pair retries={retries} rate={rate}/{secs}s \
22837                     must validate; got {e:?}"
22838                )
22839            });
22840        }
22841    }
22842
22843    #[test]
22844    fn accepts_rate_exactly_at_boundary_admits_retry_burst() {
22845        // Boundary pin: `rate == retries + 1` is the smallest bucket
22846        // capacity that structurally admits one client's exhausted
22847        // retries through completion (each attempt draws exactly one
22848        // token; `retries + 1` tokens available admits `retries + 1`
22849        // attempts, retries fully executed). The invariant is `>=`,
22850        // stated in the coherent direction `rate >= retries + 1`.
22851        // Catches a future off-by-one tightening to `rate > retries + 1`
22852        // that would drift the accept set away from the codified
22853        // [`MeshPolicy::rate_limit_admits_retry_burst`] predicate.
22854        let mut s = three_member_spec();
22855        s.politicas.timeout = None;
22856        s.politicas.retries = Some(3);
22857        s.politicas.circuit_breaker = None;
22858        s.politicas.rate_limit = Some(RateLimit {
22859            rate: 4,
22860            window: Duration::from_secs(1),
22861        });
22862        s.validate()
22863            .expect("rate == retries + 1 is the boundary accept case");
22864    }
22865
22866    #[test]
22867    fn rejects_rate_one_below_retry_burst() {
22868        // Off-by-one boundary pin: exactly one token short of the
22869        // retry burst is still structurally truncating (the invariant
22870        // is `>=`, so `<` refuses even a one-token shortfall).
22871        // `retries = 3` with `rate = 3` means one client's four
22872        // attempts consume four tokens from a three-token bucket —
22873        // the fourth attempt is 429ed. Catches a future relaxation to
22874        // `>` on the wrong side (`rate > retries`, accepting equal)
22875        // that would silently drift the accept boundary and admit a
22876        // structurally-truncated retry policy at the emit boundary.
22877        let mut s = three_member_spec();
22878        s.politicas.timeout = None;
22879        s.politicas.retries = Some(3);
22880        s.politicas.circuit_breaker = None;
22881        s.politicas.rate_limit = Some(RateLimit {
22882            rate: 3,
22883            window: Duration::from_secs(1),
22884        });
22885        assert_eq!(
22886            s.validate().unwrap_err(),
22887            AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
22888                retries: 3,
22889                rate: 3,
22890            }
22891        );
22892    }
22893
22894    #[test]
22895    fn cross_axis_burst_gate_vacuous_when_retries_absent() {
22896        // The predicate is vacuously `true` when `:retries` is None —
22897        // a `:rate-limit` alone declares a token-bucket rate whose
22898        // per-client attempt count is unconstrained by the substrate,
22899        // so no per-client saturation bound on tokens-per-client-call
22900        // is knowable at author time. The substrate takes no position
22901        // on whether an omitted `:retries` axis means zero retries or
22902        // "the client picks its own retry policy" — either way, the
22903        // pair is undeclared and the cross-axis gate has nothing to
22904        // check. Pin so a future tightening that made the gate
22905        // opinionated on half-declared pairs surfaces here.
22906        let mut s = three_member_spec();
22907        s.politicas.timeout = None;
22908        s.politicas.retries = None;
22909        s.politicas.circuit_breaker = None;
22910        s.politicas.rate_limit = Some(RateLimit {
22911            rate: 1,
22912            window: Duration::from_secs(1),
22913        });
22914        s.validate().expect(
22915            "cross-axis burst gate must be vacuous when :retries is None, \
22916             however low :rate is",
22917        );
22918    }
22919
22920    #[test]
22921    fn cross_axis_burst_gate_vacuous_when_rate_limit_absent() {
22922        // Peer of the sibling `:retries`-absent case: a `:retries`
22923        // without a `:rate-limit` declares a client-retry policy with
22924        // no rate limiter to saturate, so the pair is undeclared and
22925        // the cross-axis gate has nothing to check. Uses
22926        // [`POLICY_RETRIES_MAX`] to pin the vacuity across the widest
22927        // authored retry budget the per-axis cap admits — a `:retries
22928        // POLICY_RETRIES_MAX` alone must remain a clean pass whether
22929        // or not `:rate-limit` is declared.
22930        let mut s = three_member_spec();
22931        s.politicas.timeout = None;
22932        s.politicas.retries = Some(POLICY_RETRIES_MAX);
22933        s.politicas.circuit_breaker = None;
22934        s.politicas.rate_limit = None;
22935        s.validate().expect(
22936            "cross-axis burst gate must be vacuous when :rate-limit is None, \
22937             however high :retries is",
22938        );
22939    }
22940
22941    #[test]
22942    fn cross_axis_burst_gate_runs_after_per_axis_brackets() {
22943        // Ordering pin: a pair whose retries is *both* zero-floor-
22944        // violating and structurally below the retry-burst threshold
22945        // must surface the per-axis zero-floor arm first — the
22946        // zero-floor diagnostic is more self-locating (its omit-axis
22947        // remediation is directly named), where the cross-axis arm
22948        // would send the author to reconcile two values one of which
22949        // is not a meaningful retry count at all. Same ordering
22950        // discipline every per-axis bracket carries internally
22951        // (zero-floor before canonical-form before cap), and the
22952        // sibling cross-axis
22953        // `PolicyRetriesZero`-before-`PolicyBreakerTripsBeforeRetriesExhausted`
22954        // ordering pin on the `(:retries, :max-failures)` pair.
22955        let mut s = three_member_spec();
22956        s.politicas.timeout = None;
22957        s.politicas.retries = Some(0);
22958        s.politicas.circuit_breaker = None;
22959        s.politicas.rate_limit = Some(RateLimit {
22960            rate: 1,
22961            window: Duration::from_secs(1),
22962        });
22963        assert_eq!(
22964            s.validate().unwrap_err(),
22965            AplicacaoError::PolicyRetriesZero,
22966            "per-axis retries zero-floor arm must fire before the cross-axis burst gate"
22967        );
22968    }
22969
22970    #[test]
22971    fn cross_axis_burst_gate_runs_after_sibling_starve_gate() {
22972        // Cross-axis ordering pin: a `:politicas` whose axes trip
22973        // BOTH cross-axis arms — `:rate-limit` starves the breaker
22974        // within `:window` (the sibling
22975        // `PolicyBreakerCannotTripUnderRateLimit` invariant) AND
22976        // `:retries + 1` exceeds the bucket capacity (this arm) —
22977        // must surface the rate-limit-starve diagnostic first. The
22978        // starve arm is the token-bucket admission invariant every
22979        // rate-limited edge carries against the breaker whether or
22980        // not `:retries` is declared, so its diagnostic is more
22981        // self-locating; the burst arm reasons across a per-client
22982        // retry-policy budget the starve arm does not touch. Same
22983        // "more foundational cross-axis first" ordering discipline the
22984        // sibling
22985        // `PolicyBreakerCannotTripUnderRateLimit`-before-`PolicyBreakerTripsBeforeRetriesExhausted`
22986        // pin on the peer pair carries.
22987        //
22988        // A `{ retries: 5, rate: 1/h, max_failures: 5, cb_window: 10s }`
22989        // pair trips both: the rate structurally cannot deliver 5
22990        // failures per 10s breaker window (starve arm), and
22991        // simultaneously one client's `retries + 1 = 6` attempts alone
22992        // would exhaust the 1-token bucket (burst arm).
22993        let mut s = three_member_spec();
22994        s.politicas.timeout = None;
22995        s.politicas.retries = Some(5);
22996        s.politicas.circuit_breaker = Some(CircuitBreaker {
22997            max_failures: 5,
22998            window: Duration::from_secs(10),
22999        });
23000        s.politicas.rate_limit = Some(RateLimit {
23001            rate: 1,
23002            window: Duration::from_secs(3600),
23003        });
23004        assert_eq!(
23005            s.validate().unwrap_err(),
23006            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
23007                rate: 1,
23008                rl_window: Duration::from_secs(3600),
23009                max_failures: 5,
23010                cb_window: Duration::from_secs(10),
23011            },
23012            "sibling :rate-limit-starve cross-axis arm must fire before the \
23013             burst arm when both apply"
23014        );
23015    }
23016
23017    #[test]
23018    fn cross_axis_burst_gate_runs_after_sibling_retries_saturate_gate() {
23019        // Cross-axis ordering pin: a `:politicas` whose axes trip
23020        // BOTH the retries-saturate arm and this burst arm — one
23021        // client's `retries + 1` failures saturate the breaker's trip
23022        // threshold (the sibling
23023        // `PolicyBreakerTripsBeforeRetriesExhausted` invariant) AND
23024        // `retries + 1` exceeds the bucket capacity (this arm) —
23025        // must surface the retries-saturate diagnostic first. The
23026        // saturate arm is the per-client-vs-breaker relation every
23027        // retry-with-breaker pair carries whether or not `:rate-limit`
23028        // is declared, so its diagnostic is more self-locating; the
23029        // burst arm reasons across the rate-limit token-bucket
23030        // admission axis the saturate arm does not touch. Same
23031        // "more foundational cross-axis first" ordering discipline
23032        // carries here.
23033        //
23034        // A `{ retries: 5, max_failures: 3, cb_window: 60s,
23035        // rate: 3/s }` pair trips both: the breaker's `max_failures
23036        // = 3` is `<= retries = 5` (saturate arm), and simultaneously
23037        // one client's `retries + 1 = 6` attempts alone would exhaust
23038        // the 3-token bucket (burst arm). Clears `:timeout` so the
23039        // sibling `:window<:timeout` gate is vacuous, and the
23040        // `(rate=3/s, max_failures=3, cb_window=60s)` triple keeps
23041        // the starve arm coherent (`3 × 60s >= 3 × 1s`) so it is not
23042        // the arm that fires first.
23043        let mut s = three_member_spec();
23044        s.politicas.timeout = None;
23045        s.politicas.retries = Some(5);
23046        s.politicas.circuit_breaker = Some(CircuitBreaker {
23047            max_failures: 3,
23048            window: Duration::from_secs(60),
23049        });
23050        s.politicas.rate_limit = Some(RateLimit {
23051            rate: 3,
23052            window: Duration::from_secs(1),
23053        });
23054        assert_eq!(
23055            s.validate().unwrap_err(),
23056            AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
23057                retries: 5,
23058                max_failures: 3,
23059            },
23060            "sibling :retries-saturate cross-axis arm must fire before the \
23061             burst arm when both apply"
23062        );
23063    }
23064
23065    #[test]
23066    fn rate_limit_admits_retry_burst_predicate_matches_gate_semantic() {
23067        // Equivalence pin: the substrate-canonical
23068        // [`MeshPolicy::rate_limit_admits_retry_burst`] predicate and
23069        // the [`AplicacaoSpec::validate_politicas`] cross-axis arm
23070        // must discriminate the same set on every pair covered by
23071        // their shared invariant. A future refactor of either side
23072        // that breaks the equivalence trips here rather than as a
23073        // divergence between the predicate's Boolean answer and the
23074        // validate gate's Ok/Err arm — the same predicate-vs-gate
23075        // coherence discipline the three sibling cross-axis
23076        // predicates ([`MeshPolicy::breaker_window_observes_timeout`],
23077        // [`MeshPolicy::breaker_can_trip_under_rate_limit`],
23078        // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`])
23079        // carry against `AplicacaoSpec::validate_politicas`. The sweep
23080        // covers both arms of the invariant (strictly below, exactly
23081        // at the boundary, strictly above) and both vacuous arms
23082        // (None `:retries`, None `:rate-limit`), so the equivalence
23083        // holds exhaustively over the axis-covered accept and reject
23084        // sets. Clears `:timeout` and `:circuit-breaker` throughout
23085        // so the three sibling cross-axis arms are vacuous on every
23086        // input.
23087        let rl = |rate: u32, secs: u64| {
23088            Some(RateLimit {
23089                rate,
23090                window: Duration::from_secs(secs),
23091            })
23092        };
23093        let cases: &[(Option<u32>, Option<RateLimit>)] = &[
23094            // burst-exceeding pairs (predicate = false, gate = Err)
23095            (Some(3), rl(3, 1)),
23096            (Some(5), rl(1, 1)),
23097            (Some(10), rl(5, 1)),
23098            // boundary + coherent pairs (predicate = true, gate = Ok)
23099            (Some(3), rl(4, 1)),
23100            (Some(1), rl(5, 1)),
23101            (Some(3), rl(1_000_000, 3600)),
23102            // vacuous arms
23103            (None, rl(1, 1)),
23104            (Some(10), None),
23105            (None, None),
23106        ];
23107        for (retries, rate_limit) in cases.iter().copied() {
23108            let politicas = MeshPolicy {
23109                retries,
23110                rate_limit,
23111                ..Default::default()
23112            };
23113            let predicate = politicas.rate_limit_admits_retry_burst();
23114
23115            let mut s = three_member_spec();
23116            s.politicas = politicas.clone();
23117            let gate_ok = !matches!(
23118                s.validate(),
23119                Err(AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst { .. })
23120            );
23121
23122            assert_eq!(
23123                predicate, gate_ok,
23124                "predicate must agree with validate arm on pair \
23125                 (retries={retries:?}, rate_limit={rate_limit:?})"
23126            );
23127        }
23128    }
23129
23130    /// Sweep body shared by every `first_cross_axis_violation` ≡ gate
23131    /// equivalence pin — assert that on each `(label, politicas,
23132    /// expected)` case the substrate-canonical fold and the validate
23133    /// cascade agree byte-for-byte. Extracted so each pin's own body
23134    /// stays under `clippy::too_many_lines`.
23135    fn assert_first_cross_axis_violation_agrees_with_gate(
23136        cases: &[(&str, MeshPolicy, Option<AplicacaoError>)],
23137    ) {
23138        for (label, politicas, expected) in cases {
23139            let fold = politicas.first_cross_axis_violation();
23140            assert_eq!(
23141                fold.as_ref(),
23142                expected.as_ref(),
23143                "fold must return {expected:?} on `{label}`; got {fold:?}"
23144            );
23145
23146            let mut s = three_member_spec();
23147            s.politicas = politicas.clone();
23148            let gate = s.validate();
23149            match expected {
23150                None => {
23151                    // No cross-axis violation: validate must pass (the
23152                    // per-axis brackets pass by construction on every
23153                    // fixture above; every fixture's non-`:politicas`
23154                    // slots come from `three_member_spec`).
23155                    gate.as_ref()
23156                        .unwrap_or_else(|e| panic!("`{label}` must validate cleanly; got {e:?}"));
23157                }
23158                Some(want) => {
23159                    let got =
23160                        gate.expect_err(&format!("`{label}` must surface a cross-axis violation"));
23161                    assert_eq!(
23162                        &got, want,
23163                        "validate cross-axis cascade must return {want:?} on `{label}`; got {got:?}"
23164                    );
23165                }
23166            }
23167        }
23168    }
23169
23170    #[test]
23171    fn first_cross_axis_violation_matches_gate_on_single_arm_and_vacuous_shapes() {
23172        // Equivalence pin on the compound cross-axis fold: the
23173        // substrate-canonical [`MeshPolicy::first_cross_axis_violation`]
23174        // and the [`AplicacaoSpec::validate_politicas`] cross-axis
23175        // cascade must return identical `AplicacaoError` variants on
23176        // every axis-covered input — the "compound-fold ≡ gate"
23177        // contract that generalizes the four sibling per-arm pins
23178        // onto the compound primitive that folds all four. A future
23179        // refactor of either side that breaks the equivalence trips
23180        // here rather than as a divergence between what the substrate
23181        // primitive answers and what `feira build` accepts.
23182        //
23183        // Half-A of the sweep: every single-arm violation (one arm
23184        // fires with the three sibling arms vacuous), the vacuous
23185        // shape (empty policy — no arm fires), and the fully-coherent
23186        // shape (every axis declared inside the coherence surface —
23187        // no arm fires). Half-B (pairwise-ordering coverage — the
23188        // "which arm wins when two apply" contract) lives in the
23189        // sibling `first_cross_axis_violation_matches_gate_on_pairwise_orderings`
23190        // pin; splitting keeps each pin's body under
23191        // `clippy::too_many_lines`.
23192        let cb = |max_failures: u32, secs: u64| CircuitBreaker {
23193            max_failures,
23194            window: Duration::from_secs(secs),
23195        };
23196        let rl = |rate: u32, secs: u64| RateLimit {
23197            rate,
23198            window: Duration::from_secs(secs),
23199        };
23200        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
23201            (
23202                "window-below-timeout only",
23203                MeshPolicy {
23204                    timeout: Some(Duration::from_secs(30)),
23205                    circuit_breaker: Some(cb(5, 10)),
23206                    ..Default::default()
23207                },
23208                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
23209                    window: Duration::from_secs(10),
23210                    timeout: Duration::from_secs(30),
23211                }),
23212            ),
23213            (
23214                "starve only",
23215                MeshPolicy {
23216                    rate_limit: Some(rl(1, 3600)),
23217                    circuit_breaker: Some(cb(5, 10)),
23218                    ..Default::default()
23219                },
23220                Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
23221                    rate: 1,
23222                    rl_window: Duration::from_secs(3600),
23223                    max_failures: 5,
23224                    cb_window: Duration::from_secs(10),
23225                }),
23226            ),
23227            (
23228                "retries-saturate only",
23229                MeshPolicy {
23230                    retries: Some(3),
23231                    circuit_breaker: Some(cb(3, 60)),
23232                    ..Default::default()
23233                },
23234                Some(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
23235                    retries: 3,
23236                    max_failures: 3,
23237                }),
23238            ),
23239            (
23240                "retries-burst only",
23241                MeshPolicy {
23242                    retries: Some(5),
23243                    rate_limit: Some(rl(3, 1)),
23244                    ..Default::default()
23245                },
23246                Some(AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
23247                    retries: 5,
23248                    rate: 3,
23249                }),
23250            ),
23251            ("empty policy", MeshPolicy::default(), None),
23252            (
23253                "fully-coherent policy",
23254                MeshPolicy {
23255                    timeout: Some(Duration::from_secs(30)),
23256                    retries: Some(3),
23257                    circuit_breaker: Some(cb(5, 60)),
23258                    mtls_required: Some(true),
23259                    rate_limit: Some(rl(100, 1)),
23260                },
23261                None,
23262            ),
23263        ];
23264        assert_first_cross_axis_violation_agrees_with_gate(cases);
23265    }
23266
23267    #[test]
23268    fn first_cross_axis_violation_matches_gate_on_pairwise_orderings() {
23269        // Half-B of the compound-fold ≡ gate equivalence pin: the
23270        // load-bearing pairwise-ordering coverage. Every ordered pair
23271        // of the four cross-axis arms — six combinations — where two
23272        // arms are simultaneously eligible must surface the
23273        // more-foundational arm's diagnostic verbatim. Pins the fold's
23274        // arm-ordering byte-for-byte against the validate cascade's
23275        // arm-ordering, so a future reshuffle of either side that
23276        // silently drifts the ordering trips here rather than as a
23277        // per-arm miss the sibling per-arm `_predicate_matches_gate_semantic`
23278        // pins cannot catch (they clear every sibling arm, so their
23279        // sweeps are pairwise-ordering-agnostic by construction).
23280        //
23281        // The six pairs the four-arm cascade admits:
23282        // window-before-starve, window-before-saturate,
23283        // window-before-burst, starve-before-saturate,
23284        // starve-before-burst, saturate-before-burst.
23285        let cb = |max_failures: u32, secs: u64| CircuitBreaker {
23286            max_failures,
23287            window: Duration::from_secs(secs),
23288        };
23289        let rl = |rate: u32, secs: u64| RateLimit {
23290            rate,
23291            window: Duration::from_secs(secs),
23292        };
23293        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
23294            (
23295                "window+starve → window wins",
23296                MeshPolicy {
23297                    timeout: Some(Duration::from_secs(30)),
23298                    rate_limit: Some(rl(1, 3600)),
23299                    circuit_breaker: Some(cb(5, 10)),
23300                    ..Default::default()
23301                },
23302                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
23303                    window: Duration::from_secs(10),
23304                    timeout: Duration::from_secs(30),
23305                }),
23306            ),
23307            (
23308                "window+retries-saturate → window wins",
23309                MeshPolicy {
23310                    timeout: Some(Duration::from_secs(30)),
23311                    retries: Some(5),
23312                    circuit_breaker: Some(cb(3, 10)),
23313                    ..Default::default()
23314                },
23315                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
23316                    window: Duration::from_secs(10),
23317                    timeout: Duration::from_secs(30),
23318                }),
23319            ),
23320            (
23321                "window+retries-burst → window wins",
23322                MeshPolicy {
23323                    timeout: Some(Duration::from_secs(30)),
23324                    retries: Some(5),
23325                    rate_limit: Some(rl(3, 1)),
23326                    circuit_breaker: Some(cb(5, 10)),
23327                    ..Default::default()
23328                },
23329                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
23330                    window: Duration::from_secs(10),
23331                    timeout: Duration::from_secs(30),
23332                }),
23333            ),
23334            (
23335                "starve+retries-saturate → starve wins",
23336                MeshPolicy {
23337                    retries: Some(5),
23338                    rate_limit: Some(rl(1, 3600)),
23339                    circuit_breaker: Some(cb(5, 10)),
23340                    ..Default::default()
23341                },
23342                Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
23343                    rate: 1,
23344                    rl_window: Duration::from_secs(3600),
23345                    max_failures: 5,
23346                    cb_window: Duration::from_secs(10),
23347                }),
23348            ),
23349            (
23350                "starve+retries-burst → starve wins",
23351                MeshPolicy {
23352                    retries: Some(5),
23353                    rate_limit: Some(rl(1, 3600)),
23354                    circuit_breaker: Some(cb(10, 10)),
23355                    ..Default::default()
23356                },
23357                Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
23358                    rate: 1,
23359                    rl_window: Duration::from_secs(3600),
23360                    max_failures: 10,
23361                    cb_window: Duration::from_secs(10),
23362                }),
23363            ),
23364            (
23365                "retries-saturate+retries-burst → saturate wins",
23366                MeshPolicy {
23367                    retries: Some(5),
23368                    rate_limit: Some(rl(3, 1)),
23369                    circuit_breaker: Some(cb(3, 60)),
23370                    ..Default::default()
23371                },
23372                Some(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
23373                    retries: 5,
23374                    max_failures: 3,
23375                }),
23376            ),
23377        ];
23378        assert_first_cross_axis_violation_agrees_with_gate(cases);
23379    }
23380
23381    /// Sweep body shared by every `MeshPolicy::validate` ≡ gate
23382    /// equivalence pin — assert that on each `(label, politicas,
23383    /// expected)` case both the substrate primitive
23384    /// [`MeshPolicy::validate`] and the [`AplicacaoSpec::validate_politicas`]
23385    /// cascade (reached through `AplicacaoSpec::validate`, keying off the
23386    /// same `three_member_spec` fixture whose non-`:politicas` slots
23387    /// always validate cleanly) return identical `AplicacaoError` variants.
23388    /// Peer of [`assert_first_cross_axis_violation_agrees_with_gate`] on
23389    /// the sibling cross-axis-only surface — extended here onto the
23390    /// compound per-axis + cross-axis entry gate. Extracted so each pin's
23391    /// own body stays under `clippy::too_many_lines`.
23392    fn assert_validate_matches_gate(cases: &[(&str, MeshPolicy, Option<AplicacaoError>)]) {
23393        for (label, politicas, expected) in cases {
23394            let direct = politicas.validate();
23395            match (expected, &direct) {
23396                (None, Ok(())) => {}
23397                (None, Err(got)) => {
23398                    panic!("`{label}`: MeshPolicy::validate must pass; got {got:?}")
23399                }
23400                (Some(want), Ok(())) => {
23401                    panic!("`{label}`: MeshPolicy::validate must return {want:?}; got Ok")
23402                }
23403                (Some(want), Err(got)) => assert_eq!(
23404                    got, want,
23405                    "`{label}`: MeshPolicy::validate must return {want:?}; got {got:?}"
23406                ),
23407            }
23408
23409            let mut s = three_member_spec();
23410            s.politicas = politicas.clone();
23411            let gate = s.validate();
23412            match (expected, &gate) {
23413                (None, Ok(())) => {}
23414                (None, Err(got)) => {
23415                    panic!("`{label}`: validate_politicas gate must pass; got {got:?}")
23416                }
23417                (Some(want), Ok(())) => {
23418                    panic!("`{label}`: validate_politicas gate must return {want:?}; got Ok")
23419                }
23420                (Some(want), Err(got)) => assert_eq!(
23421                    got, want,
23422                    "`{label}`: validate_politicas gate must return {want:?}; got {got:?}"
23423                ),
23424            }
23425        }
23426    }
23427
23428    #[test]
23429    fn validate_matches_gate_on_per_axis_and_phase_boundary_shapes() {
23430        // Half-A of the compound-per-axis-+-cross-axis-fold ≡ gate
23431        // equivalence pin on [`MeshPolicy::validate`]: the four per-axis
23432        // zero-floor arms (`:timeout`, `:retries`, `:circuit-breaker
23433        // :max-failures`, `:rate-limit` rate) that discriminate the
23434        // "per-axis phase fires" arm of the compound gate, plus one
23435        // per-axis-before-cross-axis case (`{ timeout: 30s, cb.window:
23436        // ZERO }`) that pins the phase-boundary ordering — the per-axis
23437        // `PolicyBreakerZeroWindow` arm strictly precedes the cross-axis
23438        // `PolicyBreakerWindowBelowTimeout` arm, so the zero-window
23439        // diagnostic wins over the window-below-timeout diagnostic. Peer
23440        // of the sibling
23441        // `first_cross_axis_violation_matches_gate_on_single_arm_and_vacuous_shapes`
23442        // + `_on_pairwise_orderings` pins on the compound cross-axis
23443        // fold, extended here onto the outer compound entry gate that
23444        // folds per-axis + cross-axis surfaces. Half-B (cross-axis and
23445        // clean-pass surfaces) lives in the sibling
23446        // `validate_matches_gate_on_cross_axis_and_clean_pass_shapes`
23447        // pin; splitting keeps each pin's body under
23448        // `clippy::too_many_lines`.
23449        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
23450            (
23451                "per-axis: timeout zero",
23452                MeshPolicy {
23453                    timeout: Some(Duration::ZERO),
23454                    ..Default::default()
23455                },
23456                Some(AplicacaoError::PolicyTimeoutZero),
23457            ),
23458            (
23459                "per-axis: retries zero",
23460                MeshPolicy {
23461                    retries: Some(0),
23462                    ..Default::default()
23463                },
23464                Some(AplicacaoError::PolicyRetriesZero),
23465            ),
23466            (
23467                "per-axis: breaker max-failures zero",
23468                MeshPolicy {
23469                    circuit_breaker: Some(CircuitBreaker {
23470                        max_failures: 0,
23471                        window: Duration::from_secs(60),
23472                    }),
23473                    ..Default::default()
23474                },
23475                Some(AplicacaoError::PolicyBreakerZeroFailures),
23476            ),
23477            (
23478                "per-axis: rate-limit rate zero",
23479                MeshPolicy {
23480                    rate_limit: Some(RateLimit {
23481                        rate: 0,
23482                        window: Duration::from_secs(1),
23483                    }),
23484                    ..Default::default()
23485                },
23486                Some(AplicacaoError::PolicyRateLimitZero),
23487            ),
23488            (
23489                "per-axis before cross-axis: zero-window wins over window-below-timeout",
23490                MeshPolicy {
23491                    timeout: Some(Duration::from_secs(30)),
23492                    circuit_breaker: Some(CircuitBreaker {
23493                        max_failures: 5,
23494                        window: Duration::ZERO,
23495                    }),
23496                    ..Default::default()
23497                },
23498                Some(AplicacaoError::PolicyBreakerZeroWindow),
23499            ),
23500        ];
23501        assert_validate_matches_gate(cases);
23502    }
23503
23504    #[test]
23505    fn validate_matches_gate_on_cross_axis_and_clean_pass_shapes() {
23506        // Half-B of the compound-per-axis-+-cross-axis-fold ≡ gate
23507        // equivalence pin on [`MeshPolicy::validate`]: the cross-axis
23508        // arm that discriminates the "cross-axis phase fires" arm of
23509        // the compound gate (window-below-timeout — sibling per-arm
23510        // coverage lives in the two
23511        // `first_cross_axis_violation_matches_gate_on_*` pins above),
23512        // plus the two clean-pass shapes (empty policy — every axis
23513        // absent — and fully-coherent — every axis inside the coherence
23514        // surface) that pin the compound gate's `Ok(())` arm. Half-A
23515        // (per-axis + phase-boundary surfaces) lives in the sibling
23516        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
23517        // pin; splitting keeps each pin's body under
23518        // `clippy::too_many_lines`.
23519        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
23520            (
23521                "cross-axis: window-below-timeout",
23522                MeshPolicy {
23523                    timeout: Some(Duration::from_secs(30)),
23524                    circuit_breaker: Some(CircuitBreaker {
23525                        max_failures: 5,
23526                        window: Duration::from_secs(10),
23527                    }),
23528                    ..Default::default()
23529                },
23530                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
23531                    window: Duration::from_secs(10),
23532                    timeout: Duration::from_secs(30),
23533                }),
23534            ),
23535            ("clean pass: empty policy", MeshPolicy::default(), None),
23536            (
23537                "clean pass: every axis coherent",
23538                MeshPolicy {
23539                    timeout: Some(Duration::from_secs(30)),
23540                    retries: Some(3),
23541                    circuit_breaker: Some(CircuitBreaker {
23542                        max_failures: 5,
23543                        window: Duration::from_secs(60),
23544                    }),
23545                    mtls_required: Some(true),
23546                    rate_limit: Some(RateLimit {
23547                        rate: 100,
23548                        window: Duration::from_secs(1),
23549                    }),
23550                },
23551                None,
23552            ),
23553        ];
23554        assert_validate_matches_gate(cases);
23555    }
23556
23557    #[test]
23558    fn empty_politicas_validates() {
23559        // Omitting every policy axis is fine — defaults express "no
23560        // policy on this axis", not "policy = 0". The fixture's typical
23561        // values continue to validate; this test pins that
23562        // MeshPolicy::default() is a clean pass through validate().
23563        let mut s = three_member_spec();
23564        s.politicas = MeshPolicy::default();
23565        s.validate().unwrap();
23566    }
23567
23568    #[test]
23569    fn typical_politicas_validates_with_every_axis_set() {
23570        // The full §III.1 example block (timeout + retries + breaker +
23571        // mtls + rate-limit) — every axis nonzero — must remain a
23572        // clean pass.
23573        let mut s = three_member_spec();
23574        s.politicas = MeshPolicy {
23575            timeout: Some(Duration::from_secs(30)),
23576            retries: Some(3),
23577            circuit_breaker: Some(CircuitBreaker {
23578                max_failures: 5,
23579                window: Duration::from_secs(60),
23580            }),
23581            mtls_required: Some(true),
23582            rate_limit: Some(RateLimit {
23583                rate: 100,
23584                window: Duration::from_secs(1),
23585            }),
23586        };
23587        s.validate().unwrap();
23588    }
23589
23590    #[test]
23591    fn rejects_empty_cluster_name() {
23592        let mut s = three_member_spec();
23593        s.placement.clusters = vec!["rio".into(), String::new()];
23594        assert_eq!(
23595            s.validate().unwrap_err(),
23596            AplicacaoError::PlacementClusterEmpty
23597        );
23598    }
23599
23600    #[test]
23601    fn rejects_duplicate_cluster_names() {
23602        let mut s = three_member_spec();
23603        s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
23604        let err = s.validate().unwrap_err();
23605        assert!(
23606            matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
23607            "got {err:?}"
23608        );
23609    }
23610
23611    #[test]
23612    fn rejects_placement_cluster_with_uppercase() {
23613        // The canonical "I copied the cluster's display name verbatim"
23614        // typo — K8s context names are lowercase per DNS-1123 label
23615        // rule, but org docs often round-trip a TitleCase identifier
23616        // (`Rio`, `Mar-East`) from an ADR. Mirrors the
23617        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
23618        // on the peer name axis.
23619        let mut s = three_member_spec();
23620        s.placement.clusters = vec!["Rio".into(), "mar".into()];
23621        let err = s.validate().unwrap_err();
23622        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
23623            panic!("expected PlacementClusterInvalid, got other variant");
23624        };
23625        assert_eq!(cluster, "Rio");
23626        assert!(
23627            reason.contains("uppercase"),
23628            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
23629        );
23630        assert!(
23631            reason.contains("\"rio\""),
23632            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
23633        );
23634    }
23635
23636    #[test]
23637    fn rejects_placement_cluster_with_underscore() {
23638        // The canonical "I'm thinking of an env var / hostname slug"
23639        // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
23640        // schema. K8s context filtering on `my_cluster` silently misses
23641        // the cluster the author intended; the gate moves it to caixa-
23642        // build time. Same shape as `rejects_membro_caixa_with_underscore`
23643        // (3f9d7a0).
23644        let mut s = three_member_spec();
23645        s.placement.clusters = vec!["my_cluster".into()];
23646        let err = s.validate().unwrap_err();
23647        assert!(
23648            matches!(
23649                err,
23650                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
23651                    if cluster == "my_cluster" && reason.contains('_')
23652            ),
23653            "got {err:?}"
23654        );
23655    }
23656
23657    #[test]
23658    fn rejects_placement_cluster_with_dot() {
23659        // A `:placement :clusters` entry is a single DNS-1123 *label*,
23660        // not a subdomain — even though K8s context names sometimes
23661        // carry a dotted form via kubeconfig conventions, the strictest
23662        // floor among the use sites (DNS-1035 cluster.x-k8s.io
23663        // `metadata.name`, Cilium identity label values) wins. The "I
23664        // want to namespace my cluster names with `.`" intent is
23665        // expressed via `-` (`mar-east`).
23666        let mut s = three_member_spec();
23667        s.placement.clusters = vec!["team.rio".into()];
23668        let err = s.validate().unwrap_err();
23669        assert!(
23670            matches!(
23671                err,
23672                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
23673                    if cluster == "team.rio" && reason.contains('.')
23674            ),
23675            "got {err:?}"
23676        );
23677    }
23678
23679    #[test]
23680    fn rejects_placement_cluster_with_leading_hyphen() {
23681        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
23682        // with an alphanumeric. The K8s apiserver rejects `-rio`
23683        // outright; the rendered fan-out would emit a `metadata.name:
23684        // "-rio"` that fails admission far from the source caixa.lisp.
23685        let mut s = three_member_spec();
23686        s.placement.clusters = vec!["-rio".into()];
23687        let err = s.validate().unwrap_err();
23688        assert!(
23689            matches!(
23690                err,
23691                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
23692                    if cluster == "-rio" && reason.contains("start and end")
23693            ),
23694            "got {err:?}"
23695        );
23696    }
23697
23698    #[test]
23699    fn rejects_placement_cluster_with_trailing_hyphen() {
23700        // The symmetric arm of the boundary rule. Pin separately so
23701        // both ends are covered against a future relaxation that only
23702        // checks one boundary (parallel to
23703        // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
23704        let mut s = three_member_spec();
23705        s.placement.clusters = vec!["rio-".into()];
23706        let err = s.validate().unwrap_err();
23707        assert!(
23708            matches!(
23709                err,
23710                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
23711                    if cluster == "rio-"
23712            ),
23713            "got {err:?}"
23714        );
23715    }
23716
23717    #[test]
23718    fn rejects_placement_cluster_with_unicode() {
23719        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
23720        // before it reaches K8s. The byte-by-byte ASCII validity check
23721        // rejects multi-byte UTF-8 sequences by the first byte that
23722        // fails `[a-z0-9-]`.
23723        let mut s = three_member_spec();
23724        s.placement.clusters = vec!["rió".into()];
23725        let err = s.validate().unwrap_err();
23726        assert!(
23727            matches!(
23728                err,
23729                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
23730                    if cluster == "rió"
23731            ),
23732            "got {err:?}"
23733        );
23734    }
23735
23736    #[test]
23737    fn rejects_placement_cluster_with_whitespace() {
23738        // Whitespace is the canonical "I pasted from a sketch / doc"
23739        // footgun. The apiserver rejects every cluster `metadata.name`
23740        // value carrying whitespace.
23741        let mut s = three_member_spec();
23742        s.placement.clusters = vec!["rio cluster".into()];
23743        let err = s.validate().unwrap_err();
23744        assert!(
23745            matches!(
23746                err,
23747                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
23748                    if cluster == "rio cluster"
23749            ),
23750            "got {err:?}"
23751        );
23752    }
23753
23754    #[test]
23755    fn rejects_placement_cluster_too_long() {
23756        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
23757        // pin. The diagnostic names both the cap (63) and the actual
23758        // length so the author can shorten in one edit. Mirrors
23759        // `rejects_membro_caixa_too_long` (3f9d7a0).
23760        let mut s = three_member_spec();
23761        let too_long = "a".repeat(64);
23762        s.placement.clusters = vec![too_long.clone()];
23763        let err = s.validate().unwrap_err();
23764        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
23765            panic!("expected PlacementClusterInvalid");
23766        };
23767        assert_eq!(cluster, too_long);
23768        assert!(
23769            reason.contains("63") && reason.contains("64"),
23770            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
23771        );
23772    }
23773
23774    #[test]
23775    fn placement_cluster_max_length_validates() {
23776        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
23777        // future tightening (e.g. dropping to 62) surfaces here as a
23778        // regression, mirroring `membro_caixa_max_length_validates`
23779        // (3f9d7a0).
23780        let mut s = three_member_spec();
23781        s.placement.clusters = vec!["a".repeat(63)];
23782        s.validate().unwrap();
23783    }
23784
23785    #[test]
23786    fn accepts_canonical_placement_cluster_forms() {
23787        // The DNS-1123 label shapes a caixa author is realistically
23788        // going to write for cluster names: single-word lowercase
23789        // (`rio`), regional hyphen-joined (`mar-east`), single
23790        // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
23791        // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
23792        // Pin every leg so a future tightening that bans (e.g.) digit-
23793        // start identifiers surfaces here.
23794        for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
23795            let mut s = three_member_spec();
23796            s.placement.clusters = vec![form.into()];
23797            s.validate().unwrap_or_else(|e| {
23798                panic!("canonical cluster form {form:?} must validate, got {e:?}")
23799            });
23800        }
23801    }
23802
23803    #[test]
23804    fn placement_cluster_empty_takes_precedence_over_invalid() {
23805        // Order pin: the existing `PlacementClusterEmpty` diagnostic
23806        // (which doesn't try to parse) fires before the new
23807        // `PlacementClusterInvalid` parse-side diagnostic, so an empty
23808        // `:clusters` entry keeps its narrower error message — the new
23809        // gate would also reject `""`, but the empty-string arm is the
23810        // more self-locating diagnostic. Mirrors the
23811        // `membro_caixa_empty_takes_precedence_over_invalid` pin
23812        // (3f9d7a0).
23813        let mut s = three_member_spec();
23814        s.placement.clusters = vec!["rio".into(), String::new()];
23815        let err = s.validate().unwrap_err();
23816        assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
23817    }
23818
23819    #[test]
23820    fn placement_cluster_invalid_fires_before_duplicate_check() {
23821        // Order pin: a malformed-shape `:clusters` entry surfaces *its
23822        // own* diagnostic, even when a later entry would otherwise
23823        // collapse onto a duplicate name. The per-entry shape gate runs
23824        // inline before the duplicate-key insert, parallel to
23825        // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
23826        let mut s = three_member_spec();
23827        s.placement.clusters = vec!["Rio".into(), "rio".into()];
23828        let err = s.validate().unwrap_err();
23829        assert!(
23830            matches!(
23831                err,
23832                AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
23833            ),
23834            "got {err:?}"
23835        );
23836    }
23837
23838    #[test]
23839    fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
23840        // The diagnostic-shape pin: the error names the offending
23841        // `:clusters` value verbatim so the author can grep their
23842        // caixa.lisp without re-running the build, and carries a
23843        // non-empty `reason` naming the specific violation. Same shape
23844        // every typed-shape gate enshrines
23845        // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
23846        // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
23847        let mut s = three_member_spec();
23848        s.placement.clusters = vec!["BAD_CLUSTER".into()];
23849        let err = s.validate().unwrap_err();
23850        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
23851            panic!("expected PlacementClusterInvalid");
23852        };
23853        assert_eq!(cluster, "BAD_CLUSTER");
23854        assert!(
23855            !reason.is_empty(),
23856            "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
23857        );
23858    }
23859
23860    #[test]
23861    fn rejects_sharded_with_empty_clusters() {
23862        // §III.1: Sharded uses :clusters as the shard pool. An empty
23863        // pool means "shard across no clusters" — meaningless, same as
23864        // Replicated with no hosts.
23865        let mut s = three_member_spec();
23866        s.placement.estrategia = PlacementStrategy::Sharded;
23867        s.placement.shard_key = Some("$tenantId".into());
23868        s.placement.clusters = vec![];
23869        assert!(matches!(
23870            s.validate().unwrap_err(),
23871            AplicacaoError::PlacementWithoutClusters {
23872                estrategia: PlacementStrategy::Sharded
23873            }
23874        ));
23875    }
23876
23877    #[test]
23878    fn rejects_sharded_with_empty_shard_key() {
23879        let mut s = three_member_spec();
23880        s.placement.estrategia = PlacementStrategy::Sharded;
23881        s.placement.shard_key = Some(String::new());
23882        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
23883    }
23884
23885    #[test]
23886    fn rejects_shard_key_under_replicated_strategy() {
23887        // The fail-before-pass-after pin: a `:placement (:estrategia
23888        // Replicated :shard-key "tenantId")` manifest carries the
23889        // hash-keyed-distribution slot on a strategy that never consumes
23890        // it. Before the gate the typed slot's value silently vanished
23891        // at the renderer layer (caixa-mesh emits `placement.shardKey`
23892        // verbatim regardless of strategy; the Akka-style cluster-
23893        // sharding reconciler keys off `estrategia == Sharded` and
23894        // ignores the slot otherwise), with no diagnostic. Lifting the
23895        // rejection to a build-time gate makes the
23896        // `shard_key.is_some() == matches!(estrategia, Sharded)`
23897        // partition a structural property of every validated
23898        // [`Placement`].
23899        let mut s = three_member_spec();
23900        // The fixture already uses Replicated; just add a shard-key.
23901        s.placement.shard_key = Some("$tenantId".into());
23902        let err = s.validate().unwrap_err();
23903        let AplicacaoError::ShardKeyOnNonSharded {
23904            estrategia,
23905            shard_key,
23906        } = err
23907        else {
23908            panic!("expected ShardKeyOnNonSharded, got {err:?}");
23909        };
23910        assert_eq!(estrategia, PlacementStrategy::Replicated);
23911        assert_eq!(shard_key, "$tenantId");
23912    }
23913
23914    #[test]
23915    fn rejects_shard_key_under_singlenode_strategy() {
23916        // Peer of the Replicated case above on the SingleNode arm: OTP
23917        // distributed-app takeover (one cluster runs at a time) has no
23918        // hash-keyed routing axis to consume `:shard-key` either, so
23919        // the rejection fires on both non-Sharded arms uniformly.
23920        let mut s = three_member_spec();
23921        s.placement.estrategia = PlacementStrategy::SingleNode;
23922        s.placement.shard_key = Some("$tenantId".into());
23923        let err = s.validate().unwrap_err();
23924        let AplicacaoError::ShardKeyOnNonSharded {
23925            estrategia,
23926            shard_key,
23927        } = err
23928        else {
23929            panic!("expected ShardKeyOnNonSharded, got {err:?}");
23930        };
23931        assert_eq!(estrategia, PlacementStrategy::SingleNode);
23932        assert_eq!(shard_key, "$tenantId");
23933    }
23934
23935    #[test]
23936    fn rejects_empty_shard_key_under_replicated_strategy() {
23937        // The `Some("")` case under non-Sharded is rejected by
23938        // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
23939        // fires before the empty-value gate), not
23940        // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
23941        // the `Sharded` arm). Pin the partition so a future reorder of
23942        // the validate_placement match arms doesn't silently swap which
23943        // diagnostic the author sees — both are author errors, but
23944        // ShardKeyOnNonSharded names which strategy is the actual fix
23945        // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
23946        // only says "pick a non-empty key".
23947        let mut s = three_member_spec();
23948        s.placement.shard_key = Some(String::new());
23949        let err = s.validate().unwrap_err();
23950        assert!(
23951            matches!(
23952                err,
23953                AplicacaoError::ShardKeyOnNonSharded {
23954                    estrategia: PlacementStrategy::Replicated,
23955                    ref shard_key,
23956                } if shard_key.is_empty()
23957            ),
23958            "got {err:?}"
23959        );
23960    }
23961
23962    #[test]
23963    fn replicated_without_shard_key_validates() {
23964        // The complement of the rejection: `:placement :estrategia
23965        // Replicated` with `:shard-key None` is the canonical happy
23966        // path on every existing fixture. Pin the no-shard-key case so
23967        // the new gate doesn't accidentally fire on `None`.
23968        let mut s = three_member_spec();
23969        assert!(matches!(
23970            s.placement.estrategia,
23971            PlacementStrategy::Replicated
23972        ));
23973        s.placement.shard_key = None;
23974        s.validate().unwrap();
23975    }
23976
23977    #[test]
23978    fn singlenode_without_shard_key_validates() {
23979        // Peer of the Replicated no-shard-key case on the SingleNode
23980        // arm — both non-Sharded strategies must validate cleanly when
23981        // the slot is omitted.
23982        let mut s = three_member_spec();
23983        s.placement.estrategia = PlacementStrategy::SingleNode;
23984        s.placement.shard_key = None;
23985        s.validate().unwrap();
23986    }
23987
23988    #[test]
23989    fn shard_key_on_non_sharded_ctor_matches_struct_literal_wrap() {
23990        // Fail-before-pass-after pin on
23991        // [`AplicacaoError::shard_key_on_non_sharded`]'s
23992        // substrate-primitive posture: byte-identity + `Display`
23993        // byte-string parity against the open-coded struct-literal
23994        // for every non-`Sharded` [`PlacementStrategy`] arm across a
23995        // representative `:shard-key` value the sole in-crate wire-up
23996        // site (`AplicacaoSpec::validate_placement`'s
23997        // `PlacementStrategy::Replicated | PlacementStrategy::SingleNode`
23998        // arm) emits. Any wrapper-side silent normalization, `.into()`
23999        // divergence, or accidental field rebrand on the ctor body
24000        // surfaces at assert time rather than at a downstream consumer
24001        // that reads `err.estrategia` / `err.shard_key` back and gets a
24002        // different value than the one it stored.
24003        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
24004            let placement = Placement {
24005                estrategia,
24006                clusters: vec!["cluster-a".to_string()],
24007                shard_key: Some("$tenantId".to_string()),
24008                affinity: None,
24009            };
24010            let via_ctor = AplicacaoError::shard_key_on_non_sharded(&placement, "$tenantId");
24011            let via_literal = AplicacaoError::ShardKeyOnNonSharded {
24012                estrategia,
24013                shard_key: "$tenantId".to_string(),
24014            };
24015            assert_eq!(
24016                via_ctor, via_literal,
24017                "shard_key_on_non_sharded(&placement, k) must byte-equal the \
24018                 open-coded ShardKeyOnNonSharded struct-literal for {estrategia:?}"
24019            );
24020            assert_eq!(
24021                via_ctor.to_string(),
24022                via_literal.to_string(),
24023                "Display byte-string must byte-equal the open-coded struct-literal \
24024                 for {estrategia:?}"
24025            );
24026        }
24027    }
24028
24029    #[test]
24030    fn shard_key_on_non_sharded_routes_estrategia_through_placement_accessor() {
24031        // Boundary-sweep pin on the ctor's substrate-primitive
24032        // projection: the `estrategia` slot is stored verbatim from
24033        // [`Placement::estrategia`] on every arm the accessor can
24034        // return, and the `shard_key` slot preserves the caller-side
24035        // `&str` byte-for-byte. Sweeping every arm of
24036        // [`PlacementStrategy::ALL`] (including the `Sharded` arm the
24037        // current caller never reaches, since the ctor is a substrate
24038        // primitive independent of any single caller's dispatch gate)
24039        // catches a future silent field-rebrand or per-arm ctor
24040        // divergence at caixa-core build time rather than at a
24041        // downstream consumer far from the wire-up commit.
24042        for &estrategia in PlacementStrategy::ALL {
24043            let placement = Placement {
24044                estrategia,
24045                clusters: vec!["cluster-a".to_string()],
24046                shard_key: Some("$tenantId".to_string()),
24047                affinity: None,
24048            };
24049            let err = AplicacaoError::shard_key_on_non_sharded(&placement, "$tenantId");
24050            let AplicacaoError::ShardKeyOnNonSharded {
24051                estrategia: stored_estrategia,
24052                shard_key: stored_shard_key,
24053            } = err
24054            else {
24055                panic!(
24056                    "shard_key_on_non_sharded must construct ShardKeyOnNonSharded for {estrategia:?}"
24057                );
24058            };
24059            assert_eq!(
24060                stored_estrategia, estrategia,
24061                "estrategia slot must round-trip verbatim through Placement::estrategia \
24062                 for {estrategia:?}"
24063            );
24064            assert_eq!(
24065                stored_shard_key, "$tenantId",
24066                "shard_key slot must preserve the caller-side &str byte-for-byte \
24067                 for {estrategia:?}"
24068            );
24069        }
24070    }
24071
24072    #[test]
24073    fn validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor() {
24074        // End-to-end pin: the sole in-crate wire-up site
24075        // (`AplicacaoSpec::validate_placement`'s non-`Sharded`-arm
24076        // refusal) routes through
24077        // [`AplicacaoError::shard_key_on_non_sharded`] and the observed
24078        // `Err` byte-equals the ctor's output on the same non-`Sharded`
24079        // fixture. A future silent de-lift of the wire-up back to the
24080        // open-coded struct-literal trips this test at caixa-core build
24081        // time rather than at a downstream diagnostic consumer far from
24082        // the wire-up commit.
24083        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
24084            let mut s = three_member_spec();
24085            s.placement.estrategia = estrategia;
24086            s.placement.shard_key = Some("$tenantId".to_string());
24087            let observed = s.validate().unwrap_err();
24088            let expected = AplicacaoError::shard_key_on_non_sharded(&s.placement, "$tenantId");
24089            assert_eq!(
24090                observed, expected,
24091                "validate_placement's non-Sharded-arm Err must byte-equal \
24092                 shard_key_on_non_sharded(&placement, k) for {estrategia:?}"
24093            );
24094            assert_eq!(
24095                observed.to_string(),
24096                expected.to_string(),
24097                "Display byte-string parity for {estrategia:?}"
24098            );
24099        }
24100    }
24101
24102    fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
24103        // Fixture builder for the `:placement :shard-key` shape gate
24104        // tests: a three-member Aplicacao on the `Sharded` strategy
24105        // with the supplied `:shard-key` slot. Co-locates the
24106        // arm-construction so every test below carries one line of
24107        // setup (the offending `:shard-key` value) and the assertion.
24108        let mut s = three_member_spec();
24109        s.placement.estrategia = PlacementStrategy::Sharded;
24110        s.placement.shard_key = Some(key.into());
24111        s
24112    }
24113
24114    #[test]
24115    fn rejects_shard_key_with_embedded_space() {
24116        // The canonical paste-from-aligned-doc footgun:
24117        // `:shard-key "$tenant Id"` — the Akka-style entity-id
24118        // extractor reads the slot as a single-token reference, and an
24119        // embedded space breaks the token boundary at the runtime
24120        // hash-extractor pass with no diagnostic naming the offending
24121        // entry.
24122        let s = sharded_spec_with_key("$tenant Id");
24123        let err = s.validate().unwrap_err();
24124        assert!(
24125            matches!(
24126                err,
24127                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
24128                    if shard_key == "$tenant Id" && reason.contains("space")
24129            ),
24130            "got {err:?}"
24131        );
24132    }
24133
24134    #[test]
24135    fn rejects_shard_key_with_leading_space() {
24136        // Leading-space arm of the embedded-whitespace footgun — the
24137        // paste-from-aligned-doc / paste-from-CSV-cell variant where
24138        // the leading column-padding leaked into the slot.
24139        let s = sharded_spec_with_key(" $tenantId");
24140        let err = s.validate().unwrap_err();
24141        assert!(
24142            matches!(
24143                err,
24144                AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
24145                    if shard_key == " $tenantId"
24146            ),
24147            "got {err:?}"
24148        );
24149    }
24150
24151    #[test]
24152    fn rejects_shard_key_with_trailing_newline() {
24153        // The canonical paste-from-shell-heredoc footgun — every
24154        // `<<EOF` heredoc terminator paste leaves a trailing newline
24155        // the YAML emitter then folds away inconsistently across
24156        // emitter implementations.
24157        let s = sharded_spec_with_key("$tenantId\n");
24158        let err = s.validate().unwrap_err();
24159        assert!(
24160            matches!(
24161                err,
24162                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
24163                    if shard_key == "$tenantId\n" && reason.contains("0x0a")
24164            ),
24165            "got {err:?}"
24166        );
24167    }
24168
24169    #[test]
24170    fn rejects_shard_key_with_embedded_tab() {
24171        // The paste-from-aligned-doc tab-stop variant — tabs land
24172        // alongside spaces in copy-paste from formatted columns.
24173        let s = sharded_spec_with_key("$tenant\tId");
24174        let err = s.validate().unwrap_err();
24175        assert!(
24176            matches!(
24177                err,
24178                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
24179                    if shard_key == "$tenant\tId" && reason.contains("tab")
24180            ),
24181            "got {err:?}"
24182        );
24183    }
24184
24185    #[test]
24186    fn rejects_shard_key_with_control_character() {
24187        // The paste-from-binary / paste-from-screen-cleared-terminal
24188        // footgun — an embedded `\x01` (SOH) byte that some YAML
24189        // emitters silently strip and others escape as ``,
24190        // breaking round-trip across emitter implementations.
24191        let s = sharded_spec_with_key("$tenant\u{0001}Id");
24192        let err = s.validate().unwrap_err();
24193        assert!(
24194            matches!(
24195                err,
24196                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
24197                    if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
24198            ),
24199            "got {err:?}"
24200        );
24201    }
24202
24203    #[test]
24204    fn rejects_shard_key_with_non_ascii() {
24205        // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
24206        // footgun — non-ASCII bytes normalize differently between the
24207        // caixa-mesh-side YAML emitter and the in-cluster reconciler's
24208        // YAML parser, the same entity ID can silently map to two
24209        // distinct shards on a re-render.
24210        let s = sharded_spec_with_key("$tenàntId");
24211        let err = s.validate().unwrap_err();
24212        assert!(
24213            matches!(
24214                err,
24215                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
24216                    if shard_key == "$tenàntId" && reason.contains("non-ASCII")
24217            ),
24218            "got {err:?}"
24219        );
24220    }
24221
24222    #[test]
24223    fn rejects_shard_key_too_long() {
24224        // Length cap pin: 64 bytes — one byte over the
24225        // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
24226        // here is a paste-from-doc multi-line blob landing in
24227        // `:shard-key` instead of a single-token extractor expression.
24228        let too_long = "a".repeat(64);
24229        let s = sharded_spec_with_key(&too_long);
24230        let err = s.validate().unwrap_err();
24231        let AplicacaoError::ShardKeyInvalid {
24232            ref shard_key,
24233            ref reason,
24234        } = err
24235        else {
24236            panic!("expected ShardKeyInvalid, got {err:?}");
24237        };
24238        assert_eq!(shard_key, &too_long);
24239        assert!(
24240            reason.contains("63") && reason.contains("64"),
24241            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
24242        );
24243    }
24244
24245    #[test]
24246    fn shard_key_max_length_validates() {
24247        // Boundary pin: 63 bytes exactly — the
24248        // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
24249        // dropping to 62) surfaces here as a regression, mirroring
24250        // `placement_cluster_max_length_validates` /
24251        // `placement_affinity_max_length_validates` on the peer
24252        // identifier-shaped slots.
24253        let s = sharded_spec_with_key(&"a".repeat(63));
24254        s.validate().unwrap();
24255    }
24256
24257    #[test]
24258    fn accepts_canonical_shard_key_forms() {
24259        // The Akka-style entity-id extractor shapes a caixa author is
24260        // realistically going to write — pin every leg so a future
24261        // tightening that bans (e.g.) the `${...}` interpolation
24262        // variant or the `metadata.<field>` JSONPath form surfaces
24263        // here as a regression. The canonical forms span:
24264        //
24265        //   - bare property name (`tenantId`, `customerId`)
24266        //   - Akka `ExtractEntityId` placeholder (`$tenantId`)
24267        //   - JSONPath-style nested reference (`metadata.tenantId`,
24268        //     `$.user.id`)
24269        //   - interpolation-style template (`${tenant}`)
24270        //   - snake_case property name (`customer_id`)
24271        //   - kebab-case property name (`customer-id` — accepted
24272        //     because the slot is a printable-ASCII single-token
24273        //     reference, not a DNS-1123 label like
24274        //     `:placement :affinity` / `:clusters`)
24275        //   - single character (`a`, `$` — boundary)
24276        for form in [
24277            "tenantId",
24278            "customerId",
24279            "$tenantId",
24280            "metadata.tenantId",
24281            "$.user.id",
24282            "${tenant}",
24283            "customer_id",
24284            "customer-id",
24285            "a",
24286            "$",
24287        ] {
24288            let s = sharded_spec_with_key(form);
24289            s.validate().unwrap_or_else(|e| {
24290                panic!("canonical shard-key form {form:?} must validate, got {e:?}")
24291            });
24292        }
24293    }
24294
24295    #[test]
24296    fn shard_key_empty_takes_precedence_over_invalid() {
24297        // Order pin: the existing `ShardedKeyEmpty` diagnostic
24298        // (reserved for the `Sharded` `Some("")` arm) fires before the
24299        // new `ShardKeyInvalid` parse-side diagnostic, so an empty
24300        // `:shard-key` keeps its narrower error message — the new gate
24301        // would also reject `""` defensively, but the empty-string arm
24302        // is the more self-locating diagnostic. Mirrors the
24303        // `placement_cluster_empty_takes_precedence_over_invalid` pin
24304        // on the peer identifier-shaped slot.
24305        let s = sharded_spec_with_key("");
24306        let err = s.validate().unwrap_err();
24307        assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
24308    }
24309
24310    #[test]
24311    fn shard_key_invalid_diagnostic_carries_offending_value() {
24312        // The diagnostic-shape pin: the error names the offending
24313        // `:shard-key` value verbatim so the author can grep their
24314        // caixa.lisp without re-running the build, and carries a
24315        // parser-shaped `reason:` naming the specific violation —
24316        // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
24317        // on the peer identifier-shaped slot.
24318        let s = sharded_spec_with_key("$tenant Id");
24319        let err = s.validate().unwrap_err();
24320        let AplicacaoError::ShardKeyInvalid {
24321            ref shard_key,
24322            ref reason,
24323        } = err
24324        else {
24325            panic!("expected ShardKeyInvalid, got {err:?}");
24326        };
24327        assert_eq!(shard_key, "$tenant Id");
24328        assert!(
24329            !reason.is_empty(),
24330            "reason must name the specific violation, got empty string"
24331        );
24332    }
24333
24334    #[test]
24335    fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
24336        // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
24337        // `:shard-key` carried on non-Sharded strategies) fires before
24338        // the shape gate, so a malformed `:shard-key` carried on (e.g.)
24339        // a `Replicated` strategy surfaces the more self-locating
24340        // strategy-mismatch diagnostic (naming the actual fix — drop
24341        // the slot, or switch to Sharded) rather than the shape
24342        // diagnostic. The strategy-mismatch arm is the more actionable
24343        // diagnostic: a malformed shard-key on Replicated is "you
24344        // shouldn't have a :shard-key here at all", not "your
24345        // :shard-key value is malformed".
24346        let mut s = three_member_spec();
24347        // Replicated is the default fixture strategy.
24348        s.placement.shard_key = Some("$tenant Id".into());
24349        let err = s.validate().unwrap_err();
24350        assert!(
24351            matches!(
24352                err,
24353                AplicacaoError::ShardKeyOnNonSharded {
24354                    estrategia: PlacementStrategy::Replicated,
24355                    ..
24356                }
24357            ),
24358            "got {err:?}"
24359        );
24360    }
24361
24362    #[test]
24363    fn rejects_empty_affinity_hint() {
24364        let mut s = three_member_spec();
24365        s.placement.affinity = Some(String::new());
24366        assert_eq!(
24367            s.validate().unwrap_err(),
24368            AplicacaoError::PlacementAffinityEmpty
24369        );
24370    }
24371
24372    #[test]
24373    fn placement_without_affinity_validates() {
24374        // Omitting :affinity is fine — the placement engine falls back
24375        // to the default heuristic. Pin the no-hint case so the
24376        // affinity-empty rejection doesn't accidentally fire on `None`.
24377        let mut s = three_member_spec();
24378        s.placement.affinity = None;
24379        s.validate().unwrap();
24380    }
24381
24382    #[test]
24383    fn rejects_placement_affinity_with_uppercase() {
24384        // The canonical "I copied the ADR's display name verbatim" typo
24385        // — placement hints land verbatim in K8s label-selector
24386        // territory, where the apiserver enforces the DNS-1123 label
24387        // rule (lowercase-only) on every identity-keyed admission axis.
24388        // Mirrors `rejects_placement_cluster_with_uppercase` on the
24389        // sibling slot.
24390        let mut s = three_member_spec();
24391        s.placement.affinity = Some("DataLocality".into());
24392        let err = s.validate().unwrap_err();
24393        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
24394            panic!("expected PlacementAffinityInvalid, got other variant");
24395        };
24396        assert_eq!(affinity, "DataLocality");
24397        assert!(
24398            reason.contains("uppercase"),
24399            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
24400        );
24401        assert!(
24402            reason.contains("\"datalocality\""),
24403            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
24404        );
24405    }
24406
24407    #[test]
24408    fn rejects_placement_affinity_with_underscore() {
24409        // The canonical "I'm thinking of an env var / Python identifier"
24410        // leak — `_` is forbidden by every DNS-1123 label schema. Same
24411        // shape as `rejects_placement_cluster_with_underscore` on the
24412        // sibling slot.
24413        let mut s = three_member_spec();
24414        s.placement.affinity = Some("data_locality".into());
24415        let err = s.validate().unwrap_err();
24416        assert!(
24417            matches!(
24418                err,
24419                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
24420                    if affinity == "data_locality" && reason.contains('_')
24421            ),
24422            "got {err:?}"
24423        );
24424    }
24425
24426    #[test]
24427    fn rejects_placement_affinity_with_dot() {
24428        // A `:placement :affinity` value is a single DNS-1123 *label*
24429        // (it lands as a K8s label value selector key), not a subdomain.
24430        // The "I want to namespace my hint with `.`" intent is expressed
24431        // via `-` (`data-locality-east`).
24432        let mut s = three_member_spec();
24433        s.placement.affinity = Some("data.locality".into());
24434        let err = s.validate().unwrap_err();
24435        assert!(
24436            matches!(
24437                err,
24438                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
24439                    if affinity == "data.locality" && reason.contains('.')
24440            ),
24441            "got {err:?}"
24442        );
24443    }
24444
24445    #[test]
24446    fn rejects_placement_affinity_with_unicode() {
24447        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
24448        // before it reaches K8s. The byte-by-byte ASCII validity check
24449        // rejects multi-byte UTF-8 sequences by the first byte that
24450        // fails `[a-z0-9-]`.
24451        let mut s = three_member_spec();
24452        s.placement.affinity = Some("data-localité".into());
24453        let err = s.validate().unwrap_err();
24454        assert!(
24455            matches!(
24456                err,
24457                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
24458                    if affinity == "data-localité"
24459            ),
24460            "got {err:?}"
24461        );
24462    }
24463
24464    #[test]
24465    fn rejects_placement_affinity_with_leading_hyphen() {
24466        // DNS-1123 boundary rule: labels must start with an
24467        // alphanumeric. Pin separately from the trailing-hyphen arm so
24468        // a future relaxation that only checks one boundary surfaces
24469        // here as a regression (parallel to
24470        // `rejects_placement_cluster_with_leading_hyphen`).
24471        let mut s = three_member_spec();
24472        s.placement.affinity = Some("-data-locality".into());
24473        let err = s.validate().unwrap_err();
24474        assert!(
24475            matches!(
24476                err,
24477                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
24478                    if affinity == "-data-locality" && reason.contains("start and end")
24479            ),
24480            "got {err:?}"
24481        );
24482    }
24483
24484    #[test]
24485    fn rejects_placement_affinity_with_trailing_hyphen() {
24486        // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
24487        // ends are covered against a future relaxation.
24488        let mut s = three_member_spec();
24489        s.placement.affinity = Some("data-locality-".into());
24490        let err = s.validate().unwrap_err();
24491        assert!(
24492            matches!(
24493                err,
24494                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
24495                    if affinity == "data-locality-"
24496            ),
24497            "got {err:?}"
24498        );
24499    }
24500
24501    #[test]
24502    fn rejects_placement_affinity_with_whitespace() {
24503        // Whitespace is the canonical "I pasted from a sketch / doc"
24504        // footgun. The apiserver rejects every label-selector value
24505        // carrying whitespace.
24506        let mut s = three_member_spec();
24507        s.placement.affinity = Some("data locality".into());
24508        let err = s.validate().unwrap_err();
24509        assert!(
24510            matches!(
24511                err,
24512                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
24513                    if affinity == "data locality"
24514            ),
24515            "got {err:?}"
24516        );
24517    }
24518
24519    #[test]
24520    fn rejects_placement_affinity_too_long() {
24521        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
24522        // pin. The diagnostic names both the cap (63) and the actual
24523        // length so the author can shorten in one edit. Mirrors
24524        // `rejects_placement_cluster_too_long`.
24525        let mut s = three_member_spec();
24526        let too_long = "a".repeat(64);
24527        s.placement.affinity = Some(too_long.clone());
24528        let err = s.validate().unwrap_err();
24529        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
24530            panic!("expected PlacementAffinityInvalid");
24531        };
24532        assert_eq!(affinity, too_long);
24533        assert!(
24534            reason.contains("63") && reason.contains("64"),
24535            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
24536        );
24537    }
24538
24539    #[test]
24540    fn placement_affinity_max_length_validates() {
24541        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
24542        // future tightening (e.g. dropping to 62) surfaces here as a
24543        // regression, mirroring `placement_cluster_max_length_validates`.
24544        let mut s = three_member_spec();
24545        s.placement.affinity = Some("a".repeat(63));
24546        s.validate().unwrap();
24547    }
24548
24549    #[test]
24550    fn accepts_canonical_placement_affinity_forms() {
24551        // The DNS-1123 label shapes a caixa author is realistically
24552        // going to write for placement hints: the M3 canonical examples
24553        // (`data-locality`, `low-latency`, `anti-affinity`), the
24554        // single-token form (`affinity`), the single-character boundary
24555        // (`a`), the digit-start (DNS-1123 allows this, unlike
24556        // DNS-1035), and a regional-suffixed form. Pin every leg so a
24557        // future tightening that bans (e.g.) digit-start identifiers
24558        // surfaces here.
24559        for form in [
24560            "data-locality",
24561            "low-latency",
24562            "anti-affinity",
24563            "affinity",
24564            "a",
24565            "3-tier",
24566            "locality-east",
24567        ] {
24568            let mut s = three_member_spec();
24569            s.placement.affinity = Some(form.into());
24570            s.validate().unwrap_or_else(|e| {
24571                panic!("canonical affinity form {form:?} must validate, got {e:?}")
24572            });
24573        }
24574    }
24575
24576    #[test]
24577    fn placement_affinity_empty_takes_precedence_over_invalid() {
24578        // Order pin: the existing `PlacementAffinityEmpty` diagnostic
24579        // (which doesn't try to parse) fires before the new
24580        // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
24581        // `:affinity` keeps its narrower error message — the new gate
24582        // would also reject `""`, but the empty-string arm is the more
24583        // self-locating diagnostic. Mirrors the
24584        // `placement_cluster_empty_takes_precedence_over_invalid` pin.
24585        let mut s = three_member_spec();
24586        s.placement.affinity = Some(String::new());
24587        let err = s.validate().unwrap_err();
24588        assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
24589    }
24590
24591    #[test]
24592    fn placement_affinity_invalid_diagnostic_carries_offending_value() {
24593        // The diagnostic shape pin: every rejection carries the offending
24594        // `affinity:` verbatim plus a parser-shaped `reason:` so the
24595        // author can grep their caixa.lisp for `:affinity "<hint>"` and
24596        // fix it in one edit. Mirrors the
24597        // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
24598        // pin on the sibling slot.
24599        let mut s = three_member_spec();
24600        s.placement.affinity = Some("Data_Locality".into());
24601        let err = s.validate().unwrap_err();
24602        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
24603            panic!("expected PlacementAffinityInvalid");
24604        };
24605        assert_eq!(affinity, "Data_Locality");
24606        assert!(
24607            !reason.is_empty(),
24608            "diagnostic reason must not be empty (got: {reason:?})"
24609        );
24610    }
24611
24612    #[test]
24613    fn singlenode_with_takeover_candidates_validates() {
24614        // OTP distributed-application convention (MESH-COMPOSITION
24615        // §II.1): SingleNode runs on one cluster at a time but the
24616        // :clusters list enumerates the takeover candidates. Multiple
24617        // entries are not a contradiction — they are the failover pool.
24618        let mut s = three_member_spec();
24619        s.placement.estrategia = PlacementStrategy::SingleNode;
24620        s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
24621        s.validate().unwrap();
24622    }
24623
24624    // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
24625
24626    #[test]
24627    fn mesh_policy_default_is_empty() {
24628        // The Default impl carries None on every axis — the typed
24629        // analog of an unset `:politicas (())` slot. Renderers that
24630        // overlay the policy onto a cluster artifact key off this
24631        // predicate to skip the slot entirely; pinning so a future
24632        // axis added to MeshPolicy can't silently break the contract
24633        // (a new field whose Default is non-None would flip is_empty
24634        // to false on every existing caixa, surfacing here).
24635        assert!(MeshPolicy::default().is_empty());
24636    }
24637
24638    #[test]
24639    fn mesh_policy_with_only_timeout_is_not_empty() {
24640        let p = MeshPolicy {
24641            timeout: Some(Duration::from_secs(30)),
24642            ..Default::default()
24643        };
24644        assert!(!p.is_empty());
24645    }
24646
24647    #[test]
24648    fn mesh_policy_with_only_retries_is_not_empty() {
24649        let p = MeshPolicy {
24650            retries: Some(3),
24651            ..Default::default()
24652        };
24653        assert!(!p.is_empty());
24654    }
24655
24656    #[test]
24657    fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
24658        let p = MeshPolicy {
24659            circuit_breaker: Some(CircuitBreaker {
24660                max_failures: 5,
24661                window: Duration::from_secs(60),
24662            }),
24663            ..Default::default()
24664        };
24665        assert!(!p.is_empty());
24666    }
24667
24668    #[test]
24669    fn mesh_policy_with_only_mtls_required_is_not_empty() {
24670        // Even `mtls_required: Some(false)` (an explicit opt-out) is
24671        // not empty — the author *named* the axis, the renderer needs
24672        // to honor that vs. fall back to the cluster default.
24673        let p = MeshPolicy {
24674            mtls_required: Some(false),
24675            ..Default::default()
24676        };
24677        assert!(!p.is_empty());
24678    }
24679
24680    #[test]
24681    fn mesh_policy_with_only_rate_limit_is_not_empty() {
24682        let p = MeshPolicy {
24683            rate_limit: Some(RateLimit {
24684                rate: 100,
24685                window: Duration::from_secs(1),
24686            }),
24687            ..Default::default()
24688        };
24689        assert!(!p.is_empty());
24690    }
24691
24692    #[test]
24693    fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
24694        // The three-member happy-path fixture sets timeout + retries +
24695        // mtls_required — every populated axis must read non-empty.
24696        // Pin the round-trip so the M3.x per-:politicas emitter (the
24697        // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
24698        // on is_empty() to decide whether to emit at all without
24699        // re-deriving the contract from inline field probes.
24700        assert!(!three_member_spec().politicas.is_empty());
24701    }
24702
24703    // ── shared duration codec: cross-slot integer-magnitude gate ──
24704    //
24705    // The integer-magnitude discipline applied to
24706    // `supervisor::duration_codec::parse` lifts onto every typed slot
24707    // that routes through the shared codec — `MeshPolicy::timeout`
24708    // (`:politicas :timeout`) and `CircuitBreaker::window`
24709    // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
24710    // These cross-slot tests pin that the gate fires at the serde
24711    // layer for both typed slots, not just for the supervisor side.
24712
24713    #[test]
24714    fn policy_timeout_serde_rejects_fractional_seconds() {
24715        // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
24716        // so the shared codec's integer-magnitude gate applies on
24717        // deserialize. `"1.5s"` previously parsed to 1500ms and round-
24718        // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
24719        // deserialize with the canonical-form diagnostic naming the
24720        // offending `"1.5"` and the remediation `"1500ms"`.
24721        let payload = r#"{"timeout":"1.5s"}"#;
24722        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24723        let msg = err.to_string();
24724        assert!(
24725            msg.contains("not a non-negative integer"),
24726            "expected integer-magnitude diagnostic in {msg:?}"
24727        );
24728        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
24729        assert!(
24730            msg.contains("\"1500ms\""),
24731            "missing canonical-form remediation in {msg:?}"
24732        );
24733    }
24734
24735    #[test]
24736    fn policy_timeout_serde_rejects_leading_plus_sign() {
24737        // Pin the leading-`+` arm cross-slot — the prior f64 parser
24738        // accepted `"+30s"` silently and round-tripped to `"30s"`.
24739        let payload = r#"{"timeout":"+30s"}"#;
24740        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24741        let msg = err.to_string();
24742        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
24743    }
24744
24745    #[test]
24746    fn circuit_breaker_window_serde_rejects_fractional_minutes() {
24747        // `CircuitBreaker::window` uses `with =
24748        // "supervisor::duration_codec_required"` (the required-Duration
24749        // variant that delegates to the same shared parser). `"0.5m"`
24750        // parsed to 30s and round-tripped to `"30s"` on next emit —
24751        // DRIFT closed.
24752        let payload = format!(
24753            r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
24754            max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
24755            window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
24756        );
24757        let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
24758        let msg = err.to_string();
24759        assert!(
24760            msg.contains("not a non-negative integer"),
24761            "expected integer-magnitude diagnostic in {msg:?}"
24762        );
24763        assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
24764        assert!(
24765            msg.contains("\"30s\""),
24766            "missing canonical-form remediation in {msg:?}"
24767        );
24768    }
24769
24770    #[test]
24771    fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
24772        // Pin the happy-path on the cross-slot side: every canonical
24773        // author shape `render` ever emits parses cleanly through the
24774        // shared codec on the `CircuitBreaker` slot. The
24775        // codec's accepted set (post-gate) is exactly its emitted set
24776        // for the integer-magnitude class.
24777        for window_lit in ["30s", "500ms", "2m", "1h"] {
24778            let payload = format!(
24779                r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
24780                max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
24781                window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
24782            );
24783            let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
24784                panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
24785            });
24786            assert_eq!(cb.max_failures, 5);
24787        }
24788    }
24789
24790    // ── rate_limit_codec: integer-magnitude gate ──
24791    //
24792    // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
24793    // / 737a676 / d53c922 trajectory landed on every typed-duration /
24794    // typed-byte-size codec in caixa-core lifts onto the fifth typed
24795    // codec — `rate_limit_codec` — through the digit-only magnitude
24796    // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
24797    // These tests pin the gate at the serde layer for `:politicas
24798    // :rate-limit` (the only typed slot the codec backs), and at the
24799    // codec-internal `parse` layer for the canonical positive cases.
24800
24801    #[test]
24802    fn rate_limit_serde_rejects_fractional_rate() {
24803        // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
24804        // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
24805        // wording, which didn't name the canonical-form remediation or
24806        // the round-trip drift the next emit would produce. Now refused
24807        // at deserialize with the canonical-form diagnostic naming the
24808        // offending `"1.5"` magnitude and the round-trip drift wording.
24809        let payload = r#"{"rateLimit":"1.5/s"}"#;
24810        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24811        let msg = err.to_string();
24812        assert!(
24813            msg.contains("not a non-negative integer"),
24814            "expected integer-magnitude diagnostic in {msg:?}"
24815        );
24816        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
24817        assert!(
24818            msg.contains("THEORY.md"),
24819            "missing render-determinism contract citation in {msg:?}"
24820        );
24821    }
24822
24823    #[test]
24824    fn rate_limit_serde_rejects_leading_plus_sign() {
24825        // `u32::from_str("+100")` returns `Ok(100)` (Rust's
24826        // permissive-`+` parse), so `"+100/s"` silently parsed to
24827        // `RateLimit { 100, 1s }` and round-tripped through `render` to
24828        // `"100/s"` — a *different* canonical string on the next emit,
24829        // breaking the THEORY.md Part V render-determinism contract
24830        // exactly the way the peer duration codecs' `"+30s"` case did.
24831        // This is the load-bearing class the digit-only gate closes
24832        // beyond what `u32::from_str`'s strictness covers on its own.
24833        let payload = r#"{"rateLimit":"+100/s"}"#;
24834        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24835        let msg = err.to_string();
24836        assert!(
24837            msg.contains("not a non-negative integer"),
24838            "expected integer-magnitude diagnostic in {msg:?}"
24839        );
24840        assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
24841    }
24842
24843    #[test]
24844    fn rate_limit_serde_rejects_leading_minus_sign() {
24845        // The signed-negative arm: `"-1/s"` lands on the
24846        // non-canonical-but-numeric branch via the `i64` fallback (the
24847        // `f64` parse also succeeds), surfacing the canonical-form
24848        // diagnostic. Replaces the prior value-laundered "not a u32"
24849        // wording with the unified diagnostic across signs.
24850        let payload = r#"{"rateLimit":"-1/s"}"#;
24851        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24852        let msg = err.to_string();
24853        assert!(
24854            msg.contains("not a non-negative integer"),
24855            "expected integer-magnitude diagnostic in {msg:?}"
24856        );
24857        assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
24858    }
24859
24860    #[test]
24861    fn rate_limit_serde_rejects_decimal_shaped_integer() {
24862        // `"100.0/s"` is integer-valued numerically but not in the
24863        // codec's accepted set — `render` emits `"100/s"`, so the
24864        // round-trip would drift. Lifted to the canonical-form
24865        // diagnostic peer with the duration codec's `"1.0s"` case
24866        // (1c55a2a).
24867        let payload = r#"{"rateLimit":"100.0/s"}"#;
24868        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24869        let msg = err.to_string();
24870        assert!(
24871            msg.contains("not a non-negative integer"),
24872            "expected integer-magnitude diagnostic in {msg:?}"
24873        );
24874        assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
24875    }
24876
24877    #[test]
24878    fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
24879        // Non-numeric, non-digit-only input lands on the existing
24880        // narrower `"not a u32"` arm (preserved for diagnostic-shape
24881        // stability on the parser-shape footgun case). Pin this so a
24882        // future relaxation of the numeric-fallback predicate doesn't
24883        // silently collapse garbage onto the canonical-form arm — same
24884        // partition the peer duration codecs draw between
24885        // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
24886        let payload = r#"{"rateLimit":"abc/s"}"#;
24887        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24888        let msg = err.to_string();
24889        assert!(
24890            msg.contains("not a u32"),
24891            "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
24892        );
24893        assert!(
24894            !msg.contains("not a non-negative integer"),
24895            "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
24896        );
24897    }
24898
24899    #[test]
24900    fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
24901        // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
24902        // u32's range. The digit-only gate passes; `u32::from_str`
24903        // fails on overflow. Surface that with the overflow-shaped
24904        // diagnostic naming the offending magnitude verbatim, peer
24905        // with `supervisor::duration_codec`'s overflow arm. Pinning
24906        // the wording so a future refactor doesn't silently collapse
24907        // overflow onto the canonical-form arm.
24908        let payload = r#"{"rateLimit":"4294967296/s"}"#;
24909        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24910        let msg = err.to_string();
24911        assert!(
24912            msg.contains("overflows u32"),
24913            "expected overflow diagnostic in {msg:?}"
24914        );
24915        assert!(
24916            msg.contains("\"4294967296\""),
24917            "missing offending magnitude in {msg:?}"
24918        );
24919    }
24920
24921    #[test]
24922    fn rate_limit_serde_rejects_leading_zero_magnitude() {
24923        // `"0100/s"` is digit-only, so the existing
24924        // non-digit-only / sign / fractional arm doesn't catch it —
24925        // `u32::from_str("0100")` returns `Ok(100)`, so before this
24926        // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
24927        // round-tripped through `render` to `"100/s"` — a *different*
24928        // canonical string on the next emit, breaking the THEORY.md
24929        // Part V render-determinism contract exactly the way the
24930        // peer `"+100/s"` case did before the leading-`+` arm landed.
24931        // This is the load-bearing class the leading-zero gate closes
24932        // beyond what the existing digit-only / sign / fractional
24933        // gates cover, and the peer arm to the leading-`+` test
24934        // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
24935        // canonical-form-drift axis.
24936        let payload = r#"{"rateLimit":"0100/s"}"#;
24937        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24938        let msg = err.to_string();
24939        assert!(
24940            msg.contains("non-canonical leading zero"),
24941            "expected leading-zero diagnostic in {msg:?}"
24942        );
24943        assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
24944        assert!(
24945            msg.contains("THEORY.md"),
24946            "missing render-determinism contract citation in {msg:?}"
24947        );
24948    }
24949
24950    #[test]
24951    fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
24952        // `"00/s"` is the degenerate leading-zero case — every byte
24953        // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
24954        // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
24955        // a *different* canonical string, same render-determinism
24956        // violation. The single-byte `"0/s"` itself is in the
24957        // accepted set (round-trips losslessly through `render`,
24958        // refused downstream by `PolicyRateLimitZero`); the
24959        // multi-byte `"00/s"` is not. Pins the boundary between the
24960        // accepted single-`0` and the rejected leading-zero class.
24961        let payload = r#"{"rateLimit":"00/s"}"#;
24962        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24963        let msg = err.to_string();
24964        assert!(
24965            msg.contains("non-canonical leading zero"),
24966            "expected leading-zero diagnostic in {msg:?}"
24967        );
24968        assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
24969    }
24970
24971    #[test]
24972    fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
24973        // Cross-window pin — the gate is window-agnostic; the
24974        // leading-zero class is a property of the magnitude, not the
24975        // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
24976        // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
24977        // single-window coverage extended across the three canonical
24978        // windows the codec accepts.
24979        let payload = r#"{"rateLimit":"007/h"}"#;
24980        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24981        let msg = err.to_string();
24982        assert!(
24983            msg.contains("non-canonical leading zero"),
24984            "expected leading-zero diagnostic in {msg:?}"
24985        );
24986        assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
24987    }
24988
24989    #[test]
24990    fn rate_limit_serde_rejects_leading_whitespace() {
24991        // `" 100/s"` — the canonical paste-from-aligned-doc /
24992        // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
24993        // the top-level `s.trim()` silently ate the leading space and
24994        // parsed the value to `RateLimit { 100, 1s }`, which then
24995        // round-tripped through `render` to `"100/s"` (a *different*
24996        // canonical string on the next emit) — the exact
24997        // canonical-form-drift class the leading-`+` / leading-zero
24998        // arms already close, extended to the whitespace byte class.
24999        let payload = r#"{"rateLimit":" 100/s"}"#;
25000        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
25001        let msg = err.to_string();
25002        assert!(
25003            msg.contains("contains whitespace byte"),
25004            "expected whitespace diagnostic in {msg:?}"
25005        );
25006        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
25007        assert!(
25008            msg.contains("THEORY.md"),
25009            "missing render-determinism contract citation in {msg:?}"
25010        );
25011    }
25012
25013    #[test]
25014    fn rate_limit_serde_rejects_trailing_whitespace() {
25015        // `"100/s "` — the canonical shell-history / trailing-space
25016        // paste footgun. Before this gate the top-level `s.trim()`
25017        // silently ate the trailing space and parsed to
25018        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
25019        // next emit — same canonical-form drift as the leading-space
25020        // sibling, closed on the same whitespace-byte arm.
25021        let payload = r#"{"rateLimit":"100/s "}"#;
25022        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
25023        let msg = err.to_string();
25024        assert!(
25025            msg.contains("contains whitespace byte"),
25026            "expected whitespace diagnostic in {msg:?}"
25027        );
25028        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
25029    }
25030
25031    #[test]
25032    fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
25033        // `"100 / s"` — the canonical typographically-spaced author
25034        // shape (the same idiom every prose reference to a rate limit
25035        // renders as, mistakenly retained when the value is pasted
25036        // into a codec-shaped slot). Before this gate the per-part
25037        // `rate_str.trim()` / `unit.trim()` calls silently ate both
25038        // spaces on either side of `/` and parsed to
25039        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
25040        // codec's *internal* whitespace-tolerance vector, orthogonal
25041        // to the leading / trailing surface but the same canonical-
25042        // form-drift class. Pins the arm as strictly stronger than the
25043        // pre-existing top-level `s.trim()` behavior: it fires on
25044        // whitespace anywhere in the value, not just at the string
25045        // boundary.
25046        let payload = r#"{"rateLimit":"100 / s"}"#;
25047        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
25048        let msg = err.to_string();
25049        assert!(
25050            msg.contains("contains whitespace byte"),
25051            "expected whitespace diagnostic in {msg:?}"
25052        );
25053        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
25054    }
25055
25056    #[test]
25057    fn rate_limit_serde_rejects_tab_byte() {
25058        // `"\t100/s"` — the canonical paste-from-indented-doc /
25059        // paste-from-YAML-block-scalar footgun where a tab byte leads
25060        // the magnitude. Pins that the gate covers tab (`0x09`) as
25061        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
25062        // members and both would be silently swallowed by `s.trim()`
25063        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
25064        // space alone to the full ASCII-whitespace set (space `0x20`,
25065        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
25066        // the tab arm as a representative of the non-space members.
25067        let payload = r#"{"rateLimit":"\t100/s"}"#;
25068        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
25069        let msg = err.to_string();
25070        assert!(
25071            msg.contains("contains whitespace byte"),
25072            "expected whitespace diagnostic in {msg:?}"
25073        );
25074        assert!(
25075            msg.contains("0x09"),
25076            "missing offending tab byte in {msg:?}"
25077        );
25078    }
25079
25080    // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
25081    //
25082    // Successor to the ASCII-whitespace arm (1ad7755) on
25083    // `rate_limit_codec` — closes the strictly-complementary class the
25084    // byte-scan cannot see, through the lifted
25085    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
25086
25087    #[test]
25088    fn rate_limit_serde_rejects_leading_nbsp() {
25089        // NBSP prefix — paste-from-typography footgun. Byte-scan
25090        // misses, `str::trim` silently strips it, value drifts to
25091        // `"100/s"` on next serialize.
25092        let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
25093        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
25094        let msg = err.to_string();
25095        assert!(
25096            msg.contains("non-ASCII Unicode whitespace character"),
25097            "expected non-ASCII whitespace diagnostic in {msg:?}"
25098        );
25099        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
25100    }
25101
25102    #[test]
25103    fn rate_limit_serde_rejects_internal_em_space() {
25104        // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
25105        // paste-from-typography footgun on the `<integer>/<unit>`
25106        // shape.
25107        let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
25108        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
25109        let msg = err.to_string();
25110        assert!(
25111            msg.contains("non-ASCII Unicode whitespace character"),
25112            "expected non-ASCII whitespace diagnostic in {msg:?}"
25113        );
25114        assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
25115    }
25116
25117    #[test]
25118    fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
25119        // Positive-control pin: every ASCII-only canonical form the
25120        // renderer emits stays accepted through the new arm.
25121        for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
25122            let payload = format!(r#"{{"rateLimit":{lit}}}"#);
25123            let p: MeshPolicy = serde_json::from_str(&payload)
25124                .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
25125            assert!(p.rate_limit.is_some());
25126        }
25127    }
25128
25129    #[test]
25130    fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
25131        // The boundary case — `"0/s"` is the canonical form
25132        // `render(RateLimit { 0, 1s })` emits, so the codec accepts
25133        // it at the parse layer; the downstream
25134        // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
25135        // `rate == 0` at the typed-validate layer above. Pins the
25136        // partition: the leading-zero gate at the codec layer does
25137        // not poach the rate-zero semantic-validation arm at the
25138        // typed-validate layer above (a future stricter codec must
25139        // not reject `"0/s"` here, or it'd collapse the diagnostic
25140        // partitioning that lets `PolicyRateLimitZero` name the
25141        // offending typed slot).
25142        let payload = r#"{"rateLimit":"0/s"}"#;
25143        let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
25144            panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
25145        });
25146        let rl = policy.rate_limit.expect("rate_limit must be Some");
25147        assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
25148        assert_eq!(
25149            rl.window,
25150            Duration::from_secs(1),
25151            "single-`0` magnitude with `s` unit must parse to window=1s"
25152        );
25153    }
25154
25155    #[test]
25156    fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
25157        // The complementary boundary pin — every magnitude
25158        // `render` emits starts with `[1-9]` (or is the single byte
25159        // `"0"`), so the canonical-form predicate is `(len == 1) ||
25160        // (first byte != '0')`. Pinning the `len > 1 && first byte ==
25161        // '1'` case explicitly so a future tightening of the gate
25162        // (e.g. an over-eager "no leading digit < 5" rule, or a
25163        // mistakenly anchored start-of-magnitude byte check) lands
25164        // here before the canonical-forms-iterating test would catch
25165        // it.
25166        let payload = r#"{"rateLimit":"100/s"}"#;
25167        let policy: MeshPolicy = serde_json::from_str(payload)
25168            .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
25169        let rl = policy.rate_limit.expect("rate_limit must be Some");
25170        assert_eq!(
25171            rl.rate, 100,
25172            "canonical-100 magnitude must parse to rate=100"
25173        );
25174    }
25175
25176    #[test]
25177    fn rate_limit_serde_accepts_integer_canonical_forms() {
25178        // Pin the happy-path: every canonical author shape `render`
25179        // ever emits parses cleanly through the codec post-gate. The
25180        // codec's accepted set (post-gate) is exactly its emitted set
25181        // for the integer-magnitude class — same property
25182        // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
25183        // gates guarantee on the peer codecs. Iterating across rate
25184        // magnitudes (including `"0"`, which the codec accepts even
25185        // though `validate_politicas` rejects `rate == 0` at the typed
25186        // layer above) closes the codec contract at the parse layer
25187        // independently of the validate layer.
25188        for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
25189            for unit_lit in ["s", "m", "h"] {
25190                let lit = format!("{rate_lit}/{unit_lit}");
25191                let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
25192                let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
25193                    panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
25194                });
25195                let rl = policy.rate_limit.expect("rate_limit must be Some");
25196                assert_eq!(
25197                    rl.rate,
25198                    rate_lit.parse::<u32>().unwrap(),
25199                    "rate mismatch for {lit:?}"
25200                );
25201            }
25202        }
25203    }
25204
25205    #[test]
25206    fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
25207        // The structural property the gate enforces: serialize ∘
25208        // deserialize is the identity on every canonical author shape.
25209        // Peer of `parse_byte_size`'s and `parse_duration`'s
25210        // `_round_trips_through_render_for_every_canonical_form` tests
25211        // on the rate-limit axis. Before the gate, `"+100/s"` violated
25212        // this (`parse` → `RateLimit { 100, 1s }` → `render` →
25213        // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
25214        for rate in [1u32, 100, 5000, 1_000_000] {
25215            for (window, unit) in [
25216                (Duration::from_secs(1), "s"),
25217                (Duration::from_secs(60), "m"),
25218                (Duration::from_secs(3600), "h"),
25219            ] {
25220                let policy = MeshPolicy {
25221                    rate_limit: Some(RateLimit { rate, window }),
25222                    ..Default::default()
25223                };
25224                let json = serde_json::to_string(&policy).unwrap();
25225                let expected = format!("\"{rate}/{unit}\"");
25226                assert!(
25227                    json.contains(&expected),
25228                    "expected {expected:?} in {json:?}"
25229                );
25230                let back: MeshPolicy = serde_json::from_str(&json).unwrap();
25231                assert_eq!(
25232                    back.rate_limit, policy.rate_limit,
25233                    "round-trip for {json:?}"
25234                );
25235            }
25236        }
25237    }
25238
25239    // ── self-membership cross-slot gate ──────────────────────────────
25240
25241    #[test]
25242    fn validate_no_self_membership_rejects_self_named_membro() {
25243        // An Aplicacao whose `:membros` lists its own `:nome` is a
25244        // one-node lacre-closure recursion — rejected, naming the parent.
25245        let membros = vec![
25246            membro("catalog", "^0.1"),
25247            membro("checkout", "^0.1"),
25248            membro("cart", "^0.1"),
25249        ];
25250        let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
25251        assert!(
25252            matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
25253            "got {err:?}"
25254        );
25255    }
25256
25257    #[test]
25258    fn validate_no_self_membership_accepts_distinct_membros() {
25259        // Positive control: distinct member names (including a member
25260        // that is itself an Aplicacao — recursive composition is valid,
25261        // MESH-COMPOSITION §V) pass the gate.
25262        let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
25263        validate_no_self_membership(&membros, "checkout").unwrap();
25264    }
25265
25266    #[test]
25267    fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
25268        // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
25269        // `NoMembros` arm (the more-fundamental "graph must have nodes"
25270        // gate), not by this cross-slot self-edge gate. Keeping the
25271        // self-membership predicate vacuously-ok on the empty input
25272        // matches its supervisor-axis peer
25273        // (`validate_no_self_supervision_empty_children_is_ok`) and
25274        // makes the gate composable from any future call site (an M4
25275        // CR materializer's per-membros validator) without re-checking
25276        // emptiness.
25277        validate_no_self_membership(&[], "checkout").unwrap();
25278    }
25279
25280    #[test]
25281    fn validate_no_self_membership_diagnostic_names_offending_caixa() {
25282        // Pinning the Display: the self-membership diagnostic must name
25283        // the offending caixa verbatim + the "lists itself" framing the
25284        // author can grep for, so the cluster-far failure surfaces at
25285        // build time with one-line remediation. Same diagnostic shape
25286        // as the supervisor-axis `ChildSupervisesSelf` peer.
25287        let membros = vec![membro("orquestra", "^0.1")];
25288        let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
25289        let msg = err.to_string();
25290        assert!(
25291            msg.contains("orquestra"),
25292            "diagnostic must name the offending caixa nome (got: {msg:?})"
25293        );
25294        assert!(
25295            msg.contains("lists itself"),
25296            "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
25297        );
25298    }
25299
25300    #[test]
25301    fn default_servico_port_constant_pins_canonical_8080_literal() {
25302        // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
25303        // at the verbatim `8080` literal both consumers (the
25304        // `Entrada::port` serde default via [`default_port`] and the
25305        // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
25306        // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
25307        // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
25308        // discipline (a085b26) on the per-renderer canonical-K8s-axis
25309        // string-constant axis: a future refactor that drifts the
25310        // constant out from under either consumer surfaces here ahead
25311        // of every per-renderer's first emission. The literal value
25312        // matches the well-known HTTP-alt port the `pleme-computeunit`
25313        // library chart already emits as its `trigger.service.port`
25314        // default — by construction the same value the substrate
25315        // assumes about every Servico's in-cluster L4 listener.
25316        assert_eq!(
25317            DEFAULT_SERVICO_PORT, 8080,
25318            "canonical Servico port literal must remain `8080` verbatim — \
25319             this is the value both the `Entrada::port` serde default and the \
25320             caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
25321        );
25322    }
25323
25324    #[test]
25325    fn default_port_helper_returns_canonical_servico_port_constant() {
25326        // The bridge-arm — pins that the [`default_port`] helper
25327        // [`Entrada::port`]'s `#[serde(default = "default_port")]`
25328        // attribute hooks routes through the lifted
25329        // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
25330        // literal. A future refactor that re-introduces the `8080`
25331        // literal at the helper's return site (silently re-opening
25332        // the drift footgun this lift closed) surfaces here ahead of
25333        // every author-side `(:entrada (:host … :para …))` slot
25334        // without an explicit `:port`. Peer with the
25335        // `default_namespace_re_export_points_at_caixa_core_canonical`
25336        // pin on the caixa-mesh-side re-export axis.
25337        assert_eq!(
25338            default_port(),
25339            DEFAULT_SERVICO_PORT,
25340            "the serde-default helper must route through the lifted constant"
25341        );
25342    }
25343
25344    #[test]
25345    fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
25346        // The end-to-end pin — an author-surface `(:entrada (:host …
25347        // :para …))` without an explicit `:port` slot deserializes to
25348        // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
25349        // verbatim. Routes the canonical lifted constant through both
25350        // the serde-default machinery (the `#[serde(default =
25351        // "default_port")]` attribute) and the typed-value-shape
25352        // contract (the resulting [`Entrada::port`] value). A future
25353        // refactor that drifts either axis — replacing the serde
25354        // hook's helper, changing the typed slot's wire shape — would
25355        // surface here before any per-renderer's CNP / Gateway /
25356        // HTTPRoute emission consumed the drifted default.
25357        let entrada: Entrada =
25358            serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
25359        assert_eq!(
25360            entrada.port, DEFAULT_SERVICO_PORT,
25361            "the serde default must materialize as the lifted canonical Servico port"
25362        );
25363    }
25364
25365    #[test]
25366    fn servico_port_min_pins_canonical_accept_set_floor() {
25367        // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
25368        // verbatim `1` literal every typed `:entrada :port` acceptance
25369        // gate keys off. Peer with the
25370        // [`default_servico_port_constant_pins_canonical_8080_literal`]
25371        // discipline on the canonical-Servico-port-constant axis: a
25372        // future refactor that drifts the accept-set floor out from
25373        // under the sole consumer at [`AplicacaoSpec::validate`]'s
25374        // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
25375        // every per-`:entrada` `EntradaPortZero` diagnostic. The
25376        // literal value matches the IANA-registered TCP/UDP port
25377        // space floor (`1..=65535` — port `0` is the "any ephemeral"
25378        // sentinel, not a well-defined destination the substrate's
25379        // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
25380        // axis can honor).
25381        assert_eq!(
25382            SERVICO_PORT_MIN, 1,
25383            "canonical Servico port accept-set floor must remain `1` verbatim — \
25384             this is the value the `AplicacaoSpec::validate` gate at \
25385             `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
25386        );
25387    }
25388
25389    #[test]
25390    fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
25391        // The cross-const invariant pin — the substrate's canonical
25392        // default port must satisfy its own accept-set floor by
25393        // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
25394        // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
25395        // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
25396        // override the operator pins through a future
25397        // `:placement :default-port` slot that lands out-of-range, a
25398        // per-edition Servico-port migration that lifted the floor
25399        // above the previous default without coordinating the pair —
25400        // would silently invalidate the serde-default emission at
25401        // every author-side `(:entrada (:host … :para …))` slot
25402        // without an explicit `:port`: the default port would fall
25403        // below the accept-set floor, the `AplicacaoSpec::validate`
25404        // gate would reject every default-carrying Aplicacao as
25405        // `EntradaPortZero`, and the substrate's typed
25406        // `(defcaixa … :kind Aplicacao)` surface would fail validate
25407        // on every Aplicacao whose author omitted `:entrada :port`
25408        // for the substrate's chosen default — a class of authoring-
25409        // surface footguns the compile-time pin structurally closes.
25410        // Peer with the
25411        // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
25412        // (27f9b34) cross-const invariant pin discipline on the peer
25413        // canonical-Helm-per-values-block child-chart-enablement-toggle
25414        // axis pair.
25415        const {
25416            assert!(
25417                SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
25418                "the substrate's canonical default port DEFAULT_SERVICO_PORT \
25419                 must satisfy its own accept-set floor SERVICO_PORT_MIN — \
25420                 every default-carrying `(:entrada (:host … :para …))` slot \
25421                 without an explicit `:port` inherits `DEFAULT_SERVICO_PORT` \
25422                 through the serde default hook and must pass the \
25423                 `AplicacaoSpec::validate` floor gate by construction",
25424            );
25425        }
25426    }
25427
25428    #[test]
25429    fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
25430        // The gate-site pin — asserts the `AplicacaoSpec::validate`
25431        // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
25432        // `EntradaPortZero` diagnostic on the below-floor input
25433        // `port: 0` (the only below-floor value the `u16` field can
25434        // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
25435        // is the singleton `{0}`). A future refactor that drifts the
25436        // gate off the lifted const (silently re-introducing an
25437        // inline `if e.port == 0` byte-check) surfaces here — the
25438        // pin cannot distinguish `< 1` from `== 0` on the current
25439        // floor, but it *does* pin that the diagnostic fires on `0`
25440        // through whichever gate is wired, so any future accept-set
25441        // floor migration (a hypothetical unprivileged-only
25442        // migration lifting `SERVICO_PORT_MIN` to `1024`) must
25443        // update this test alongside the const declaration —
25444        // structurally guaranteeing the gate + accept-set + pin
25445        // trio move together. Peer with the
25446        // [`rejects_zero_entrada_port`] behavioral pin on the same
25447        // per-`:entrada :port` axis — that pin asserts the pre-lift
25448        // behavioral contract (`port: 0` → `EntradaPortZero`); this
25449        // pin adds the structural link to the lifted floor const.
25450        assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
25451        let mut s = three_member_spec();
25452        s.entrada.as_mut().unwrap().port = 0;
25453        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
25454    }
25455
25456    // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
25457
25458    #[test]
25459    fn membro_serde_keys_match_lifted_membro_key_consts() {
25460        // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
25461        // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
25462        // name the exact camelCase JSON keys the
25463        // `#[serde(rename_all = "camelCase")]` attribute on
25464        // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
25465        // that each canonical byte-sequence appears verbatim in the
25466        // JSON — a future accidental `rename_all = "snake_case"` /
25467        // `"kebab-case"` / verbatim-field-name flip at the derive
25468        // attribute (any of which would silently break every downstream
25469        // JSON consumer that reaches for one of the two consts via
25470        // `Value::get(...)`) surfaces here as a build-time test failure
25471        // at `aplicacao.rs`, not as an apply-time
25472        // `.get(<stale-canonical-const>)` returning `None` far from the
25473        // derive-attr drift's commit. Peer with the sibling
25474        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
25475        // (40cc4e5) pin on the M2 supervision-tree top-level axis —
25476        // same discipline the SupervisorSpec top-level lift established,
25477        // extended here to the M3 [`Membro`] per-`:membros` axis.
25478        let m = Membro {
25479            caixa: "catalog".into(),
25480            versao: "^0.1".into(),
25481        };
25482        let json = serde_json::to_string(&m).unwrap();
25483        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
25484            let quoted = format!("\"{key}\"");
25485            assert!(
25486                json.contains(&quoted),
25487                "serialized Membro must carry the lifted MEMBRO_KEY_* \
25488                 byte-sequence {quoted} verbatim in the JSON emission \
25489                 (got: {json})",
25490            );
25491        }
25492    }
25493
25494    #[test]
25495    fn membro_key_consts_are_pairwise_distinct() {
25496        // Cross-axis drift-detection pin: a future collapse of the two
25497        // canonical [`Membro`] per-entry byte-strings onto the same
25498        // value (e.g. an accidental copy-paste flip of
25499        // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
25500        // silently reroute every downstream probe on one axis onto the
25501        // sibling axis's overlay entry and pass every propagation-probe
25502        // test that expected only the stale axis's value. Peer of the
25503        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
25504        // (40cc4e5).
25505        let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
25506        for (i, a) in all.iter().enumerate() {
25507            for b in all.iter().skip(i + 1) {
25508                assert_ne!(
25509                    a, b,
25510                    "MEMBRO_KEY_* consts must be pairwise-distinct \
25511                     canonical byte-sequences — got `{a}` == `{b}`",
25512                );
25513            }
25514        }
25515    }
25516
25517    // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
25518    //    URL-path fallback resolver every HTTPRoute-aware renderer
25519    //    reaching for a per-rule path-list resolution routes through.
25520    //    The four pin tests below fix the four-way accept-set the
25521    //    resolver must always honor: (:paths-non-empty-verbatim,
25522    //    :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
25523    //    :paths-preserves-order-across-multiple-entries) — drift on any
25524    //    arm surfaces at caixa-core build time rather than at cluster-
25525    //    apply time. Peer discipline with `MeshPolicy::is_empty` on the
25526    //    sibling `:politicas` typed-primitive dispatch axis.
25527
25528    fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
25529        Entrada {
25530            host: "example.com".into(),
25531            para: "cart".into(),
25532            paths: paths.into_iter().map(String::from).collect(),
25533            port: DEFAULT_SERVICO_PORT,
25534        }
25535    }
25536
25537    #[test]
25538    fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
25539        // The typed `:entrada :paths` slot carries an author-declared
25540        // list — the resolver returns each entry verbatim, no
25541        // catch-all substitution. The canonical "author declared
25542        // paths, honor them verbatim" arm of the path-list dispatch.
25543        let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
25544        assert_eq!(
25545            e.resolved_paths(),
25546            vec!["/api/cart", "/api/products"],
25547            "resolved_paths must return each `:entrada :paths` entry \
25548             verbatim when the typed slot is non-empty (got {:?})",
25549            e.resolved_paths(),
25550        );
25551    }
25552
25553    #[test]
25554    fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
25555        // Empty `:entrada :paths` slot — the resolver substitutes the
25556        // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
25557        // catch-all fallback verbatim. Pins the empty-arm of the
25558        // resolver's four-way accept-set against a future silent
25559        // detour that returned an empty Vec (which would emit an
25560        // HTTPRoute with zero rules — silently dropping every
25561        // external `:entrada` flow at admission time), routed to a
25562        // different fallback shape, or dropped the catch-all
25563        // altogether.
25564        let e = entrada_with_paths(vec![]);
25565        assert_eq!(
25566            e.resolved_paths(),
25567            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
25568            "resolved_paths on empty `:entrada :paths` must fall back \
25569             to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
25570             all — got {:?}",
25571            e.resolved_paths(),
25572        );
25573    }
25574
25575    #[test]
25576    fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
25577        // Single-entry `:entrada :paths` — the resolver returns the
25578        // single declared path verbatim, NOT the catch-all fallback
25579        // (author declared a path, honor it — the empty-arm and the
25580        // len-1 arm are semantically distinct axes of the resolver's
25581        // accept-set). Pins that the resolver treats "author declared
25582        // one path" as authored input, not as the empty case.
25583        let e = entrada_with_paths(vec!["/api/only"]);
25584        assert_eq!(
25585            e.resolved_paths(),
25586            vec!["/api/only"],
25587            "resolved_paths on single-entry `:entrada :paths` must \
25588             return the declared path verbatim, NOT the catch-all \
25589             fallback (got {:?})",
25590            e.resolved_paths(),
25591        );
25592    }
25593
25594    #[test]
25595    fn resolved_paths_preserves_author_declared_order() {
25596        // The `:entrada :paths` list is author-ordered — the resolver
25597        // preserves the author's declaration order verbatim, since
25598        // per-rule dispatch order at the K8s Gateway API HTTPRoute
25599        // consumer is significant (first-match-wins under the
25600        // path-prefix matcher). Pins against a future silent
25601        // re-sort / dedup / normalize detour that reordered author
25602        // input.
25603        let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
25604        assert_eq!(
25605            e.resolved_paths(),
25606            vec!["/z/last", "/a/first", "/m/mid"],
25607            "resolved_paths must preserve author-declared `:entrada \
25608             :paths` order verbatim — got {:?}",
25609            e.resolved_paths(),
25610        );
25611    }
25612
25613    // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
25614    //    slot `&[String]` slice accessor every per-`:entrada` consumer
25615    //    that must see the author's declaration verbatim (not the
25616    //    fallback-applied projection the sibling `resolved_paths`
25617    //    returns) routes through. The three pin tests below fix the
25618    //    accept-set the accessor must honor: (:non-empty-byte-equal,
25619    //    :empty-projects-empty-slice, :preserves-author-declared-order)
25620    //    — drift on any arm surfaces at caixa-core build time rather
25621    //    than at cluster-apply time. Peer discipline with the sibling
25622    //    [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
25623    //    peer M3 mesh-slot `Vec<String>`-carry axis.
25624
25625    #[test]
25626    fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
25627        // Byte-equal pin: [`Entrada::paths`] must project the raw
25628        // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
25629        // slice borrowed from the typed slot's own [`Vec<String>`]
25630        // storage — no re-ordering, no dedup, no per-entry normalization,
25631        // no fallback substitution (the fallback-applying projection is
25632        // the sibling [`Entrada::resolved_paths`] resolver). Pins against
25633        // a future silent detour that re-normalized the list, dropped
25634        // duplicates the [`AplicacaoSpec::validate`]
25635        // `EntradaPathDuplicate` refusal already rejects at build time,
25636        // or (most severe) accidentally routed through the fallback-
25637        // applying sibling and returned the substrate catch-all when
25638        // the author declared an empty list — collapsing the raw-slot
25639        // and fallback-applied axes into one and breaking the
25640        // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
25641        //
25642        // Peer of the sibling
25643        // [`Placement::clusters`]-shape byte-equal pin
25644        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
25645        // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
25646        let fixtures: Vec<Vec<String>> = vec![
25647            Vec::new(),
25648            vec!["/api/cart".into()],
25649            vec!["/api/cart".into(), "/api/products".into()],
25650            vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
25651        ];
25652        for paths in fixtures {
25653            let e = Entrada {
25654                host: "example.com".into(),
25655                para: "cart".into(),
25656                paths: paths.clone(),
25657                port: DEFAULT_SERVICO_PORT,
25658            };
25659            assert_eq!(
25660                e.paths(),
25661                paths.as_slice(),
25662                "Entrada::paths must return :entrada :paths verbatim \
25663                 (got {:?}, expected {:?})",
25664                e.paths(),
25665                paths.as_slice(),
25666            );
25667            assert_eq!(
25668                e.paths(),
25669                e.paths.as_slice(),
25670                "Entrada::paths accessor and .paths.as_slice() field \
25671                 access must byte-equal — the accessor is the substrate-\
25672                 primitive typed dispatch every downstream per-`:entrada` \
25673                 raw-slot path-list consumer must route through",
25674            );
25675            assert_eq!(
25676                e.paths().len(),
25677                e.paths.len(),
25678                "Entrada::paths().len() must byte-equal self.paths.len() \
25679                 — a length drift would silently split the paired \
25680                 pre-flight cascade-head `.is_empty()` probe input in \
25681                 the sibling [`Entrada::resolved_paths`] resolver from \
25682                 the per-entry validate loop's traversal input in \
25683                 [`AplicacaoSpec::validate`]",
25684            );
25685        }
25686    }
25687
25688    #[test]
25689    fn resolved_paths_reads_through_lifted_paths_accessor() {
25690        // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
25691        // pre-flight `.paths().is_empty()` cascade-head probe (which
25692        // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
25693        // catch-all fallback arm when the accessor projects the empty
25694        // slice) and the per-entry `.paths().iter().map(String::as_str)`
25695        // projection (which must reach every entry in the same order
25696        // the accessor projects, so the sibling
25697        // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
25698        // per-entry projection stay in lockstep by construction) must
25699        // both key off the lifted accessor. Pins the two-site coherence
25700        // by exercising each production consumer end-to-end: (1) the
25701        // catch-all-fallback arm under the empty slice, (2) the
25702        // author-declared-verbatim arm under a two-entry cohort whose
25703        // per-entry projection must byte-equal the input's per-entry
25704        // author-declared paths in the author's declared order.
25705        //
25706        // Peer of the sibling M3
25707        // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
25708        // `validate_placement_reads_through_lifted_clusters_accessor`
25709        // on the sibling `Placement::clusters` reader-site convergence.
25710        let empty = entrada_with_paths(vec![]);
25711        assert_eq!(
25712            empty.resolved_paths(),
25713            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
25714            "resolved_paths on empty :entrada :paths must trip the \
25715             lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
25716             catch-all fallback — routing through the lifted paths() \
25717             accessor must not silently drop the fallback arm",
25718        );
25719
25720        let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
25721        assert_eq!(
25722            declared.resolved_paths(),
25723            vec!["/api/cart", "/api/products"],
25724            "resolved_paths on non-empty :entrada :paths must return each \
25725             entry verbatim in the author's declared order — routing \
25726             through the lifted paths() accessor must not silently \
25727             reorder or drop entries",
25728        );
25729        // Byte-equal pin against the raw-slot accessor to keep the
25730        // fallback-applying resolver's per-entry projection input in
25731        // lockstep with the raw-slot accessor's projection.
25732        let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
25733        assert_eq!(
25734            declared.resolved_paths(),
25735            raw_projected,
25736            "resolved_paths non-empty projection must byte-equal the \
25737             lifted paths() accessor's per-entry String::as_str projection \
25738             — the two projections share the same input slice by \
25739             construction, so any drift here would surface a silent \
25740             re-ordering / dedup / normalization detour in the resolver",
25741        );
25742    }
25743
25744    #[test]
25745    fn validate_reads_through_lifted_entrada_paths_accessor() {
25746        // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
25747        // per-entry value-shape gate's `for p in e.paths()` traversal
25748        // (which must reach every entry in the same order the accessor
25749        // projects, so both the per-entry `EntradaPathEmpty` /
25750        // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
25751        // the duplicate-detection HashSet insert that trips
25752        // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
25753        // projection) must route through the lifted accessor. Pins the
25754        // coherence by exercising each production consumer end-to-end:
25755        // (1) the `EntradaPathEmpty` refusal fires on the second entry
25756        // of a two-entry cohort whose head is valid but tail is empty
25757        // (which requires the loop to reach the second entry through
25758        // the accessor), and (2) the `EntradaPathDuplicate` refusal
25759        // fires on the second entry of a two-entry cohort that shares
25760        // a path (which requires the loop to reach both entries — a
25761        // first-entry-only projection would silently pass since the
25762        // dedup HashSet has room for the first insert).
25763        //
25764        // Peer of the sibling
25765        // `validate_placement_reads_through_lifted_clusters_accessor`
25766        // on the sibling `Placement::clusters` reader-site convergence.
25767        let base = crate::AplicacaoSpec {
25768            membros: vec![crate::Membro {
25769                caixa: "cart".into(),
25770                versao: "^0.1".into(),
25771            }],
25772            contratos: Vec::new(),
25773            politicas: crate::MeshPolicy::default(),
25774            placement: crate::Placement {
25775                estrategia: crate::PlacementStrategy::SingleNode,
25776                clusters: vec!["rio".into()],
25777                shard_key: None,
25778                affinity: None,
25779            },
25780            entrada: Some(Entrada {
25781                host: "example.com".into(),
25782                para: "cart".into(),
25783                paths: vec!["/api/cart".into(), String::new()],
25784                port: DEFAULT_SERVICO_PORT,
25785            }),
25786        };
25787        assert_eq!(
25788            base.validate(),
25789            Err(crate::AplicacaoError::EntradaPathEmpty),
25790            "validate must trip EntradaPathEmpty on the second entry of \
25791             a two-entry cohort — routing through the lifted paths() \
25792             accessor must not silently short-circuit the loop at the \
25793             valid head entry",
25794        );
25795
25796        let mut dup = base;
25797        dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
25798        assert_eq!(
25799            dup.validate(),
25800            Err(crate::AplicacaoError::EntradaPathDuplicate {
25801                path: "/api/cart".into(),
25802            }),
25803            "validate must trip EntradaPathDuplicate on the second entry \
25804             of a two-entry cohort that shares a path — routing through \
25805             the lifted paths() accessor must not silently short-circuit \
25806             the dedup HashSet insert at the first entry",
25807        );
25808    }
25809
25810    // ── Entrada::hostname / Entrada::hostnames — the substrate-
25811    //    canonical per-`:entrada` DNS-hostname resolver pair every
25812    //    Gateway-API-aware renderer reaching for a per-listener
25813    //    singular `hostname:` filter (Gateway) or a per-route plural
25814    //    `spec.hostnames[]` filter list (HTTPRoute) routes through.
25815    //    The three pin tests below fix the two-way accept-set the pair
25816    //    must always honor: (:singular-byte-equal-to-host,
25817    //    :plural-is-singleton-of-singular, :plural-len-is-one) — drift
25818    //    on any arm surfaces at caixa-core build time rather than at
25819    //    cluster-apply time when the API server refuses the HTTPRoute
25820    //    for non-intersecting hostname filters. Peer discipline with
25821    //    the sibling `resolved_paths` accept-set pin block above on the
25822    //    per-`:entrada` path-list resolver axis.
25823
25824    fn entrada_with_host(host: &str) -> Entrada {
25825        Entrada {
25826            host: host.into(),
25827            para: "cart".into(),
25828            paths: Vec::new(),
25829            port: DEFAULT_SERVICO_PORT,
25830        }
25831    }
25832
25833    #[test]
25834    fn hostname_returns_entrada_host_byte_equal() {
25835        // The canonical singular-axis pin: [`Entrada::hostname`] must
25836        // return the `:entrada :host` field byte-for-byte, borrowed
25837        // from the typed slot's own [`String`] storage. Pins against a
25838        // future silent detour that re-normalized the host (an
25839        // accidental `.to_lowercase()` — validate_entrada_host already
25840        // enforces lowercase, so any re-normalization is redundant + a
25841        // drift surface between the validator and the accessor), a
25842        // trailing-`.` fully-qualified DNS shape substitution, or a
25843        // Punycode round-trip that lowered a Unicode host through IDNA.
25844        let e = entrada_with_host("checkout.quero.cloud");
25845        assert_eq!(
25846            e.hostname(),
25847            "checkout.quero.cloud",
25848            "Entrada::hostname must return :entrada :host verbatim \
25849             (got {:?})",
25850            e.hostname(),
25851        );
25852        assert_eq!(
25853            e.hostname(),
25854            e.host.as_str(),
25855            "Entrada::hostname must byte-equal the .host field access",
25856        );
25857    }
25858
25859    #[test]
25860    fn hostnames_returns_singleton_of_hostname_accessor() {
25861        // The pair-invariant pin: [`Entrada::hostnames`] must always
25862        // return exactly `vec![hostname()]` — the singleton list whose
25863        // sole entry is the substrate's canonical per-`:entrada`
25864        // singular hostname. Pins the two-consumer coherence axis: the
25865        // Gateway listener's singular `hostname:` filter and the
25866        // HTTPRoute's plural `spec.hostnames[]` filter list must
25867        // agree, else the Gateway API v1.x conformance layer rejects
25868        // the HTTPRoute at attach time with
25869        // `Accepted:False/NoMatchingParent` (the parent Gateway's
25870        // listener hostname doesn't intersect the route's hostname
25871        // filter list) — a divergence whose apply-time symptom is far
25872        // from any single-site commit and never surfaces in the
25873        // emitted YAML. Pinning the pair-invariant here makes any
25874        // future accidental split (an accidental `.to_string() + "."`
25875        // trailing-`.` on the plural side that didn't land on the
25876        // singular side, an accidental prefix stripping on one axis,
25877        // an accidental wildcard prepend the SNI fan-out overlay
25878        // authors on the plural side without a paired singular
25879        // migration) trip at caixa-core build time.
25880        let e = entrada_with_host("checkout.quero.cloud");
25881        assert_eq!(
25882            e.hostnames(),
25883            vec![e.hostname()],
25884            "Entrada::hostnames must return `vec![hostname()]` under \
25885             the pair-invariant — got {:?} vs. singleton {:?}",
25886            e.hostnames(),
25887            vec![e.hostname()],
25888        );
25889    }
25890
25891    #[test]
25892    fn hostnames_is_singleton_under_single_host_author_surface() {
25893        // The singleton-shape pin: under today's single-hostname-per-
25894        // `:entrada` author surface (the `:host` slot is a single
25895        // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
25896        // must always return a list of length exactly one. Pins
25897        // against a future silent detour that returned an empty list
25898        // (which would emit an HTTPRoute with `spec.hostnames: []` —
25899        // matching every incoming Host header regardless of the
25900        // Aplicacao's declared ingress apex, silently over-matching
25901        // every foreign VirtualHost the parent Gateway also fronts) or
25902        // a duplicated entry (which the Gateway API v1.x parser
25903        // accepts as a `[]-length-2 list of equal hostnames]` but
25904        // whose semantics differ from the intended singleton). The
25905        // author-surface extension point ("a future `:entrada
25906        // :alt-hosts` list overlay" the docstring names) is the sole
25907        // future axis that flips this pin — that migration will re-
25908        // author this test to pin the new plural cardinality.
25909        let e = entrada_with_host("checkout.quero.cloud");
25910        assert_eq!(
25911            e.hostnames().len(),
25912            1,
25913            "Entrada::hostnames must be a singleton under today's \
25914             single-hostname-per-`:entrada` author surface — got \
25915             length {}: {:?}",
25916            e.hostnames().len(),
25917            e.hostnames(),
25918        );
25919    }
25920
25921    // ── Entrada::destination — the substrate-canonical per-`:entrada`
25922    //    destination-Servico scalar accessor every Gateway-API
25923    //    HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
25924    //    discriminator arg (HTTPRoute name composer) or a per-rule
25925    //    `backendRefs[0].name` axis routes through. The two pin tests
25926    //    below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
25927    //    either arm surfaces at caixa-core build time rather than at
25928    //    cluster-apply time when an HTTPRoute's `metadata.name` and
25929    //    `backendRefs[]` silently disagree on which destination Servico
25930    //    the ingress fronts. Peer discipline with the sibling
25931    //    `resolved_paths` + `hostname` + `hostnames` accept-set pin
25932    //    blocks above on the per-`:entrada` path-list / DNS-hostname
25933    //    resolver axes.
25934
25935    #[test]
25936    fn destination_returns_entrada_para_byte_equal() {
25937        // The canonical destination-scalar pin: [`Entrada::destination`]
25938        // must return the `:entrada :para` field byte-for-byte, borrowed
25939        // from the typed slot's own [`String`] storage. Pins against a
25940        // future silent detour that re-normalized the destination (an
25941        // accidental `.to_lowercase()` — the destination Servico is
25942        // already validated as a DNS-1123 label upstream, so any
25943        // re-normalization is redundant + a drift surface between the
25944        // validator and the accessor), a namespace-prefix rewrite (an
25945        // accidental `format!("{namespace}/{para}")` per-CR fully-
25946        // qualified rewrite that didn't land on the peer axis), or a
25947        // per-cluster suffix stamp the operator authors on one
25948        // consumer without the other.
25949        for para in ["cart", "checkout", "catalog", "orders-v2"] {
25950            let e = Entrada {
25951                host: "checkout.quero.cloud".into(),
25952                para: para.into(),
25953                paths: Vec::new(),
25954                port: DEFAULT_SERVICO_PORT,
25955            };
25956            assert_eq!(
25957                e.destination(),
25958                para,
25959                "Entrada::destination must return :entrada :para verbatim \
25960                 (got {:?}, expected {para:?})",
25961                e.destination(),
25962            );
25963            assert_eq!(
25964                e.destination(),
25965                e.para.as_str(),
25966                "Entrada::destination must byte-equal the .para field access",
25967            );
25968        }
25969    }
25970
25971    #[test]
25972    fn destination_borrows_from_entrada_para_storage() {
25973        // The borrow-not-copy pin: [`Entrada::destination`] must
25974        // return a `&str` slice that borrows from the typed slot's
25975        // own [`String`] storage — same-address invariant with
25976        // `entrada.para.as_str()`. Pins against a future silent detour
25977        // that allocated a fresh `String` (`self.para.clone()` in the
25978        // body would type-check but silently drop the borrow, and
25979        // every downstream consumer that assumed the returned slice
25980        // outlives `&self` would break on a stale-reference use-after-
25981        // free). Peer with the sibling `hostname_returns_entrada_
25982        // host_byte_equal` on the singular-DNS-hostname axis.
25983        let e = entrada_with_host("checkout.quero.cloud");
25984        let dest = e.destination();
25985        let para_slice = e.para.as_str();
25986        assert_eq!(
25987            dest.as_ptr(),
25988            para_slice.as_ptr(),
25989            "Entrada::destination must borrow from the .para String's \
25990             backing storage — a fresh allocation here means the \
25991             accessor no longer names the substrate-primitive typed \
25992             dispatch and every downstream consumer would silently \
25993             carry a detached copy",
25994        );
25995        assert_eq!(
25996            dest.len(),
25997            para_slice.len(),
25998            "Entrada::destination and .para.as_str() must byte-equal in \
25999             length as well as in address",
26000        );
26001    }
26002
26003    #[test]
26004    fn port_returns_entrada_port_verbatim_across_permutations() {
26005        // The canonical L4-port-scalar pin: [`Entrada::port`] must
26006        // return the `:entrada :port` field verbatim as a `u16` across
26007        // every author-declared value in the validated accept-set
26008        // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
26009        // silent detour that clamped the port (an accidental
26010        // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
26011        // land on the peer [`AplicacaoSpec::port_for_destination`]
26012        // resolver), rewrote it through a per-cluster port-remap table
26013        // the operator authors on one consumer without the other, or
26014        // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
26015        // serde-default value (which would silently collapse the
26016        // distinction between "author explicitly declared `:port 8080`"
26017        // and "author omitted the slot and inherited the default" the
26018        // future per-cluster override slot depends on). Peer with the
26019        // sibling `destination_returns_entrada_para_byte_equal` +
26020        // `hostname_returns_entrada_host_byte_equal` pins on the
26021        // per-`:entrada` `&str` scalar axes.
26022        for port in [
26023            SERVICO_PORT_MIN,
26024            DEFAULT_SERVICO_PORT,
26025            8443u16,
26026            9090u16,
26027            u16::MAX,
26028        ] {
26029            let e = Entrada {
26030                host: "checkout.quero.cloud".into(),
26031                para: "cart".into(),
26032                paths: Vec::new(),
26033                port,
26034            };
26035            assert_eq!(
26036                e.port(),
26037                port,
26038                "Entrada::port must return :entrada :port verbatim \
26039                 (got {}, expected {port})",
26040                e.port(),
26041            );
26042            assert_eq!(
26043                e.port(),
26044                e.port,
26045                "Entrada::port accessor and .port field access must \
26046                 byte-equal — the accessor is the substrate-primitive \
26047                 typed dispatch every downstream L4-port consumer must \
26048                 route through",
26049            );
26050        }
26051    }
26052
26053    #[test]
26054    fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
26055        // Two-consumer coherence pin: the
26056        // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
26057        // (which reads through [`Entrada::port`] to compare against
26058        // [`SERVICO_PORT_MIN`]) and the
26059        // [`AplicacaoSpec::port_for_destination`] resolver (which reads
26060        // through [`Entrada::port`] to emit the per-destination
26061        // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
26062        // lifted accessor, so any future rebrand on the typed slot's
26063        // reader shape lands at exactly one place. Pins the two-site
26064        // coherence by exercising a below-floor port through validate
26065        // (which must reject) and a validated in-accept-set port through
26066        // port_for_destination (which must emit the same value the
26067        // accessor returns).
26068        let mut spec = three_member_spec();
26069        if let Some(e) = spec.entrada.as_mut() {
26070            e.port = 0;
26071        }
26072        assert_eq!(
26073            spec.validate().unwrap_err(),
26074            AplicacaoError::EntradaPortZero,
26075            "validate must reject `:entrada :port 0` through the lifted \
26076             Entrada::port accessor — port zero lies below \
26077             SERVICO_PORT_MIN and the validator routes through port() \
26078             to name the floor",
26079        );
26080
26081        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
26082            let mut spec = three_member_spec();
26083            if let Some(e) = spec.entrada.as_mut() {
26084                e.port = port;
26085            }
26086            spec.validate().expect(
26087                "entrada with in-accept-set :port must validate — the \
26088                 structural-floor gate reads through Entrada::port",
26089            );
26090            let entrada_ref = spec.entrada().expect(":entrada present");
26091            assert_eq!(
26092                spec.port_for_destination(entrada_ref.destination()),
26093                entrada_ref.port(),
26094                "port_for_destination(entrada.destination()) must equal \
26095                 entrada.port() — the two consumers of the per-:entrada \
26096                 L4-port axis (validator, per-destination resolver) both \
26097                 route through Entrada::port",
26098            );
26099        }
26100    }
26101
26102    #[test]
26103    fn wit_contract_source_returns_de_byte_equal_across_permutations() {
26104        // The canonical caller-Servico-scalar pin: [`WitContract::source`]
26105        // must return the `:contratos :de` field byte-for-byte, borrowed
26106        // from the typed slot's own [`String`] storage. Peer of the
26107        // sibling `destination_returns_entrada_para_byte_equal` pin on
26108        // the per-`:entrada` axis — same "the substrate-primitive
26109        // accessor must byte-equal the raw field access verbatim across
26110        // every author-declared value" discipline extended to the
26111        // per-`:contratos` caller arm. Pins against a future silent
26112        // detour that re-normalized the caller (an accidental
26113        // `.to_lowercase()` — every `:contratos :de` is validated as a
26114        // DNS-1123 label upstream via `validate_contrato_caixa`, so any
26115        // re-normalization is redundant + a drift surface between the
26116        // validator and the accessor), a namespace-prefix rewrite (an
26117        // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
26118        // rewrite that didn't land on the peer axis), or a per-cluster
26119        // suffix stamp the operator authors on one consumer without the
26120        // other.
26121        for de in ["cart", "checkout", "catalog", "orders-v2"] {
26122            let c = WitContract {
26123                de: de.into(),
26124                para: "downstream".into(),
26125                wit: "wasi:http/proxy".into(),
26126                endpoint: Some("/lookup".into()),
26127                subject: None,
26128                slot: None,
26129            };
26130            assert_eq!(
26131                c.source(),
26132                de,
26133                "WitContract::source must return :contratos :de verbatim \
26134                 (got {:?}, expected {de:?})",
26135                c.source(),
26136            );
26137            assert_eq!(
26138                c.source(),
26139                c.de.as_str(),
26140                "WitContract::source must byte-equal the .de field access",
26141            );
26142        }
26143    }
26144
26145    #[test]
26146    fn wit_contract_source_borrows_from_de_storage() {
26147        // The borrow-not-copy pin: [`WitContract::source`] must return a
26148        // `&str` slice that borrows from the typed slot's own [`String`]
26149        // storage — same-address invariant with `c.de.as_str()`. Pins
26150        // against a future silent detour that allocated a fresh `String`
26151        // (`self.de.clone()` in the body would type-check but silently
26152        // drop the borrow, and every downstream consumer that assumed
26153        // the returned slice outlives `&self` would break on a stale-
26154        // reference use-after-free). Peer of the sibling
26155        // `destination_borrows_from_entrada_para_storage` on the
26156        // per-`:entrada` axis.
26157        let c = WitContract {
26158            de: "cart".into(),
26159            para: "catalog".into(),
26160            wit: "wasi:http/proxy".into(),
26161            endpoint: Some("/lookup".into()),
26162            subject: None,
26163            slot: None,
26164        };
26165        let src = c.source();
26166        let de_slice = c.de.as_str();
26167        assert_eq!(
26168            src.as_ptr(),
26169            de_slice.as_ptr(),
26170            "WitContract::source must borrow from the .de String's \
26171             backing storage — a fresh allocation here means the \
26172             accessor no longer names the substrate-primitive typed \
26173             dispatch and every downstream consumer would silently \
26174             carry a detached copy",
26175        );
26176        assert_eq!(
26177            src.len(),
26178            de_slice.len(),
26179            "WitContract::source and .de.as_str() must byte-equal in \
26180             length as well as in address",
26181        );
26182    }
26183
26184    #[test]
26185    fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
26186        // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
26187        // must return the `:contratos :para` field byte-for-byte,
26188        // borrowed from the typed slot's own [`String`] storage. Peer of
26189        // the sibling `destination_returns_entrada_para_byte_equal` on
26190        // the per-`:entrada` axis — both accessors name "the destination-
26191        // Servico byte-string" concept on their respective mesh-slot
26192        // atoms (per-ingress apex vs. per-typed-edge callee) and both
26193        // must project the underlying `.para` field verbatim so every
26194        // downstream renderer that composes them with peer accessors
26195        // (e.g. `spec.port_for_destination(c.destination())` at the CNP
26196        // per-edge L4 port emit site) reads the same byte-string the
26197        // author declared.
26198        for para in ["catalog", "payment", "orders", "inventory-v3"] {
26199            let c = WitContract {
26200                de: "cart".into(),
26201                para: para.into(),
26202                wit: "wasi:http/proxy".into(),
26203                endpoint: Some("/lookup".into()),
26204                subject: None,
26205                slot: None,
26206            };
26207            assert_eq!(
26208                c.destination(),
26209                para,
26210                "WitContract::destination must return :contratos :para \
26211                 verbatim (got {:?}, expected {para:?})",
26212                c.destination(),
26213            );
26214            assert_eq!(
26215                c.destination(),
26216                c.para.as_str(),
26217                "WitContract::destination must byte-equal the .para \
26218                 field access",
26219            );
26220        }
26221    }
26222
26223    #[test]
26224    fn wit_contract_destination_borrows_from_para_storage() {
26225        // The borrow-not-copy pin: [`WitContract::destination`] must
26226        // return a `&str` slice that borrows from the typed slot's own
26227        // [`String`] storage — same-address invariant with
26228        // `c.para.as_str()`. Peer of the sibling
26229        // `destination_borrows_from_entrada_para_storage` on the
26230        // per-`:entrada` axis.
26231        let c = WitContract {
26232            de: "cart".into(),
26233            para: "catalog".into(),
26234            wit: "wasi:http/proxy".into(),
26235            endpoint: Some("/lookup".into()),
26236            subject: None,
26237            slot: None,
26238        };
26239        let dest = c.destination();
26240        let para_slice = c.para.as_str();
26241        assert_eq!(
26242            dest.as_ptr(),
26243            para_slice.as_ptr(),
26244            "WitContract::destination must borrow from the .para \
26245             String's backing storage — a fresh allocation here means \
26246             the accessor no longer names the substrate-primitive typed \
26247             dispatch and every downstream consumer would silently \
26248             carry a detached copy",
26249        );
26250        assert_eq!(
26251            dest.len(),
26252            para_slice.len(),
26253            "WitContract::destination and .para.as_str() must byte-equal \
26254             in length as well as in address",
26255        );
26256    }
26257
26258    #[test]
26259    fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
26260        // The canonical per-`:contratos` WIT-world-reference scalar pin:
26261        // [`WitContract::world_ref`] must return the `:contratos :wit`
26262        // field byte-for-byte, borrowed from the typed slot's own
26263        // [`String`] storage. Sibling of the peer per-`:contratos`
26264        // [`WitContract::source`] / [`WitContract::destination`]
26265        // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
26266        // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
26267        // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
26268        // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
26269        // "the substrate-primitive accessor must byte-equal the raw
26270        // field access verbatim across every author-declared value"
26271        // discipline extended to the per-`:contratos` WIT-world arm.
26272        // Pins against a future silent detour that re-canonicalized the
26273        // WIT world reference (an accidental `.to_lowercase()` pass that
26274        // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
26275        // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
26276        // gate is already lowercase-prefixed so any re-normalization is
26277        // redundant + a drift surface between the validator and the
26278        // accessor), an M4-promotion-shape rewrite that formatted a
26279        // typed WIT-world enum through [`Display`] and silently drifted
26280        // the printer output from the source `caixa.lisp`, or a per-
26281        // cluster WIT-alias rewrite that didn't land on the peer field-
26282        // access sites. Five values sweep the shape-dispatch accept-set
26283        // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
26284        // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
26285        // `wasi:keyvalue/`).
26286        for (wit, endpoint, subject, slot) in [
26287            ("wasi:http/proxy", Some("/lookup"), None, None),
26288            ("http:proxy", Some("/health"), None, None),
26289            ("nats:pub-sub", None, Some("orders.paid"), None),
26290            ("kafka:events", None, Some("checkout-events"), None),
26291            ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
26292        ] {
26293            let c = WitContract {
26294                de: "cart".into(),
26295                para: "downstream".into(),
26296                wit: wit.into(),
26297                endpoint: endpoint.map(str::to_string),
26298                subject: subject.map(str::to_string),
26299                slot: slot.map(str::to_string),
26300            };
26301            assert_eq!(
26302                c.world_ref(),
26303                wit,
26304                "WitContract::world_ref must return :contratos :wit \
26305                 verbatim (got {:?}, expected {wit:?})",
26306                c.world_ref(),
26307            );
26308            assert_eq!(
26309                c.world_ref(),
26310                c.wit.as_str(),
26311                "WitContract::world_ref must byte-equal the .wit field \
26312                 access",
26313            );
26314        }
26315    }
26316
26317    #[test]
26318    fn wit_contract_world_ref_borrows_from_wit_storage() {
26319        // The borrow-not-copy pin: [`WitContract::world_ref`] must
26320        // return a `&str` slice that borrows from the typed slot's own
26321        // [`String`] storage — same-address invariant with
26322        // `c.wit.as_str()`. Pins against a future silent detour that
26323        // allocated a fresh `String` (`self.wit.clone()` in the body
26324        // would type-check but silently drop the borrow, and every
26325        // downstream consumer that assumed the returned slice outlives
26326        // `&self` would break on a stale-reference use-after-free — the
26327        // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
26328        // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
26329        // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
26330        // / [`is_pubsub`][WitContract::is_pubsub] /
26331        // [`is_store`][WitContract::is_store] methods route through —
26332        // each borrow from the WitContract's own storage and each would
26333        // silently misbehave if this accessor produced a detached copy).
26334        // Peer of the sibling per-`:contratos` [`WitContract::source`] /
26335        // [`WitContract::destination`] and per-`:entrada`
26336        // [`Entrada::destination`] / [`Entrada::hostname`] and
26337        // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
26338        // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
26339        let c = WitContract {
26340            de: "cart".into(),
26341            para: "catalog".into(),
26342            wit: "wasi:http/proxy".into(),
26343            endpoint: Some("/lookup".into()),
26344            subject: None,
26345            slot: None,
26346        };
26347        let world = c.world_ref();
26348        let wit_slice = c.wit.as_str();
26349        assert_eq!(
26350            world.as_ptr(),
26351            wit_slice.as_ptr(),
26352            "WitContract::world_ref must borrow from the .wit String's \
26353             backing storage — a fresh allocation here means the \
26354             accessor no longer names the substrate-primitive typed \
26355             dispatch and every downstream consumer would silently carry \
26356             a detached copy",
26357        );
26358        assert_eq!(
26359            world.len(),
26360            wit_slice.len(),
26361            "WitContract::world_ref and .wit.as_str() must byte-equal in \
26362             length as well as in address",
26363        );
26364    }
26365
26366    #[test]
26367    fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
26368        // Sibling-triple invariant pin composing all three per-`:contratos`
26369        // substrate-primitive typed dispatches — [`WitContract::source`]
26370        // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
26371        // [`WitContract::world_ref`] — at the joint
26372        // `(source(), destination(), world_ref())` call shape every
26373        // renderer that fans on per-edge caller-callee-shape identity
26374        // keys off. The invariant, evaluated per-contract:
26375        //
26376        //   (c.source(), c.destination(), c.world_ref())
26377        //   == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
26378        //
26379        // Closes the last unlifted per-`:contratos` scalar axis — every
26380        // downstream consumer that reads the triple now routes through
26381        // exactly three typed dispatches on the substrate primitive,
26382        // not two typed + one open-coded field access. A future refactor
26383        // that silently split any one accessor's projection (an
26384        // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
26385        // canonicalization that didn't reach the peer `source`/
26386        // `destination` arms, an accidental `source()` per-cluster
26387        // caller-alias rewrite that didn't land on the `world_ref` peer)
26388        // surfaces at caixa-core build time. Peer of the sibling per-
26389        // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
26390        // per-`:entrada` `(hostname(), destination())` (6db982c /
26391        // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
26392        // axes, extended to the per-`:contratos` triple.
26393        for (de, para, wit, endpoint, subject, slot) in [
26394            (
26395                "cart",
26396                "catalog",
26397                "wasi:http/proxy",
26398                Some("/lookup"),
26399                None,
26400                None,
26401            ),
26402            (
26403                "checkout",
26404                "orders",
26405                "nats:pub-sub",
26406                None,
26407                Some("orders.paid"),
26408                None,
26409            ),
26410            (
26411                "cart",
26412                "kv",
26413                "wasi:keyvalue/store",
26414                None,
26415                None,
26416                Some("carts/{cart_id}"),
26417            ),
26418            (
26419                "orders-v2",
26420                "inventory-v3",
26421                "http:proxy",
26422                Some("/reserve"),
26423                None,
26424                None,
26425            ),
26426        ] {
26427            let c = WitContract {
26428                de: de.into(),
26429                para: para.into(),
26430                wit: wit.into(),
26431                endpoint: endpoint.map(str::to_string),
26432                subject: subject.map(str::to_string),
26433                slot: slot.map(str::to_string),
26434            };
26435            assert_eq!(
26436                (c.source(), c.destination(), c.world_ref()),
26437                (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
26438                "(WitContract::source, ::destination, ::world_ref) must \
26439                 project (.de, .para, .wit) verbatim across every author-\
26440                 declared triple (got ({:?}, {:?}, {:?}), expected \
26441                 ({de:?}, {para:?}, {wit:?}))",
26442                c.source(),
26443                c.destination(),
26444                c.world_ref(),
26445            );
26446        }
26447    }
26448
26449    #[test]
26450    fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
26451        // The canonical per-`:contratos` owned-form caller-callee-pair
26452        // pin: [`WitContract::edge_pair`] must return the
26453        // `(source(), destination())` tuple in owned form byte-for-byte,
26454        // projected through the lifted [`WitContract::source`] /
26455        // [`WitContract::destination`] scalar accessors. Pins the
26456        // composite-projection invariant on the per-`:contratos`
26457        // mesh-slot atom — every author-declared `(de, para)` pair must
26458        // round-trip verbatim through the substrate primitive's typed
26459        // dispatch, so the nine [`AplicacaoError`] diagnostic-
26460        // construction sites the accessor now feeds
26461        // ([`AplicacaoError::EmptyWit`],
26462        // [`AplicacaoError::ContratoEndpointEmpty`],
26463        // [`AplicacaoError::ContratoEndpointNotAbsolute`],
26464        // [`AplicacaoError::ContratoEndpointInvalid`],
26465        // [`AplicacaoError::ContratoSubjectEmpty`],
26466        // [`AplicacaoError::ContratoSubjectInvalid`],
26467        // [`AplicacaoError::ContratoSlotEmpty`],
26468        // [`AplicacaoError::ContratoSlotInvalid`],
26469        // [`AplicacaoError::ContratoDuplicate`]) all read the same
26470        // `(de, para)` label pair every author sees at the source
26471        // `caixa.lisp`. Pins against a future silent detour that swapped
26472        // the `.0` / `.1` arms (an accidental `(destination(),
26473        // source())` re-order in the body would silently invert every
26474        // downstream diagnostic's `de:` / `para:` label pair, silently
26475        // reversing the direction of every operator-facing typed error
26476        // arrow), a fresh-allocation shape drift (an accidental
26477        // `.to_string()` on one arm but not the other would leave the
26478        // owned/borrowed pair mismatched vs. the sibling `source()` /
26479        // `destination()` returns), or an M4 per-cluster caller/callee-
26480        // alias rewrite that landed on `source()` without reaching
26481        // `destination()` (or vice versa). Peer of the sibling per-
26482        // `:contratos` `(source, destination, world_ref)` triple
26483        // pin above on the mesh-slot-atom scalar-value axes, extended
26484        // to the owned-form pair-projection axis.
26485        for (de, para, wit, endpoint, subject, slot) in [
26486            (
26487                "cart",
26488                "catalog",
26489                "wasi:http/proxy",
26490                Some("/lookup"),
26491                None,
26492                None,
26493            ),
26494            (
26495                "checkout",
26496                "orders",
26497                "nats:pub-sub",
26498                None,
26499                Some("orders.paid"),
26500                None,
26501            ),
26502            (
26503                "cart",
26504                "kv",
26505                "wasi:keyvalue/store",
26506                None,
26507                None,
26508                Some("carts/{cart_id}"),
26509            ),
26510            (
26511                "orders-v2",
26512                "inventory-v3",
26513                "http:proxy",
26514                Some("/reserve"),
26515                None,
26516                None,
26517            ),
26518        ] {
26519            let c = WitContract {
26520                de: de.into(),
26521                para: para.into(),
26522                wit: wit.into(),
26523                endpoint: endpoint.map(str::to_string),
26524                subject: subject.map(str::to_string),
26525                slot: slot.map(str::to_string),
26526            };
26527            assert_eq!(
26528                c.edge_pair(),
26529                (de.to_string(), para.to_string()),
26530                "WitContract::edge_pair must return (:contratos :de, \
26531                 :contratos :para) as an owned tuple verbatim (got {:?}, \
26532                 expected ({de:?}, {para:?}))",
26533                c.edge_pair(),
26534            );
26535        }
26536    }
26537
26538    #[test]
26539    fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
26540        // The composition pin: [`WitContract::edge_pair`] must return
26541        // exactly `(source().to_string(), destination().to_string())` —
26542        // the owned form of the sibling accessor pair — so any future
26543        // refactor that silently re-authored the caller-arm / callee-arm
26544        // projection to bypass the lifted scalar accessors (an accidental
26545        // `(self.de.clone(), self.para.clone())` regression back to the
26546        // raw field-access shape, an M4-typed-caller-enum `Display`
26547        // re-canonicalization on `source()` that didn't reach
26548        // `edge_pair()`, a per-cluster alias rewrite the operator lands
26549        // on `destination()` without reaching this composite projection)
26550        // trips at caixa-core build time. Pins the "typed dispatch
26551        // composes with typed dispatch, not with raw field access"
26552        // discipline every downstream diagnostic-construction site now
26553        // routes through — a `de:` / `para:` label pair whose
26554        // projection silently drifted off the substrate primitive's
26555        // scalar accessors would silently split the diagnostic's self-
26556        // locating signal from the source `caixa.lisp` author's view.
26557        // Peer of the sibling per-`:politicas` `is_empty` /
26558        // `validate_politicas` accessor-routing-pin family on the M3
26559        // mesh-slot family (18575, 18739, 18918, 19140, 19371).
26560        let c = WitContract {
26561            de: "cart".into(),
26562            para: "catalog".into(),
26563            wit: "wasi:http/proxy".into(),
26564            endpoint: Some("/lookup".into()),
26565            subject: None,
26566            slot: None,
26567        };
26568        assert_eq!(
26569            c.edge_pair(),
26570            (c.source().to_string(), c.destination().to_string()),
26571            "WitContract::edge_pair must compose exactly \
26572             (source().to_string(), destination().to_string()) — a \
26573             bypass of either sibling accessor here would silently \
26574             decouple the composite-projection axis from the \
26575             substrate-primitive scalar accessors every downstream \
26576             consumer routes through",
26577        );
26578    }
26579
26580    #[test]
26581    fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
26582     {
26583        // The canonical per-`:contratos` owned-form
26584        // caller-callee-world-ref-triple pin:
26585        // [`WitContract::edge_triple`] must return the
26586        // `(source(), destination(), world_ref())` tuple in owned form
26587        // byte-for-byte, projected through the lifted
26588        // [`WitContract::source`] / [`WitContract::destination`] /
26589        // [`WitContract::world_ref`] scalar accessors. Pins the
26590        // composite-projection invariant on the per-`:contratos`
26591        // mesh-slot atom — every author-declared `(de, para, wit)`
26592        // triple must round-trip verbatim through the substrate
26593        // primitive's typed dispatch, so the nine
26594        // [`AplicacaoError`] diagnostic-construction sites the
26595        // accessor now feeds (the [`WitTarget`]-dispatch's eight
26596        // wrong-target / missing-target / invalid-wit / capability-
26597        // with-payload arms in [`WitContract::target`], plus the
26598        // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
26599        // diagnostic constructor in [`AplicacaoSpec::validate`]) all
26600        // read the same `(de, para, wit)` triple every author sees at
26601        // the source `caixa.lisp`. Pins against a future silent
26602        // detour that swapped any two arms (an accidental `(destination(),
26603        // source(), world_ref())` re-order in the body would silently
26604        // invert every downstream diagnostic's `de:` / `para:` label
26605        // pair, silently reversing the direction of every operator-
26606        // facing typed error arrow), a fresh-allocation shape drift
26607        // (an accidental `.to_string()` skipped on one arm would leave
26608        // the owned/borrowed triple mismatched vs. the sibling
26609        // `source()` / `destination()` / `world_ref()` returns), or an
26610        // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
26611        // canonicalization pass that landed on one accessor without
26612        // reaching the peers. Peer of the sibling per-`:contratos`
26613        // caller-callee-pair
26614        // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
26615        // pin on the mesh-slot-atom composite-projection axis,
26616        // extended to the triple-projection axis.
26617        for (de, para, wit, endpoint, subject, slot) in [
26618            (
26619                "cart",
26620                "catalog",
26621                "wasi:http/proxy",
26622                Some("/lookup"),
26623                None,
26624                None,
26625            ),
26626            (
26627                "checkout",
26628                "orders",
26629                "nats:pub-sub",
26630                None,
26631                Some("orders.paid"),
26632                None,
26633            ),
26634            (
26635                "cart",
26636                "kv",
26637                "wasi:keyvalue/store",
26638                None,
26639                None,
26640                Some("carts/{cart_id}"),
26641            ),
26642            (
26643                "orders-v2",
26644                "inventory-v3",
26645                "http:proxy",
26646                Some("/reserve"),
26647                None,
26648                None,
26649            ),
26650        ] {
26651            let c = WitContract {
26652                de: de.into(),
26653                para: para.into(),
26654                wit: wit.into(),
26655                endpoint: endpoint.map(str::to_string),
26656                subject: subject.map(str::to_string),
26657                slot: slot.map(str::to_string),
26658            };
26659            assert_eq!(
26660                c.edge_triple(),
26661                (de.to_string(), para.to_string(), wit.to_string()),
26662                "WitContract::edge_triple must return (:contratos :de, \
26663                 :contratos :para, :contratos :wit) as an owned triple \
26664                 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
26665                c.edge_triple(),
26666            );
26667        }
26668    }
26669
26670    #[test]
26671    fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
26672        // The composition pin: [`WitContract::edge_triple`] must return
26673        // exactly `(source().to_string(), destination().to_string(),
26674        // world_ref().to_string())` — the owned form of the sibling
26675        // scalar-accessor triple — so any future refactor that silently
26676        // re-authored one arm's projection to bypass the lifted scalar
26677        // accessors (an accidental `(self.de.clone(), self.para.clone(),
26678        // self.wit.clone())` regression back to the raw field-access
26679        // shape the internal `edge` closure and the ContratoDuplicate
26680        // diagnostic both carried before this lift landed, an
26681        // M4-typed-caller-enum `Display` re-canonicalization on
26682        // `source()` that didn't reach `edge_triple()`, a per-cluster
26683        // alias rewrite the operator lands on `destination()` /
26684        // `world_ref()` without reaching this composite projection)
26685        // trips at caixa-core build time. Pins the "typed dispatch
26686        // composes with typed dispatch, not with raw field access"
26687        // discipline every downstream diagnostic-construction site now
26688        // routes through — a `de:` / `para:` / `wit:` triple whose
26689        // projection silently drifted off the substrate primitive's
26690        // scalar accessors would silently split the diagnostic's self-
26691        // locating signal from the source `caixa.lisp` author's view.
26692        // Peer of the sibling per-`:contratos` edge_pair composition-
26693        // pin above on the mesh-slot-atom composite-projection axis.
26694        let c = WitContract {
26695            de: "cart".into(),
26696            para: "catalog".into(),
26697            wit: "wasi:http/proxy".into(),
26698            endpoint: Some("/lookup".into()),
26699            subject: None,
26700            slot: None,
26701        };
26702        assert_eq!(
26703            c.edge_triple(),
26704            (
26705                c.source().to_string(),
26706                c.destination().to_string(),
26707                c.world_ref().to_string(),
26708            ),
26709            "WitContract::edge_triple must compose exactly \
26710             (source().to_string(), destination().to_string(), \
26711             world_ref().to_string()) — a bypass of any sibling accessor \
26712             here would silently decouple the composite-projection axis \
26713             from the substrate-primitive scalar accessors every \
26714             downstream consumer routes through",
26715        );
26716    }
26717
26718    #[test]
26719    fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
26720        // The canonical semantics-pin: [`WitContract::edge_triple`] must
26721        // project the full `(de, para, wit)` identity of a `:contratos`
26722        // edge — the sub-triple every triple-carrying
26723        // [`AplicacaoError::Contrato*`] diagnostic weaves into its
26724        // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
26725        // missing-target, capability-with-payload, invalid-wit, and the
26726        // duplicate-gate). Rejects a drift in shape (an accidental
26727        // silent detour that returned a `(de, para)` pair or added an
26728        // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
26729        // would trip here because the return type would no longer
26730        // pattern-match the eight `let (de, para, wit) = edge();`
26731        // destructures the [`WitContract::target`] dispatch feeds off
26732        // + the paired duplicate-gate `let (de, para, wit) =
26733        // c.edge_triple();` destructure in
26734        // [`AplicacaoSpec::validate`]). Peer of the sibling per-
26735        // `:contratos` caller-callee-pair pin above extended to the
26736        // triple projection surface: closes the "one composite
26737        // accessor per typed diagnostic-construction sub-tuple"
26738        // discipline on the per-`:contratos` mesh-slot-atom axis.
26739        let c = WitContract {
26740            de: "checkout".into(),
26741            para: "orders".into(),
26742            wit: "nats:pub-sub".into(),
26743            endpoint: None,
26744            subject: Some("orders.paid".into()),
26745            slot: None,
26746        };
26747        let (de, para, wit) = c.edge_triple();
26748        assert_eq!(de, "checkout");
26749        assert_eq!(para, "orders");
26750        assert_eq!(wit, "nats:pub-sub");
26751    }
26752
26753    #[test]
26754    fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
26755     {
26756        // The composition pin: [`WitContract::identity`] must return
26757        // exactly `(source(), destination(), world_ref(), endpoint(),
26758        // subject(), slot())` — the borrowed form of the six-scalar-
26759        // accessor identity axis. Any future refactor that silently
26760        // re-authored one arm's projection to bypass a scalar accessor
26761        // (a `self.de.as_str()` regression back to raw field access on
26762        // any of the three required arms, a `self.endpoint.as_deref()`
26763        // regression on any of the three optional arms, an M4 per-
26764        // cluster caller/callee-alias rewrite the operator lands on
26765        // `source()` / `destination()` without reaching this composite
26766        // projection) trips at caixa-core build time. Sweeps four
26767        // permutations of the WIT-shape × payload lattice — HTTP with
26768        // endpoint, pub-sub with subject, store with slot, payload-less
26769        // capability — so every payload arm is exercised. Peer of the
26770        // sibling per-`:contratos`
26771        // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
26772        // composition pin on the mesh-slot-atom composite-projection
26773        // axis; extends the discipline from the (de, para, wit) prefix
26774        // onto the full-identity axis carrying the three payload arms.
26775        for (de, para, wit, endpoint, subject, slot) in [
26776            (
26777                "cart",
26778                "catalog",
26779                "wasi:http/proxy",
26780                Some("/lookup"),
26781                None,
26782                None,
26783            ),
26784            (
26785                "checkout",
26786                "orders",
26787                "nats:pub-sub",
26788                None,
26789                Some("orders.paid"),
26790                None,
26791            ),
26792            (
26793                "cart",
26794                "kv",
26795                "wasi:keyvalue/store",
26796                None,
26797                None,
26798                Some("carts/{cart_id}"),
26799            ),
26800            ("audit", "sink", "wasi:logging", None, None, None),
26801        ] {
26802            let c = WitContract {
26803                de: de.into(),
26804                para: para.into(),
26805                wit: wit.into(),
26806                endpoint: endpoint.map(str::to_owned),
26807                subject: subject.map(str::to_owned),
26808                slot: slot.map(str::to_owned),
26809            };
26810            assert_eq!(
26811                c.identity(),
26812                (
26813                    c.source(),
26814                    c.destination(),
26815                    c.world_ref(),
26816                    c.endpoint(),
26817                    c.subject(),
26818                    c.slot(),
26819                ),
26820                "WitContract::identity must compose exactly \
26821                 (source(), destination(), world_ref(), endpoint(), \
26822                 subject(), slot()) — a bypass of any sibling accessor \
26823                 here would silently decouple the identity-projection \
26824                 axis from the substrate-primitive scalar accessors \
26825                 every dedup-key consumer routes through",
26826            );
26827        }
26828    }
26829
26830    #[test]
26831    fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
26832        // The canonical semantics-pin: [`WitContract::identity`] must
26833        // project the six-axis (de, para, wit, endpoint, subject, slot)
26834        // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
26835        // gate keys off — two `WitContract`s that agree on all six axes
26836        // are the same typed edge declared twice, the graph-edge
26837        // analogue of duplicate `:membros` / `:placement :clusters` /
26838        // `:entrada :paths` entries. Rejects a shape drift (an
26839        // accidental silent detour that returned a prefix tuple or
26840        // added an extra field) by pattern-matching the six-arm shape.
26841        // Peer of the sibling per-`:contratos`
26842        // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
26843        // pin extended from the (de, para, wit) prefix onto the full
26844        // six-axis identity that the dedup key rides.
26845        let c = WitContract {
26846            de: "cart".into(),
26847            para: "catalog".into(),
26848            wit: "wasi:http/proxy".into(),
26849            endpoint: Some("/products/:id".into()),
26850            subject: None,
26851            slot: None,
26852        };
26853        let (de, para, wit, endpoint, subject, slot) = c.identity();
26854        assert_eq!(de, "cart");
26855        assert_eq!(para, "catalog");
26856        assert_eq!(wit, "wasi:http/proxy");
26857        assert_eq!(endpoint, Some("/products/:id"));
26858        assert_eq!(subject, None);
26859        assert_eq!(slot, None);
26860
26861        // Two byte-identical contracts must produce equal identities —
26862        // the dedup key's foundational invariant.
26863        let c2 = c.clone();
26864        assert_eq!(c.identity(), c2.identity());
26865
26866        // Any change on any of the six axes must break the identity —
26867        // sweeps by mutating one axis at a time.
26868        let mut mutated = c.clone();
26869        mutated.de = "search".into();
26870        assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
26871        let mut mutated = c.clone();
26872        mutated.para = "warehouse".into();
26873        assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
26874        let mut mutated = c.clone();
26875        mutated.wit = "http:legacy".into();
26876        assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
26877        let mut mutated = c.clone();
26878        mutated.endpoint = Some("/search".into());
26879        assert_ne!(
26880            c.identity(),
26881            mutated.identity(),
26882            "endpoint axis must partition"
26883        );
26884        let mut mutated = c.clone();
26885        mutated.subject = Some("orders.paid".into());
26886        assert_ne!(
26887            c.identity(),
26888            mutated.identity(),
26889            "subject axis must partition"
26890        );
26891        let mut mutated = c;
26892        mutated.slot = Some("carts/{id}".into());
26893        assert_ne!(mutated.identity().5, None, "slot axis must partition");
26894    }
26895
26896    #[test]
26897    fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
26898        // The canonical per-`:contratos` structural-self-edge pin:
26899        // [`WitContract::is_self_loop`] must return `true` when the
26900        // `:de` and `:para` fields agree byte-for-byte, across every
26901        // WIT-shape variant the per-edge shape family carries. Pins
26902        // the shape-agnostic identity-space partition the
26903        // [`AplicacaoSpec::validate`] self-edge gate at
26904        // caixa-core/src/aplicacao.rs:5559 fires against — all four
26905        // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
26906        // under the same one predicate. Four permutations sweep the
26907        // accept-set: HTTP with endpoint, pub-sub with subject, KV
26908        // store with slot, and payload-less capability.
26909        for (nome, wit, endpoint, subject, slot) in [
26910            ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
26911            ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
26912            (
26913                "kv",
26914                "wasi:keyvalue/store",
26915                None,
26916                None,
26917                Some("carts/{cart_id}"),
26918            ),
26919            ("audit", "wasi:logging", None, None, None),
26920        ] {
26921            let c = WitContract {
26922                de: nome.into(),
26923                para: nome.into(),
26924                wit: wit.into(),
26925                endpoint: endpoint.map(str::to_string),
26926                subject: subject.map(str::to_string),
26927                slot: slot.map(str::to_string),
26928            };
26929            assert!(
26930                c.is_self_loop(),
26931                "WitContract::is_self_loop must return true when \
26932                 :contratos :de == :contratos :para (got false on \
26933                 {nome:?} under {wit:?})",
26934            );
26935        }
26936    }
26937
26938    #[test]
26939    fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
26940        // The complement pin: [`WitContract::is_self_loop`] must return
26941        // `false` on every well-shaped inter-Servico contract (the
26942        // author-intended `:contratos` shape MESH-COMPOSITION §III.1
26943        // names — "Servico A calls Servico B" between two distinct
26944        // graph nodes). Pins against a future silent detour that
26945        // inverted the predicate (an accidental `!= ` swap for `==`
26946        // would silently reject every legitimate inter-Servico edge
26947        // and admit every self-edge — the exact inversion of the
26948        // author-intended shape). Four permutations sweep the same
26949        // WIT-shape accept-set the sibling positive-arm test carries.
26950        for (de, para, wit, endpoint, subject, slot) in [
26951            (
26952                "cart",
26953                "catalog",
26954                "wasi:http/proxy",
26955                Some("/lookup"),
26956                None,
26957                None,
26958            ),
26959            (
26960                "checkout",
26961                "orders",
26962                "nats:pub-sub",
26963                None,
26964                Some("orders.paid"),
26965                None,
26966            ),
26967            (
26968                "cart",
26969                "kv",
26970                "wasi:keyvalue/store",
26971                None,
26972                None,
26973                Some("carts/{cart_id}"),
26974            ),
26975            ("audit", "sink", "wasi:logging", None, None, None),
26976        ] {
26977            let c = WitContract {
26978                de: de.into(),
26979                para: para.into(),
26980                wit: wit.into(),
26981                endpoint: endpoint.map(str::to_string),
26982                subject: subject.map(str::to_string),
26983                slot: slot.map(str::to_string),
26984            };
26985            assert!(
26986                !c.is_self_loop(),
26987                "WitContract::is_self_loop must return false when \
26988                 :contratos :de differs from :contratos :para (got true \
26989                 on {de:?} → {para:?} under {wit:?})",
26990            );
26991        }
26992    }
26993
26994    #[test]
26995    fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
26996        // The composition pin: [`WitContract::is_self_loop`] must
26997        // resolve to exactly `self.source() == self.destination()` —
26998        // the equality probe of the sibling scalar-accessor pair — so
26999        // any future refactor that silently re-authored the predicate
27000        // to bypass the lifted scalar accessors (an accidental
27001        // `self.de == self.para` regression back to the raw field-
27002        // access shape, an M4-typed-caller-enum identity-comparison
27003        // rule that landed on `source()` without reaching
27004        // `destination()`, a per-cluster alias rewrite the operator
27005        // pins on `destination()` without reaching this predicate)
27006        // trips at caixa-core build time. Pins the "typed dispatch
27007        // composes with typed dispatch, not with raw field access"
27008        // discipline the sibling [`WitContract::edge_pair`] /
27009        // [`WitContract::edge_triple`] composite-projection accessors
27010        // already carry, extended onto the per-edge endpoint-equality
27011        // predicate axis. Positive and complement arms both fire.
27012        let self_edge = WitContract {
27013            de: "cart".into(),
27014            para: "cart".into(),
27015            wit: "wasi:http/proxy".into(),
27016            endpoint: Some("/lookup".into()),
27017            subject: None,
27018            slot: None,
27019        };
27020        assert_eq!(
27021            self_edge.is_self_loop(),
27022            self_edge.source() == self_edge.destination(),
27023            "WitContract::is_self_loop must compose exactly \
27024             `source() == destination()` — a bypass of either sibling \
27025             accessor here would silently decouple the endpoint-\
27026             equality predicate from the substrate-primitive scalar \
27027             accessors every downstream consumer routes through",
27028        );
27029        let inter_edge = WitContract {
27030            de: "cart".into(),
27031            para: "catalog".into(),
27032            wit: "wasi:http/proxy".into(),
27033            endpoint: Some("/lookup".into()),
27034            subject: None,
27035            slot: None,
27036        };
27037        assert_eq!(
27038            inter_edge.is_self_loop(),
27039            inter_edge.source() == inter_edge.destination(),
27040            "WitContract::is_self_loop must compose exactly \
27041             `source() == destination()` on the complement arm too",
27042        );
27043    }
27044
27045    #[test]
27046    fn wit_contract_target_wit_shape_gate_routes_through_world_ref_accessor() {
27047        // The composition pin: [`WitContract::target`]'s invalid-wit
27048        // value-shape gate must feed the reason string through the
27049        // lifted [`WitContract::world_ref`] scalar accessor — the same
27050        // typed dispatch on the substrate primitive every peer
27051        // per-`:contratos` payload-carrier extraction in the same
27052        // method body already routes through
27053        // ([`WitContract::endpoint`] on the HTTP-arm target extraction,
27054        // [`WitContract::subject`] on the pub-sub-arm target extraction,
27055        // [`WitContract::slot`] on the store-arm target extraction) and
27056        // every peer composite-projection accessor
27057        // ([`WitContract::edge_pair`], [`WitContract::edge_triple`],
27058        // [`WitContract::identity`]) already composes from. Any future
27059        // refactor that silently re-authored the gate to bypass the
27060        // lifted accessor (an accidental `&self.wit` regression back to
27061        // the raw field-access shape, an M4-typed-`WitWorld` `Display`
27062        // re-canonicalization on `world_ref()` that didn't reach this
27063        // gate, a per-CR lowercasing canonicalization pass the M4
27064        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
27065        // per-tenant that lands on `world_ref()` without reaching this
27066        // gate) would silently split the invalid-wit diagnostic reason
27067        // from the substrate-primitive projection every downstream
27068        // consumer routes through. Same "typed dispatch composes with
27069        // typed dispatch, not with raw field access" discipline the
27070        // sibling
27071        // [`wit_contract_is_self_loop_routes_through_source_destination_accessors`]
27072        // pin already carries on the endpoint-equality predicate axis,
27073        // extended onto the invalid-wit value-shape gate axis inside
27074        // the same [`WitContract::target`] body. Closes the last
27075        // unlifted raw-field-access site inside `impl WitContract`.
27076        //
27077        // The fixture carries `:wit "WASI:HTTP/proxy"` — the canonical
27078        // uppercase-typo footgun the pre-c4213a4 shape silently demoted
27079        // to a capability-only edge; the value-shape gate rejects it
27080        // through [`crate::render::is_wit_world_ref`] on the substrate
27081        // primitive's ASCII-lowercase-only accept-set, with a
27082        // parser-shaped reason string the test asserts round-trips
27083        // byte-for-byte between the direct-dispatch call (through the
27084        // predicate on the accessor's projection) and the
27085        // [`WitContract::target`] gate's produced reason field.
27086        let c = WitContract {
27087            de: "cart".into(),
27088            para: "catalog".into(),
27089            wit: "WASI:HTTP/proxy".into(),
27090            endpoint: Some("/lookup".into()),
27091            subject: None,
27092            slot: None,
27093        };
27094        let err = c.target().unwrap_err();
27095        let AplicacaoError::ContratoWitInvalid {
27096            ref de,
27097            ref para,
27098            ref wit,
27099            ref reason,
27100        } = err
27101        else {
27102            panic!("expected ContratoWitInvalid, got {err:?}");
27103        };
27104        assert_eq!(de, "cart");
27105        assert_eq!(para, "catalog");
27106        assert_eq!(wit, "WASI:HTTP/proxy");
27107        let expected_reason = crate::render::is_wit_world_ref(c.world_ref()).unwrap_err();
27108        assert_eq!(
27109            *reason, expected_reason,
27110            "WitContract::target's invalid-wit value-shape gate reason \
27111             must compose exactly is_wit_world_ref(self.world_ref()) — \
27112             a bypass here (e.g. a raw `&self.wit` field-access \
27113             regression, or a divergent predicate on a different \
27114             projection) would silently decouple the invalid-wit \
27115             diagnostic's reason field from the substrate-primitive \
27116             scalar accessor every peer per-`:contratos` extraction in \
27117             the same method body already routes through",
27118        );
27119    }
27120
27121    #[test]
27122    fn wit_contract_is_self_loop_predicate_is_const_fn() {
27123        // Fail-before-pass-after pin on the [`WitContract::is_self_loop`]
27124        // caller-callee identity-space predicate's `const`-eval-surface
27125        // posture. The wrapper below dispatches through
27126        // [`WitContract::is_self_loop`] and is well-formed only when the
27127        // callee is itself `pub const fn` — any future accidental
27128        // downgrade to non-`const` fails the wrapper at caixa-core build
27129        // time with E0015 (`cannot call non-const method`), strictly
27130        // stronger than a runtime `assert!` and strictly stronger than a
27131        // module-scope `const _: () = assert!(…)` pin (the type's
27132        // `String` / `Option<String>` carriers rule out `const`-context
27133        // value construction; the `const fn` wrapper is the load-bearing
27134        // shape that side-steps the destructor-in-const restriction on
27135        // the value axis while still pinning the `const`-fn posture on
27136        // the callee — mirror of the sibling
27137        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
27138        // (279823b) and
27139        // [`wit_contract_identity_projection_accessor_is_const_fn`]
27140        // (1ab648c) pins' discipline verbatim on the peer scalar-
27141        // accessor and composite-projection surfaces). Closes the last
27142        // unlifted per-`:contratos` shape/identity predicate on the
27143        // const-eval surface — the peer WIT-shape-partition family
27144        // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
27145        // [`WitContract::is_store`] / [`WitContract::is_capability`]
27146        // already carried the `pub const fn` posture on the peer
27147        // WIT-world-ref classifier axis (d46420c / 84c2325 / 279823b);
27148        // this pin extends the same posture onto the caller-callee
27149        // identity-space partition. Sweeps every WIT-shape arm on both
27150        // the equal-endpoints (self-edge) and distinct-endpoints
27151        // (inter-edge) arms of the identity-space partition, plus one
27152        // same-length distinct-byte pair to pin the mid-loop `!=` arm
27153        // past the leading length-mismatch shortcut.
27154        const fn is_self_loop_via_const_fn(c: &WitContract) -> bool {
27155            c.is_self_loop()
27156        }
27157        let mk = |de: &str, para: &str, wit: &str| WitContract {
27158            de: de.into(),
27159            para: para.into(),
27160            wit: wit.into(),
27161            endpoint: None,
27162            subject: None,
27163            slot: None,
27164        };
27165        for (nome, wit) in [
27166            ("cart", "wasi:http/proxy"),
27167            ("checkout", "nats:pub-sub"),
27168            ("kv", "wasi:keyvalue/store"),
27169            ("audit", "wasi:logging"),
27170        ] {
27171            let self_edge = mk(nome, nome, wit);
27172            assert!(
27173                is_self_loop_via_const_fn(&self_edge),
27174                "self-edge {nome:?} under {wit:?}"
27175            );
27176            assert_eq!(
27177                is_self_loop_via_const_fn(&self_edge),
27178                self_edge.is_self_loop()
27179            );
27180        }
27181        for (de, para, wit) in [
27182            ("cart", "catalog", "wasi:http/proxy"),
27183            ("checkout", "orders", "nats:pub-sub"),
27184            ("cart", "kv", "wasi:keyvalue/store"),
27185            ("audit", "sink", "wasi:logging"),
27186        ] {
27187            let inter_edge = mk(de, para, wit);
27188            assert!(
27189                !is_self_loop_via_const_fn(&inter_edge),
27190                "inter-edge {de:?}→{para:?} under {wit:?}",
27191            );
27192            assert_eq!(
27193                is_self_loop_via_const_fn(&inter_edge),
27194                inter_edge.is_self_loop()
27195            );
27196        }
27197        // Same-length distinct-byte pair — pins the mid-loop `!=` arm
27198        // past the leading `a.len() != b.len()` shortcut so the const-fn
27199        // wrapper exercises every arm of the byte-slice equality loop.
27200        let same_len_pair = mk("cart", "kart", "wasi:http/proxy");
27201        assert!(
27202            !is_self_loop_via_const_fn(&same_len_pair),
27203            "same-length distinct-byte"
27204        );
27205        assert_eq!(
27206            is_self_loop_via_const_fn(&same_len_pair),
27207            same_len_pair.is_self_loop()
27208        );
27209    }
27210
27211    #[test]
27212    fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
27213        // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
27214        // pin: [`WitContract::endpoint`] must return the `:contratos
27215        // :endpoint` field byte-for-byte, borrowed from the typed slot's
27216        // own `Option<String>` storage. Peer of the sibling
27217        // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
27218        // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
27219        // mesh-slot `Option<String>` optional-scalar axes — same "the
27220        // substrate-primitive accessor must byte-equal the raw field
27221        // access verbatim across every author-declared value" discipline
27222        // extended to the per-`:contratos` HTTP-payload-carrier arm.
27223        // Pins against a future silent detour that re-canonicalized the
27224        // endpoint (an accidental percent-encoding pass that didn't
27225        // reach the peer field-access site at the dedup key, a per-CR
27226        // fully-qualified prefix rewrite the operator authors on one
27227        // consumer without the other, or an M4 typed-path-template
27228        // `Display` re-canonicalization that silently drifted the
27229        // printer output from the source `caixa.lisp`). Four values
27230        // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
27231        // gate upstream admits (short root-path, dashed, param-shaped,
27232        // deep-hierarchy).
27233        for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
27234            let c = WitContract {
27235                de: "cart".into(),
27236                para: "catalog".into(),
27237                wit: "wasi:http/proxy".into(),
27238                endpoint: Some(endpoint.into()),
27239                subject: None,
27240                slot: None,
27241            };
27242            assert_eq!(
27243                c.endpoint(),
27244                Some(endpoint),
27245                "WitContract::endpoint must return :contratos :endpoint \
27246                 verbatim (got {:?}, expected Some({endpoint:?}))",
27247                c.endpoint(),
27248            );
27249            assert_eq!(
27250                c.endpoint(),
27251                c.endpoint.as_deref(),
27252                "WitContract::endpoint must byte-equal the .endpoint \
27253                 field's `.as_deref()` projection",
27254            );
27255        }
27256    }
27257
27258    #[test]
27259    fn wit_contract_endpoint_none_when_field_is_none() {
27260        // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
27261        // payload-carrier accessor pin: when the typed slot is absent —
27262        // the canonical shape under a non-HTTP `:wit` world per the
27263        // [`WitContract::target`]-enforced shape ↔ target partition
27264        // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
27265        // carries `:slot`, [`WitTarget::Capability`] carries none) —
27266        // [`WitContract::endpoint`] must return `None`. Pins against a
27267        // future silent detour that projected the absent slot to a
27268        // `Some("")` empty-string default (the canonical `Option<String>`
27269        // → `String` collapse footgun the sibling M2
27270        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
27271        // emptiness predicates already guard on the peer M2 typed-slot
27272        // surfaces), a `Some("None")` stringified-None round-trip, or a
27273        // `Some` arm whose contents were derived from a sibling slot (an
27274        // accidental fallback to the `:subject` / `:slot` payload that
27275        // read the pub-sub / store payload into the endpoint axis).
27276        // Three contracts sweep the accept-set every non-HTTP `:wit`
27277        // world lands on — pub-sub NATS, key/value, and payload-less
27278        // capability.
27279        for (wit, subject, slot) in [
27280            ("nats:pub-sub", Some("orders.paid"), None),
27281            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
27282            ("wasi:cli/environment", None, None),
27283        ] {
27284            let c = WitContract {
27285                de: "cart".into(),
27286                para: "downstream".into(),
27287                wit: wit.into(),
27288                endpoint: None,
27289                subject: subject.map(str::to_string),
27290                slot: slot.map(str::to_string),
27291            };
27292            assert!(
27293                c.endpoint().is_none(),
27294                "WitContract::endpoint must return None when the typed \
27295                 slot is absent under :wit {wit:?} (got {:?})",
27296                c.endpoint(),
27297            );
27298            assert_eq!(
27299                c.endpoint(),
27300                c.endpoint.as_deref(),
27301                "WitContract::endpoint must byte-equal the .endpoint \
27302                 field's `.as_deref()` projection in the absent arm",
27303            );
27304        }
27305    }
27306
27307    #[test]
27308    fn wit_contract_endpoint_borrows_from_endpoint_storage() {
27309        // The borrow-not-copy pin: [`WitContract::endpoint`] must return
27310        // an `Option<&str>` whose `Some` arm borrows from the typed
27311        // slot's own [`String`] storage — same-address invariant with
27312        // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
27313        // detour that allocated a fresh `String`
27314        // (`self.endpoint.clone().map(...)` in the body would type-check
27315        // but silently drop the borrow, and every downstream consumer
27316        // that assumed the returned slice outlives `&self` would break
27317        // on a stale-reference use-after-free — the [`WitContract::target`]
27318        // Http-arm payload extraction rebinds the returned `Option<&str>`
27319        // through `.ok_or_else(...)` and threads the `&str` payload into
27320        // [`WitTarget::Http { endpoint: &'a str }`], the
27321        // [`AplicacaoSpec::validate`] duplicate-`:contratos`
27322        // [`ContratoIdentity`] dedup key threads the returned
27323        // `Option<&str>` into the six-tuple's HTTP arm — each borrow
27324        // from the WitContract's own storage and each would silently
27325        // misbehave if this accessor produced a detached copy). Peer of
27326        // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
27327        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
27328        // shaped optional-scalar axes — first extension of the
27329        // `Option<&str>` borrow-not-copy discipline onto the
27330        // per-`:contratos` HTTP-shaped payload-carrier axis.
27331        let c = WitContract {
27332            de: "cart".into(),
27333            para: "catalog".into(),
27334            wit: "wasi:http/proxy".into(),
27335            endpoint: Some("/lookup".into()),
27336            subject: None,
27337            slot: None,
27338        };
27339        let ep = c.endpoint().expect("Some arm");
27340        let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
27341        assert_eq!(
27342            ep.as_ptr(),
27343            storage_slice.as_ptr(),
27344            "WitContract::endpoint must borrow from the .endpoint \
27345             String's backing storage — a fresh allocation here means \
27346             the accessor no longer names the substrate-primitive typed \
27347             dispatch and every downstream consumer would silently \
27348             carry a detached copy",
27349        );
27350        assert_eq!(
27351            ep.len(),
27352            storage_slice.len(),
27353            "WitContract::endpoint and .endpoint.as_deref() must byte-\
27354             equal in length as well as in address",
27355        );
27356    }
27357
27358    #[test]
27359    fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
27360        // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
27361        // pin: [`WitContract::subject`] must return the `:contratos
27362        // :subject` field byte-for-byte, borrowed from the typed slot's
27363        // own `Option<String>` storage. Peer of the sibling per-`:contratos`
27364        // [`WitContract::endpoint`] (7020470) accessor pin on the M3
27365        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
27366        // optional-scalar axis — same "the substrate-primitive accessor
27367        // must byte-equal the raw field access verbatim across every
27368        // author-declared value" discipline extended to the pub-sub arm.
27369        // Pins against a future silent detour that re-canonicalized the
27370        // subject (an accidental `.to_lowercase()` normalization that
27371        // didn't reach the peer field-access site at the dedup key, a
27372        // per-CR fully-qualified prefix rewrite the operator authors on
27373        // one consumer without the other, or an M4 typed-subject-template
27374        // `Display` re-canonicalization that silently drifted the printer
27375        // output from the source `caixa.lisp`). Four values sweep the
27376        // NATS accept-set every pub-sub author-declared subject lands on
27377        // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
27378        for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
27379            let c = WitContract {
27380                de: "cart".into(),
27381                para: "notifier".into(),
27382                wit: "nats:pub-sub".into(),
27383                endpoint: None,
27384                subject: Some(subject.into()),
27385                slot: None,
27386            };
27387            assert_eq!(
27388                c.subject(),
27389                Some(subject),
27390                "WitContract::subject must return :contratos :subject \
27391                 verbatim (got {:?}, expected Some({subject:?}))",
27392                c.subject(),
27393            );
27394            assert_eq!(
27395                c.subject(),
27396                c.subject.as_deref(),
27397                "WitContract::subject must byte-equal the .subject \
27398                 field's `.as_deref()` projection",
27399            );
27400        }
27401    }
27402
27403    #[test]
27404    fn wit_contract_subject_none_when_field_is_none() {
27405        // The absent-`:subject` arm of the per-`:contratos` pub-sub-
27406        // shaped payload-carrier accessor pin: when the typed slot is
27407        // absent — the canonical shape under a non-pub-sub `:wit` world
27408        // per the [`WitContract::target`]-enforced shape ↔ target
27409        // partition ([`WitTarget::Http`] carries `:endpoint`,
27410        // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
27411        // carries none) — [`WitContract::subject`] must return `None`.
27412        // Pins against a future silent detour that projected the absent
27413        // slot to a `Some("")` empty-string default (the canonical
27414        // `Option<String>` → `String` collapse footgun the sibling M2
27415        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
27416        // emptiness predicates already guard on the peer M2 typed-slot
27417        // surfaces), a `Some("None")` stringified-None round-trip, or a
27418        // `Some` arm whose contents were derived from a sibling slot (an
27419        // accidental fallback to the `:endpoint` / `:slot` payload that
27420        // read the HTTP / store payload into the subject axis). Three
27421        // contracts sweep the accept-set every non-pub-sub `:wit` world
27422        // lands on — HTTP proxy, key/value store, and payload-less
27423        // capability.
27424        for (wit, endpoint, slot) in [
27425            ("wasi:http/proxy", Some("/lookup"), None),
27426            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
27427            ("wasi:cli/environment", None, None),
27428        ] {
27429            let c = WitContract {
27430                de: "cart".into(),
27431                para: "downstream".into(),
27432                wit: wit.into(),
27433                endpoint: endpoint.map(str::to_string),
27434                subject: None,
27435                slot: slot.map(str::to_string),
27436            };
27437            assert!(
27438                c.subject().is_none(),
27439                "WitContract::subject must return None when the typed \
27440                 slot is absent under :wit {wit:?} (got {:?})",
27441                c.subject(),
27442            );
27443            assert_eq!(
27444                c.subject(),
27445                c.subject.as_deref(),
27446                "WitContract::subject must byte-equal the .subject \
27447                 field's `.as_deref()` projection in the absent arm",
27448            );
27449        }
27450    }
27451
27452    #[test]
27453    fn wit_contract_subject_borrows_from_subject_storage() {
27454        // The borrow-not-copy pin: [`WitContract::subject`] must return
27455        // an `Option<&str>` whose `Some` arm borrows from the typed
27456        // slot's own [`String`] storage — same-address invariant with
27457        // `c.subject.as_deref().unwrap()`. Pins against a future silent
27458        // detour that allocated a fresh `String`
27459        // (`self.subject.clone().map(...)` in the body would type-check
27460        // but silently drop the borrow, and every downstream consumer
27461        // that assumed the returned slice outlives `&self` would break
27462        // on a stale-reference use-after-free — the [`WitContract::target`]
27463        // PubSub-arm payload extraction rebinds the returned
27464        // `Option<&str>` through `.ok_or_else(...)` and threads the
27465        // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
27466        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
27467        // [`ContratoIdentity`] dedup key threads the returned
27468        // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
27469        // from the WitContract's own storage and each would silently
27470        // misbehave if this accessor produced a detached copy). Peer of
27471        // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
27472        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
27473        // shaped optional-scalar axis — second extension of the
27474        // `Option<&str>` borrow-not-copy discipline onto the
27475        // per-`:contratos` payload-carrier family, this time on the
27476        // pub-sub arm.
27477        let c = WitContract {
27478            de: "cart".into(),
27479            para: "notifier".into(),
27480            wit: "nats:pub-sub".into(),
27481            endpoint: None,
27482            subject: Some("orders.paid".into()),
27483            slot: None,
27484        };
27485        let sub = c.subject().expect("Some arm");
27486        let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
27487        assert_eq!(
27488            sub.as_ptr(),
27489            storage_slice.as_ptr(),
27490            "WitContract::subject must borrow from the .subject \
27491             String's backing storage — a fresh allocation here means \
27492             the accessor no longer names the substrate-primitive typed \
27493             dispatch and every downstream consumer would silently \
27494             carry a detached copy",
27495        );
27496        assert_eq!(
27497            sub.len(),
27498            storage_slice.len(),
27499            "WitContract::subject and .subject.as_deref() must byte-\
27500             equal in length as well as in address",
27501        );
27502    }
27503
27504    #[test]
27505    fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
27506        // The canonical per-`:contratos` key/value-store-shaped
27507        // `:slot`-scalar pin: [`WitContract::slot`] must return the
27508        // `:contratos :slot` field byte-for-byte, borrowed from the
27509        // typed slot's own `Option<String>` storage. Peer of the
27510        // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
27511        // [`WitContract::subject`] (90de675) accessor pins on the M3
27512        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
27513        // optional-scalar axis — same "the substrate-primitive
27514        // accessor must byte-equal the raw field access verbatim
27515        // across every author-declared value" discipline extended to
27516        // the store arm. Pins against a future silent detour that
27517        // re-canonicalized the slot template (an accidental
27518        // `.to_lowercase()` bucket-prefix normalization that didn't
27519        // reach the peer field-access site at the dedup key, a per-CR
27520        // fully-qualified prefix rewrite the operator authors on one
27521        // consumer without the other, or an M4 typed-key-template
27522        // `Display` re-canonicalization that silently drifted the
27523        // printer output from the source `caixa.lisp`). Four values
27524        // sweep the wasi:keyvalue accept-set every store-shaped
27525        // author-declared slot lands on (flat bucket, single-param
27526        // template, multi-param template, nested-hierarchy template).
27527        for slot in [
27528            "sessions",
27529            "carts/{cart_id}",
27530            "orders/{tenant}/{order_id}",
27531            "cache/tenant-a/orders/{id}",
27532        ] {
27533            let c = WitContract {
27534                de: "cart".into(),
27535                para: "kv".into(),
27536                wit: "wasi:keyvalue/store".into(),
27537                endpoint: None,
27538                subject: None,
27539                slot: Some(slot.into()),
27540            };
27541            assert_eq!(
27542                c.slot(),
27543                Some(slot),
27544                "WitContract::slot must return :contratos :slot \
27545                 verbatim (got {:?}, expected Some({slot:?}))",
27546                c.slot(),
27547            );
27548            assert_eq!(
27549                c.slot(),
27550                c.slot.as_deref(),
27551                "WitContract::slot must byte-equal the .slot field's \
27552                 `.as_deref()` projection",
27553            );
27554        }
27555    }
27556
27557    #[test]
27558    fn wit_contract_slot_none_when_field_is_none() {
27559        // The absent-`:slot` arm of the per-`:contratos` store-shaped
27560        // payload-carrier accessor pin: when the typed slot is absent —
27561        // the canonical shape under a non-store `:wit` world per the
27562        // [`WitContract::target`]-enforced shape ↔ target partition
27563        // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
27564        // carries `:subject`, [`WitTarget::Capability`] carries none) —
27565        // [`WitContract::slot`] must return `None`. Pins against a
27566        // future silent detour that projected the absent slot to a
27567        // `Some("")` empty-string default (the canonical
27568        // `Option<String>` → `String` collapse footgun the sibling M2
27569        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
27570        // emptiness predicates already guard on the peer M2 typed-slot
27571        // surfaces), a `Some("None")` stringified-None round-trip, or
27572        // a `Some` arm whose contents were derived from a sibling
27573        // slot (an accidental fallback to the `:endpoint` / `:subject`
27574        // payload that read the HTTP / pub-sub payload into the store
27575        // axis). Three contracts sweep the accept-set every non-store
27576        // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
27577        // payload-less capability.
27578        for (wit, endpoint, subject) in [
27579            ("wasi:http/proxy", Some("/lookup"), None),
27580            ("nats:pub-sub", None, Some("orders.paid")),
27581            ("wasi:cli/environment", None, None),
27582        ] {
27583            let c = WitContract {
27584                de: "cart".into(),
27585                para: "downstream".into(),
27586                wit: wit.into(),
27587                endpoint: endpoint.map(str::to_string),
27588                subject: subject.map(str::to_string),
27589                slot: None,
27590            };
27591            assert!(
27592                c.slot().is_none(),
27593                "WitContract::slot must return None when the typed \
27594                 slot is absent under :wit {wit:?} (got {:?})",
27595                c.slot(),
27596            );
27597            assert_eq!(
27598                c.slot(),
27599                c.slot.as_deref(),
27600                "WitContract::slot must byte-equal the .slot field's \
27601                 `.as_deref()` projection in the absent arm",
27602            );
27603        }
27604    }
27605
27606    #[test]
27607    fn wit_contract_slot_borrows_from_slot_storage() {
27608        // The borrow-not-copy pin: [`WitContract::slot`] must return
27609        // an `Option<&str>` whose `Some` arm borrows from the typed
27610        // slot's own [`String`] storage — same-address invariant with
27611        // `c.slot.as_deref().unwrap()`. Pins against a future silent
27612        // detour that allocated a fresh `String`
27613        // (`self.slot.clone().map(...)` in the body would type-check
27614        // but silently drop the borrow, and every downstream consumer
27615        // that assumed the returned slice outlives `&self` would
27616        // break on a stale-reference use-after-free — the
27617        // [`WitContract::target`] Store-arm payload extraction rebinds
27618        // the returned `Option<&str>` through `.ok_or_else(...)` and
27619        // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
27620        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
27621        // [`ContratoIdentity`] dedup key threads the returned
27622        // `Option<&str>` into the six-tuple's store arm — each borrow
27623        // from the WitContract's own storage and each would silently
27624        // misbehave if this accessor produced a detached copy). Peer
27625        // of the sibling per-`:contratos` [`WitContract::endpoint`]
27626        // (7020470) / [`WitContract::subject`] (90de675)
27627        // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
27628        // shaped optional-scalar axis — third and final extension of
27629        // the `Option<&str>` borrow-not-copy discipline onto the
27630        // per-`:contratos` payload-carrier family, this time on the
27631        // store arm.
27632        let c = WitContract {
27633            de: "cart".into(),
27634            para: "kv".into(),
27635            wit: "wasi:keyvalue/store".into(),
27636            endpoint: None,
27637            subject: None,
27638            slot: Some("carts/{cart_id}".into()),
27639        };
27640        let slot = c.slot().expect("Some arm");
27641        let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
27642        assert_eq!(
27643            slot.as_ptr(),
27644            storage_slice.as_ptr(),
27645            "WitContract::slot must borrow from the .slot String's \
27646             backing storage — a fresh allocation here means the \
27647             accessor no longer names the substrate-primitive typed \
27648             dispatch and every downstream consumer would silently \
27649             carry a detached copy",
27650        );
27651        assert_eq!(
27652            slot.len(),
27653            storage_slice.len(),
27654            "WitContract::slot and .slot.as_deref() must byte-equal \
27655             in length as well as in address",
27656        );
27657    }
27658
27659    #[test]
27660    fn membro_nome_returns_caixa_byte_equal_across_permutations() {
27661        // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
27662        // [`Membro::nome`] must return the `:membros :caixa` field
27663        // byte-for-byte, borrowed from the typed slot's own [`String`]
27664        // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
27665        // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
27666        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
27667        // slot-atom scalar-value axes — same "the substrate-primitive
27668        // accessor must byte-equal the raw field access verbatim across
27669        // every author-declared value" discipline extended to the
27670        // per-`:membros` member-identity arm. Pins against a future
27671        // silent detour that re-normalized the member identity (an
27672        // accidental `.to_lowercase()` — every `:membros :caixa` is
27673        // validated as a DNS-1123 label upstream via
27674        // [`validate_membro_caixa`], so any re-normalization is
27675        // redundant + a drift surface between the validator and the
27676        // accessor), a namespace-prefix rewrite (an accidental
27677        // `format!("{namespace}/{caixa}")` per-CR fully-qualified
27678        // rewrite that didn't land on the peer axes), or a per-cluster
27679        // alias stamp the operator authors on one consumer without the
27680        // other. Four values sweep the accept-set the DNS-1123 gate
27681        // upstream admits (short single-word / dashed / v-suffixed
27682        // member names).
27683        for name in ["cart", "checkout", "catalog", "orders-v2"] {
27684            let m = Membro {
27685                caixa: name.into(),
27686                versao: "^0.1".into(),
27687            };
27688            assert_eq!(
27689                m.nome(),
27690                name,
27691                "Membro::nome must return :membros :caixa verbatim \
27692                 (got {:?}, expected {name:?})",
27693                m.nome(),
27694            );
27695            assert_eq!(
27696                m.nome(),
27697                m.caixa.as_str(),
27698                "Membro::nome must byte-equal the .caixa field access",
27699            );
27700        }
27701    }
27702
27703    #[test]
27704    fn membro_nome_borrows_from_caixa_storage() {
27705        // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
27706        // slice that borrows from the typed slot's own [`String`]
27707        // storage — same-address invariant with `m.caixa.as_str()`. Pins
27708        // against a future silent detour that allocated a fresh `String`
27709        // (`self.caixa.clone()` in the body would type-check but
27710        // silently drop the borrow, and every downstream consumer that
27711        // assumed the returned slice outlives `&self` would break on a
27712        // stale-reference use-after-free — the `HashSet<&str>` collector
27713        // at [`AplicacaoSpec::validate`]'s `names` seed, the
27714        // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
27715        // [`AplicacaoSpec::detect_sync_cycles`], the
27716        // [`crate::render::insert_first_seen`] dedup key at
27717        // [`AplicacaoSpec::validate_membros`] — each borrow from the
27718        // Membro's own storage and each would silently misbehave if
27719        // this accessor produced a detached copy). Peer of the sibling
27720        // per-`:contratos` [`WitContract::source`] /
27721        // [`WitContract::destination`] and per-`:entrada`
27722        // [`Entrada::destination`] borrow-invariant pins on the mesh-
27723        // slot-atom scalar-value axes.
27724        let m = Membro {
27725            caixa: "checkout".into(),
27726            versao: "^0.1".into(),
27727        };
27728        let name = m.nome();
27729        let caixa_slice = m.caixa.as_str();
27730        assert_eq!(
27731            name.as_ptr(),
27732            caixa_slice.as_ptr(),
27733            "Membro::nome must borrow from the .caixa String's backing \
27734             storage — a fresh allocation here means the accessor no \
27735             longer names the substrate-primitive typed dispatch and \
27736             every downstream consumer would silently carry a detached \
27737             copy",
27738        );
27739        assert_eq!(
27740            name.len(),
27741            caixa_slice.len(),
27742            "Membro::nome and .caixa.as_str() must byte-equal in length \
27743             as well as in address",
27744        );
27745    }
27746
27747    #[test]
27748    fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
27749        // The canonical per-`:membros` member-`:versao`-scalar pin:
27750        // [`Membro::versao_requirement`] must return the
27751        // `:membros :versao` field byte-for-byte, borrowed from the typed
27752        // slot's own [`String`] storage. Sibling of the peer
27753        // `membro_nome_returns_caixa_byte_equal_across_permutations`
27754        // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
27755        // — same "the substrate-primitive accessor must byte-equal the
27756        // raw field access verbatim across every author-declared value"
27757        // discipline extended to the per-`:membros` member-`:versao`
27758        // requirement-string arm. Pins against a future silent detour
27759        // that re-canonicalized the requirement (an accidental
27760        // `.to_string()` via [`parse_requirement`] → [`Display`] round-
27761        // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
27762        // drifted the printer output away from the source `caixa.lisp`,
27763        // an accidental whitespace trim on `"^ 0.1"` that no consumer
27764        // ever produced from the field-access side, an accidental
27765        // per-cluster lacre-projected concrete-version rewrite that
27766        // didn't land on the peer field-access sites). Five values sweep
27767        // the accept-set the shared
27768        // [`crate::render::require_valid_versao_requirement`] gate
27769        // admits (caret / tilde / exact / wildcard / bare-major).
27770        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
27771            let m = Membro {
27772                caixa: "cart".into(),
27773                versao: req.into(),
27774            };
27775            assert_eq!(
27776                m.versao_requirement(),
27777                req,
27778                "Membro::versao_requirement must return :membros :versao \
27779                 verbatim (got {:?}, expected {req:?})",
27780                m.versao_requirement(),
27781            );
27782            assert_eq!(
27783                m.versao_requirement(),
27784                m.versao.as_str(),
27785                "Membro::versao_requirement must byte-equal the .versao \
27786                 field access",
27787            );
27788        }
27789    }
27790
27791    #[test]
27792    fn membro_versao_requirement_borrows_from_versao_storage() {
27793        // The borrow-not-copy pin: [`Membro::versao_requirement`] must
27794        // return a `&str` slice that borrows from the typed slot's own
27795        // [`String`] storage — same-address invariant with
27796        // `m.versao.as_str()`. Pins against a future silent detour that
27797        // allocated a fresh `String` (`self.versao.clone()` in the body
27798        // would type-check but silently drop the borrow, and every
27799        // downstream consumer that assumed the returned slice outlives
27800        // `&self` would break on a stale-reference use-after-free). Peer
27801        // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
27802        // per-`:contratos` [`WitContract::source`] /
27803        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
27804        // [`Entrada::destination`] (6db982c) borrow-invariant pins on
27805        // the mesh-slot-atom scalar-value axes.
27806        let m = Membro {
27807            caixa: "checkout".into(),
27808            versao: "^0.1".into(),
27809        };
27810        let req = m.versao_requirement();
27811        let versao_slice = m.versao.as_str();
27812        assert_eq!(
27813            req.as_ptr(),
27814            versao_slice.as_ptr(),
27815            "Membro::versao_requirement must borrow from the .versao \
27816             String's backing storage — a fresh allocation here means \
27817             the accessor no longer names the substrate-primitive typed \
27818             dispatch and every downstream consumer would silently carry \
27819             a detached copy",
27820        );
27821        assert_eq!(
27822            req.len(),
27823            versao_slice.len(),
27824            "Membro::versao_requirement and .versao.as_str() must byte-\
27825             equal in length as well as in address",
27826        );
27827    }
27828
27829    #[test]
27830    fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
27831        // Sibling-pair invariant pin composing both per-`:membros`
27832        // substrate-primitive typed dispatches — [`Membro::nome`]
27833        // (4a32abf) and [`Membro::versao_requirement`] — at the joint
27834        // `(nome(), versao_requirement())` call shape every renderer
27835        // that fans on per-member identity + version pin keys off. The
27836        // invariant, evaluated per-member:
27837        //
27838        //   (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
27839        //
27840        // Closes the last unlifted per-`:membros` scalar axis — every
27841        // downstream consumer that reads the pair now routes through
27842        // exactly two typed dispatches on the substrate primitive, not
27843        // one typed + one open-coded field access. A future refactor
27844        // that silently split either accessor's projection (an
27845        // accidental `nome()` namespace-prefix rewrite that didn't
27846        // reach the peer, an accidental `versao_requirement()` lacre-
27847        // projected concrete-version rewrite that didn't land on the
27848        // `nome()` peer) surfaces at caixa-core build time. Peer of the
27849        // sibling per-`:entrada` `(hostname(), destination())` and
27850        // per-`:contratos` `(source(), destination())` pair invariants
27851        // on the mesh-slot-atom scalar-value axes.
27852        for (caixa, versao) in [
27853            ("cart", "^0.1"),
27854            ("checkout", "~0.1.2"),
27855            ("catalog", "0.1.0"),
27856            ("orders-v2", "*"),
27857        ] {
27858            let m = Membro {
27859                caixa: caixa.into(),
27860                versao: versao.into(),
27861            };
27862            assert_eq!(
27863                (m.nome(), m.versao_requirement()),
27864                (m.caixa.as_str(), m.versao.as_str()),
27865                "(Membro::nome, Membro::versao_requirement) must project \
27866                 (.caixa, .versao) verbatim across every author-declared \
27867                 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
27868                m.nome(),
27869                m.versao_requirement(),
27870            );
27871        }
27872    }
27873
27874    #[test]
27875    fn validate_membros_empty_gate_routes_through_nome_accessor() {
27876        // Composition pin: [`AplicacaoSpec::validate_membros`]'s
27877        // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
27878        // not the raw `.caixa` field access. Structurally: setting
27879        // ONLY the `.caixa` field to `""` on an otherwise-well-formed
27880        // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
27881        // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
27882        // (i.e. the empty string) — so the emptiness predicate the
27883        // refusal arm reaches under is the accessor-projected value,
27884        // not a peer field that would silently drift under a future
27885        // accessor-side rewrite.
27886        //
27887        // Pins against a future silent detour that (a) re-derived the
27888        // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
27889        // instead of `self.nome().is_empty()`, silently disagreeing with
27890        // every peer consumer (the `validate_membro_caixa(m.nome())`
27891        // per-slot helper — which now owns the emptiness arm outright —
27892        // the dedup-key `insert_first_seen(&mut seen, m.nome(), …)`
27893        // below, and the emit-side per-`programs[]` entry-`name:` at
27894        // caixa-mesh/src/lib.rs:133), (b) accessor-side introduced a
27895        // per-tenant alias arm the caller was unaware of, silently
27896        // rewriting an author-declared `:caixa "checkout"` to `""` —
27897        // the raw-field-access gate would fail-open while the
27898        // accessor-routed peer consumers would fail-closed, splitting
27899        // the diagnostic from the actual failure surface.
27900        //
27901        // Peer of the sibling
27902        // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
27903        // (c0110f1) composition pin — same "the shape-gate predicate
27904        // must route through the substrate-primitive typed dispatch"
27905        // discipline extended onto the per-`:membros` empty-`:caixa`
27906        // refusal-arm axis. Closes the last unlifted `.caixa` production-
27907        // code read site on `Membro` — after this converge every
27908        // caixa-core `.caixa` field access outside the accessor's own
27909        // body is either a test-side field-setter (in-module tests
27910        // constructing invalid-shape inputs) or a doc-comment reference.
27911        let mut s = three_member_spec();
27912        s.membros[1].caixa = String::new();
27913        assert!(
27914            s.membros[1].nome().is_empty(),
27915            "Membro::nome must byte-equal the .caixa field access — an \
27916             accessor-side detour that no longer projects the raw field \
27917             would silently split this drift-detection test from the \
27918             validate() refusal arm",
27919        );
27920        assert_eq!(
27921            s.membros[1].nome(),
27922            s.membros[1].caixa.as_str(),
27923            "Membro::nome and .caixa.as_str() must byte-equal on an \
27924             empty-`:caixa` entry — the emptiness gate keys off the \
27925             accessor by construction",
27926        );
27927        assert_eq!(
27928            s.validate().unwrap_err(),
27929            AplicacaoError::MembroCaixaEmpty,
27930            "validate_membros' emptiness gate must fire MembroCaixaEmpty \
27931             on an entry whose accessor-projected `nome()` is empty",
27932        );
27933    }
27934
27935    #[test]
27936    fn validate_membros_empty_arm_is_owned_by_validate_membro_caixa_alone() {
27937        // Convergence pin, paired with the deletion of the redundant
27938        // outer `if m.nome().is_empty() { return Err(MembroCaixaEmpty); }`
27939        // guard formerly inline in [`AplicacaoSpec::validate_membros`]:
27940        // after the collapse, the `MembroCaixaEmpty` refusal on every
27941        // empty-`:caixa` per-member input is owned solely by the shared
27942        // [`validate_membro_caixa`] helper — the same per-slot substrate
27943        // primitive routing empty + shape arms uniformly onto
27944        // [`crate::render::require_valid_dns_1123_label`] that every
27945        // peer M3 mesh-slot per-slot gate ([`validate_placement_cluster`]
27946        // on `:placement :clusters`, [`validate_entrada_para`] on
27947        // `:entrada :para`, [`validate_contrato_caixa`] on `:contratos
27948        // :de`/`:para`) already funnels its own empty arm through.
27949        //
27950        // Two arms pin the collapse:
27951        //
27952        //   (1) The per-slot helper called with the empty string returns
27953        //       byte-equal to the previous inline arm's diagnostic — so
27954        //       a future rebrand of [`validate_membro_caixa`] that
27955        //       (accidentally) stopped returning [`MembroCaixaEmpty`] on
27956        //       empty input (an inadvertent switch to
27957        //       [`AplicacaoError::MembroCaixaInvalid`] via the parse-side
27958        //       `on_invalid` arm, an accidental re-routing to a shared
27959        //       `MembroError::Empty` under a future error-hierarchy
27960        //       flattening) would silently split the drift from the
27961        //       [`validate_membros`] caller and surface the wrong
27962        //       diagnostic on the author-facing empty-`:caixa` footgun.
27963        //
27964        //   (2) The whole-spec equivalence: an empty-`:caixa` entry
27965        //       anywhere in the `:membros` fan-out still trips
27966        //       [`MembroCaixaEmpty`] end-to-end via [`validate`], with
27967        //       no outer inline guard needed. Same shape as the
27968        //       whole-spec arm on [`validate_placement_cluster`] /
27969        //       [`validate_entrada_para`] / [`validate_contrato_caixa`]:
27970        //       one substrate primitive per axis, folding empty + shape.
27971        //
27972        // Same PRIME DIRECTIVE convergence the peer per-slot gate lifts
27973        // (906a5c6 validate_contratos, 20cd523 validate_entrada, f03a154
27974        // MeshPolicy::validate) already extend across the M3 mesh-slot
27975        // family — closes the last per-slot gate on the family carrying
27976        // an inline empty guard duplicating its own helper.
27977        assert_eq!(
27978            validate_membro_caixa(""),
27979            Err(AplicacaoError::MembroCaixaEmpty),
27980            "validate_membro_caixa must own the empty arm outright — a \
27981             regression here would silently split MembroCaixaEmpty from \
27982             validate_membros' end-to-end refusal shape after the outer \
27983             inline `if m.nome().is_empty()` guard collapse",
27984        );
27985        let mut s = three_member_spec();
27986        s.membros[0].caixa = String::new();
27987        assert_eq!(
27988            s.validate().unwrap_err(),
27989            AplicacaoError::MembroCaixaEmpty,
27990            "an empty-`:caixa` :membros head entry must trip \
27991             MembroCaixaEmpty end-to-end via validate() with the outer \
27992             inline guard removed — the per-slot helper alone is now \
27993             load-bearing",
27994        );
27995        let mut s = three_member_spec();
27996        s.membros[2].caixa = String::new();
27997        assert_eq!(
27998            s.validate().unwrap_err(),
27999            AplicacaoError::MembroCaixaEmpty,
28000            "an empty-`:caixa` :membros tail entry must trip \
28001             MembroCaixaEmpty end-to-end via validate() with the outer \
28002             inline guard removed — the per-slot helper alone reaches \
28003             every fan-out position",
28004        );
28005    }
28006
28007    #[test]
28008    fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
28009        // The canonical per-`:placement` Akka-cluster-sharding
28010        // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
28011        // the `:placement :shard-key` field byte-for-byte, borrowed
28012        // from the typed slot's own `Option<String>` storage. Peer of
28013        // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
28014        // per-`:contratos` [`WitContract::source`] /
28015        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
28016        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
28017        // slot-atom scalar-value axes — same "the substrate-primitive
28018        // accessor must byte-equal the raw field access verbatim across
28019        // every author-declared value" discipline extended to the
28020        // per-`:placement` Akka-cluster-sharding key extractor arm.
28021        // Pins against a future silent detour that re-normalized the
28022        // key (an accidental `.to_lowercase()` — every non-empty
28023        // `:shard-key` is validated as a printable-ASCII single-token
28024        // reference upstream via [`validate_placement_shard_key`], so
28025        // any re-normalization is redundant + a drift surface between
28026        // the validator and the accessor), a per-cluster alias rewrite
28027        // the operator authors on one consumer without the other, or an
28028        // accidental variable-prefix strip (`$tenantId` → `tenantId`)
28029        // that didn't land on the peer field-access sites. Four values
28030        // sweep the accept-set the shape gate admits — bare identifier,
28031        // `$`-prefixed variable, dotted path, `${}`-quoted variable —
28032        // the four canonical Akka-style entity-id extractor shapes the
28033        // future M4 cluster-sharding reconciler hashes.
28034        for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
28035            let p = Placement {
28036                estrategia: PlacementStrategy::Sharded,
28037                clusters: vec!["rio".into()],
28038                affinity: None,
28039                shard_key: Some(key.into()),
28040            };
28041            assert_eq!(
28042                p.shard_key(),
28043                Some(key),
28044                "Placement::shard_key must return :placement :shard-key \
28045                 verbatim (got {:?}, expected Some({key:?}))",
28046                p.shard_key(),
28047            );
28048            assert_eq!(
28049                p.shard_key(),
28050                p.shard_key.as_deref(),
28051                "Placement::shard_key must byte-equal the .shard_key \
28052                 field's `.as_deref()` projection",
28053            );
28054        }
28055    }
28056
28057    #[test]
28058    fn placement_shard_key_none_when_field_is_none() {
28059        // The absent-`:shard-key` arm of the per-`:placement`
28060        // Akka-cluster-sharding accessor pin: when the typed slot is
28061        // absent — the canonical shape under `:estrategia Replicated` /
28062        // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
28063        // enforced `shard_key.is_some() == matches!(estrategia,
28064        // Sharded)` partition — [`Placement::shard_key`] must return
28065        // `None`. Pins against a future silent detour that projected
28066        // the absent slot to a `Some("")` empty-string default (the
28067        // canonical `Option<String>` → `String` collapse footgun the
28068        // sibling M2 [`crate::LimitsSpec::is_empty`] /
28069        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
28070        // already guard on the peer M2 typed-slot surfaces), a
28071        // `Some("None")` stringified-None round-trip, or a `Some` arm
28072        // whose contents were derived from a sibling slot (an
28073        // accidental fallback to `estrategia.as_str()` that read the
28074        // strategy discriminator into the key axis). Two placements
28075        // sweep the accept-set every `validate`-passing non-`Sharded`
28076        // shape lands on — `Replicated` (Erlang/OTP distributed-app
28077        // takeover) and `SingleNode` (single-node hosting).
28078        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
28079            let p = Placement {
28080                estrategia,
28081                clusters: vec!["rio".into()],
28082                affinity: None,
28083                shard_key: None,
28084            };
28085            assert!(
28086                p.shard_key().is_none(),
28087                "Placement::shard_key must return None when the typed \
28088                 slot is absent under :estrategia {estrategia:?} (got {:?})",
28089                p.shard_key(),
28090            );
28091            assert_eq!(
28092                p.shard_key(),
28093                p.shard_key.as_deref(),
28094                "Placement::shard_key must byte-equal the .shard_key \
28095                 field's `.as_deref()` projection in the absent arm",
28096            );
28097        }
28098    }
28099
28100    #[test]
28101    fn placement_shard_key_borrows_from_shard_key_storage() {
28102        // The borrow-not-copy pin: [`Placement::shard_key`] must return
28103        // an `Option<&str>` whose `Some` arm borrows from the typed
28104        // slot's own [`String`] storage — same-address invariant with
28105        // `p.shard_key.as_deref().unwrap()`. Pins against a future
28106        // silent detour that allocated a fresh `String`
28107        // (`self.shard_key.clone().map(...)` in the body would type-
28108        // check but silently drop the borrow, and every downstream
28109        // consumer that assumed the returned slice outlives `&self`
28110        // would break on a stale-reference use-after-free — the
28111        // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
28112        // gate's `Some(k)`-bound match arm reads `k: &str` under the
28113        // accessor's return type and would silently misbehave if this
28114        // accessor produced a detached copy). Peer of the sibling
28115        // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
28116        // [`WitContract::source`] / [`WitContract::destination`]
28117        // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
28118        // (6db982c) borrow-invariant pins on the mesh-slot-atom
28119        // scalar-value axes — first extension of the discipline onto
28120        // an `Option<String>`-shaped optional-scalar axis.
28121        let p = Placement {
28122            estrategia: PlacementStrategy::Sharded,
28123            clusters: vec!["rio".into()],
28124            affinity: None,
28125            shard_key: Some("tenantId".into()),
28126        };
28127        let key = p.shard_key().expect("Some arm");
28128        let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
28129        assert_eq!(
28130            key.as_ptr(),
28131            storage_slice.as_ptr(),
28132            "Placement::shard_key must borrow from the .shard_key \
28133             String's backing storage — a fresh allocation here means \
28134             the accessor no longer names the substrate-primitive typed \
28135             dispatch and every downstream consumer would silently \
28136             carry a detached copy",
28137        );
28138        assert_eq!(
28139            key.len(),
28140            storage_slice.len(),
28141            "Placement::shard_key and .shard_key.as_deref() must byte-\
28142             equal in length as well as in address",
28143        );
28144    }
28145
28146    #[test]
28147    fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
28148        // The canonical per-`:placement` M3-Adaptive-compression-hint
28149        // scalar pin: [`Placement::affinity`] must return the
28150        // `:placement :affinity` field byte-for-byte, borrowed from the
28151        // typed slot's own `Option<String>` storage. Peer of the sibling
28152        // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
28153        // pin on the sibling `Option<&str>` optional-scalar axis — same
28154        // "the substrate-primitive accessor must byte-equal the raw
28155        // field access verbatim across every author-declared value"
28156        // discipline extended to the peer per-`:placement` M3-Adaptive-
28157        // compression-hint arm. Pins against a future silent detour
28158        // that re-normalized the hint (an accidental `.to_lowercase()`
28159        // — every `:affinity` is already validated as a DNS-1123 label
28160        // upstream via [`validate_placement_affinity`], so any re-
28161        // normalization is redundant + a drift surface between the
28162        // validator and the accessor), a per-cluster alias rewrite the
28163        // operator authors on one consumer without the other, or an
28164        // accidental hint-family collapse (`low-latency` → `latency`
28165        // that dropped the qualifier prefix). Four values sweep the
28166        // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
28167        // canonical adaptive-compression-weight biases the future M4
28168        // placement engine reads.
28169        for hint in [
28170            "data-locality",
28171            "low-latency",
28172            "high-throughput",
28173            "cost-optimized",
28174        ] {
28175            let p = Placement {
28176                estrategia: PlacementStrategy::Replicated,
28177                clusters: vec!["rio".into()],
28178                affinity: Some(hint.into()),
28179                shard_key: None,
28180            };
28181            assert_eq!(
28182                p.affinity(),
28183                Some(hint),
28184                "Placement::affinity must return :placement :affinity \
28185                 verbatim (got {:?}, expected Some({hint:?}))",
28186                p.affinity(),
28187            );
28188            assert_eq!(
28189                p.affinity(),
28190                p.affinity.as_deref(),
28191                "Placement::affinity must byte-equal the .affinity \
28192                 field's `.as_deref()` projection",
28193            );
28194        }
28195    }
28196
28197    #[test]
28198    fn placement_affinity_none_when_field_is_none() {
28199        // The absent-`:affinity` arm of the per-`:placement`
28200        // M3-Adaptive-compression-hint accessor pin: when the typed
28201        // slot is absent — the canonical shape of an Aplicacao that
28202        // leaves the compression weighting up to the placement engine's
28203        // cluster-default arm — [`Placement::affinity`] must return
28204        // `None`. Pins against a future silent detour that projected
28205        // the absent slot to a `Some("")` empty-string default (the
28206        // canonical `Option<String>` → `String` collapse footgun the
28207        // sibling M2 [`crate::LimitsSpec::is_empty`] /
28208        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
28209        // already guard on the peer M2 typed-slot surfaces), a
28210        // `Some("None")` stringified-None round-trip, a `Some` arm
28211        // whose contents were derived from a sibling slot (an
28212        // accidental fallback to `estrategia.as_str()` that read the
28213        // strategy discriminator into the hint axis), or a
28214        // `Some("default")` implicit-default that would silently biases
28215        // the routing without the author having written one. Three
28216        // placements sweep the accept-set every `validate`-passing
28217        // `:affinity None` shape lands on — one per PlacementStrategy
28218        // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
28219        // with a shard-key), since `:affinity` is orthogonal to
28220        // `:estrategia` in the typed grammar.
28221        for (estrategia, shard_key) in [
28222            (PlacementStrategy::SingleNode, None),
28223            (PlacementStrategy::Replicated, None),
28224            (PlacementStrategy::Sharded, Some("tenantId".to_string())),
28225        ] {
28226            let p = Placement {
28227                estrategia,
28228                clusters: vec!["rio".into()],
28229                affinity: None,
28230                shard_key,
28231            };
28232            assert!(
28233                p.affinity().is_none(),
28234                "Placement::affinity must return None when the typed \
28235                 slot is absent under :estrategia {estrategia:?} (got {:?})",
28236                p.affinity(),
28237            );
28238            assert_eq!(
28239                p.affinity(),
28240                p.affinity.as_deref(),
28241                "Placement::affinity must byte-equal the .affinity \
28242                 field's `.as_deref()` projection in the absent arm",
28243            );
28244        }
28245    }
28246
28247    #[test]
28248    fn placement_affinity_borrows_from_affinity_storage() {
28249        // The borrow-not-copy pin: [`Placement::affinity`] must return
28250        // an `Option<&str>` whose `Some` arm borrows from the typed
28251        // slot's own [`String`] storage — same-address invariant with
28252        // `p.affinity.as_deref().unwrap()`. Pins against a future
28253        // silent detour that allocated a fresh `String`
28254        // (`self.affinity.clone().map(...)` in the body would type-
28255        // check but silently drop the borrow, and every downstream
28256        // consumer that assumed the returned slice outlives `&self`
28257        // would break on a stale-reference use-after-free — the
28258        // [`AplicacaoSpec::validate_placement`] per-hint value-shape
28259        // gate reads the accessor's `&str` return through the
28260        // [`validate_placement_affinity`] `&str` parameter and would
28261        // silently misbehave if this accessor produced a detached
28262        // copy). Peer of the sibling per-`:placement`
28263        // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
28264        // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
28265        // extends the discipline onto the sibling per-`:placement`
28266        // M3-Adaptive-compression-hint arm.
28267        let p = Placement {
28268            estrategia: PlacementStrategy::Replicated,
28269            clusters: vec!["rio".into()],
28270            affinity: Some("data-locality".into()),
28271            shard_key: None,
28272        };
28273        let hint = p.affinity().expect("Some arm");
28274        let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
28275        assert_eq!(
28276            hint.as_ptr(),
28277            storage_slice.as_ptr(),
28278            "Placement::affinity must borrow from the .affinity \
28279             String's backing storage — a fresh allocation here means \
28280             the accessor no longer names the substrate-primitive typed \
28281             dispatch and every downstream consumer would silently \
28282             carry a detached copy",
28283        );
28284        assert_eq!(
28285            hint.len(),
28286            storage_slice.len(),
28287            "Placement::affinity and .affinity.as_deref() must byte-\
28288             equal in length as well as in address",
28289        );
28290    }
28291
28292    #[test]
28293    fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
28294        // The canonical per-`:placement` distribution-strategy-scalar
28295        // pin: [`Placement::estrategia`] must return the `:placement
28296        // :estrategia` field verbatim as a [`PlacementStrategy`],
28297        // `Copy`-projected from the typed slot's own `PlacementStrategy`
28298        // storage across every variant in the closed accept-set
28299        // (`SingleNode` — Erlang/OTP distributed-app takeover;
28300        // `Replicated` — active-active across every named cluster;
28301        // `Sharded` — Akka-style hash-keyed entity distribution). Pins
28302        // against a future silent detour that re-derived the strategy
28303        // from a peer axis (an accidental fallback to
28304        // `if shard_key.is_some() { Sharded } else { Replicated }`
28305        // collapse that read the shard-key axis into the strategy
28306        // discriminator), a variant remap the operator authors on one
28307        // consumer without the other, or a stale-derive detour that
28308        // substituted [`PlacementStrategy::default`] when the field
28309        // held any explicit variant (which would silently collapse the
28310        // distinction between "author explicitly declared `:estrategia
28311        // Replicated`" and "author omitted the slot and inherited the
28312        // default" the future per-cluster override slot depends on).
28313        // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
28314        // pin on the `Copy`-return `u16` scalar axis — same "the
28315        // substrate-primitive accessor must byte-equal the raw field
28316        // access verbatim across every author-declared value" discipline
28317        // extended onto the per-`:placement` distribution-strategy
28318        // `Copy`-composite-enum scalar axis.
28319        for estrategia in [
28320            PlacementStrategy::SingleNode,
28321            PlacementStrategy::Replicated,
28322            PlacementStrategy::Sharded,
28323        ] {
28324            // Route the paired `:shard-key` fixture-builder through the
28325            // typed cross-slot invariant predicate
28326            // [`PlacementStrategy::requires_shard_key`] rather than the
28327            // [`gen_platform::IsVariant`]-derived [`PlacementStrategy::is_sharded`]
28328            // arm-identity predicate — same discipline the sibling
28329            // `placement_strategy_variants_round_trip` fixture builder now
28330            // reads through.
28331            let shard_key = estrategia
28332                .requires_shard_key()
28333                .then(|| "tenantId".to_string());
28334            let p = Placement {
28335                estrategia,
28336                clusters: vec!["rio".into()],
28337                affinity: None,
28338                shard_key,
28339            };
28340            assert_eq!(
28341                p.estrategia(),
28342                estrategia,
28343                "Placement::estrategia must return :placement :estrategia \
28344                 verbatim (got {:?}, expected {estrategia:?})",
28345                p.estrategia(),
28346            );
28347            assert_eq!(
28348                p.estrategia(),
28349                p.estrategia,
28350                "Placement::estrategia accessor and .estrategia field \
28351                 access must byte-equal — the accessor is the substrate-\
28352                 primitive typed dispatch every downstream distribution-\
28353                 strategy consumer must route through",
28354            );
28355        }
28356    }
28357
28358    #[test]
28359    fn validate_placement_reads_through_lifted_estrategia_accessor() {
28360        // Three-consumer coherence pin: the
28361        // [`AplicacaoSpec::validate_placement`]
28362        // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
28363        // `estrategia:` field (which reads through
28364        // [`Placement::estrategia`] to name the strategy the empty
28365        // `:clusters` list was declared against), the same method's
28366        // `Sharded ↔ non-Sharded` `match` partition dispatch (which
28367        // reads through [`Placement::estrategia`] to fan across the
28368        // shape-gate cascades), and the non-`Sharded`-arm
28369        // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
28370        // `estrategia:` field (which reads through
28371        // [`Placement::estrategia`] to name the strategy the declared-
28372        // but-inert `:shard-key` was authored under) must all key off
28373        // the lifted accessor, so any future rebrand on the typed
28374        // slot's reader shape lands at exactly one place. Pins the
28375        // three-site coherence by exercising each error surface end-
28376        // to-end and asserting the surfaced `estrategia:` field byte-
28377        // equals the accessor's return. Peer of the sibling per-
28378        // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
28379        // pin on the M3 mesh-slot `Copy`-return scalar axis.
28380
28381        // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
28382        // whose `estrategia:` field must byte-equal the accessor's return
28383        // for every variant in the closed accept-set.
28384        for estrategia in [
28385            PlacementStrategy::SingleNode,
28386            PlacementStrategy::Replicated,
28387            PlacementStrategy::Sharded,
28388        ] {
28389            let mut spec = three_member_spec();
28390            spec.placement.estrategia = estrategia;
28391            spec.placement.clusters = Vec::new();
28392            // Route the paired `:shard-key` spec-mutator through the typed
28393            // cross-slot invariant predicate
28394            // [`PlacementStrategy::requires_shard_key`] rather than the
28395            // [`gen_platform::IsVariant`]-derived
28396            // [`PlacementStrategy::is_sharded`] arm-identity predicate —
28397            // same discipline the sibling
28398            // `placement_strategy_variants_round_trip` and
28399            // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
28400            // fixture builders now read through.
28401            spec.placement.shard_key = estrategia
28402                .requires_shard_key()
28403                .then(|| "tenantId".to_string());
28404            let err = spec.validate().unwrap_err();
28405            match err {
28406                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
28407                    assert_eq!(
28408                        e,
28409                        spec.placement.estrategia(),
28410                        "PlacementWithoutClusters.estrategia must byte-equal \
28411                         Placement::estrategia() — the error carrier reads \
28412                         through the lifted accessor",
28413                    );
28414                }
28415                other => panic!(
28416                    "expected PlacementWithoutClusters, got {other:?} for \
28417                     estrategia={estrategia:?}"
28418                ),
28419            }
28420        }
28421
28422        // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
28423        // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
28424        // must byte-equal the accessor's return for both non-`Sharded`
28425        // strategies.
28426        for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
28427            let mut spec = three_member_spec();
28428            spec.placement.estrategia = estrategia;
28429            spec.placement.shard_key = Some("tenantId".into());
28430            let err = spec.validate().unwrap_err();
28431            match err {
28432                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
28433                    assert_eq!(
28434                        e,
28435                        spec.placement.estrategia(),
28436                        "ShardKeyOnNonSharded.estrategia must byte-equal \
28437                         Placement::estrategia() — the non-Sharded-arm \
28438                         refusal reads through the lifted accessor",
28439                    );
28440                }
28441                other => panic!(
28442                    "expected ShardKeyOnNonSharded, got {other:?} for \
28443                     estrategia={estrategia:?}"
28444                ),
28445            }
28446        }
28447    }
28448
28449    // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
28450    //
28451    // The [`Placement::clusters`] accessor lift is the second slice-return
28452    // (`&[T]`) accessor on any typed slot — sibling to the seed M2
28453    // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
28454    // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
28455    // below cover (1) the accessor's byte-equal projection against the raw
28456    // field access across the empty / singleton / cohort fixtures the
28457    // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
28458    // and the per-cluster validate loop fan between, and (2) the two-
28459    // consumer coherence of the paired pre-flight refusal probe and the
28460    // per-cluster validate loop routing through the accessor on both arms.
28461
28462    #[test]
28463    fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
28464        // The canonical per-`:placement` cluster-pool-scalar-shape pin:
28465        // [`Placement::clusters`] must return the `:placement :clusters`
28466        // typed `Vec<String>` verbatim as a `&[String]` slice-view over
28467        // the same backing buffer the raw `self.clusters.as_slice()`
28468        // field access borrows from, byte-equal across every
28469        // representative fixture in the accept-set — the empty slice
28470        // (the pre-validation sentinel every
28471        // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
28472        // the singleton slice (the minimal `SingleNode`-shape cohort),
28473        // and multi-entry cohorts (the peer `Replicated` / `Sharded`
28474        // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
28475        //
28476        // Pins against a future silent detour that returned
28477        // `&Vec<String>` (which would type-check but leak the storage-
28478        // side `Vec`'s grow/push/reserve surface no consumer of the
28479        // typed view reaches for), a fresh-allocated `Vec<String>` copy
28480        // (which would type-check via a coercion but silently break
28481        // every downstream caller that relied on the slice sharing the
28482        // backing buffer's identity), or an out-of-order or length-
28483        // drifted projection (which would silently split the paired
28484        // pre-flight `.is_empty()` refusal probe's input from the per-
28485        // cluster validate loop's traversal input).
28486        //
28487        // Peer of the sibling M2
28488        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
28489        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
28490        // `:supervisor` static-child-list axis, extended onto the M3
28491        // per-`:placement` distribution-target-list `Vec`-carry axis.
28492        let fixtures: Vec<Vec<String>> = vec![
28493            Vec::new(),
28494            vec!["rio".into()],
28495            vec!["rio".into(), "mar".into()],
28496            vec!["rio".into(), "mar".into(), "plo".into()],
28497        ];
28498        for clusters in fixtures {
28499            let p = Placement {
28500                clusters: clusters.clone(),
28501                ..Placement::default()
28502            };
28503            assert_eq!(
28504                p.clusters(),
28505                clusters.as_slice(),
28506                "Placement::clusters must return :placement :clusters \
28507                 verbatim (got {:?}, expected {:?})",
28508                p.clusters(),
28509                clusters.as_slice(),
28510            );
28511            assert_eq!(
28512                p.clusters(),
28513                p.clusters.as_slice(),
28514                "Placement::clusters accessor and .clusters.as_slice() \
28515                 field access must byte-equal — the accessor is the \
28516                 substrate-primitive typed dispatch every downstream \
28517                 cluster-pool consumer must route through",
28518            );
28519            assert_eq!(
28520                p.clusters().len(),
28521                p.clusters.len(),
28522                "Placement::clusters().len() must byte-equal \
28523                 self.clusters.len() — a length-drift would silently \
28524                 split the paired pre-flight `.is_empty()` refusal \
28525                 probe input from the per-cluster validate loop's \
28526                 traversal input",
28527            );
28528        }
28529    }
28530
28531    #[test]
28532    fn validate_placement_reads_through_lifted_clusters_accessor() {
28533        // Two-consumer coherence pin: the
28534        // [`AplicacaoSpec::validate_placement`] pre-flight
28535        // `self.placement.clusters().is_empty()` refusal probe (which
28536        // must trip [`AplicacaoError::PlacementWithoutClusters`] when
28537        // the accessor projects the empty slice) and the per-cluster
28538        // validate loop's `for c in self.placement.clusters()`
28539        // traversal (which must reach every entry in the same order
28540        // the accessor projects, so both the per-entry value-shape
28541        // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
28542        // and the duplicate-detection HashSet insert that trips
28543        // [`AplicacaoError::PlacementClusterDuplicate`] key off the
28544        // accessor's projection) must both key off the lifted
28545        // accessor, so any future rebrand on the typed slot's reader
28546        // shape lands at exactly one place. Pins the two-site
28547        // coherence by exercising each production consumer end-to-end:
28548        // (1) the `PlacementWithoutClusters` refusal under the empty
28549        // slice, (2) the `PlacementClusterInvalid` refusal fires on
28550        // the second entry of a two-cluster cohort whose head is
28551        // valid but tail is not (which requires the loop to reach the
28552        // second entry through the accessor), and (3) the
28553        // `PlacementClusterDuplicate` refusal fires on the second
28554        // entry of a two-cluster cohort that shares a name (which
28555        // requires the loop to reach both entries — a first-entry-only
28556        // projection would silently pass since the dedup HashSet has
28557        // room for the first insert).
28558        //
28559        // Peer of the sibling M2
28560        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
28561        // (bc92bce) coherence pin on the per-`:supervisor` static-
28562        // child-list axis, extended onto the M3 per-`:placement`
28563        // distribution-target-list `Vec`-carry axis.
28564
28565        // (1) Pre-flight `.is_empty()` probe: the empty slice must
28566        // trip `PlacementWithoutClusters`.
28567        let mut spec = three_member_spec();
28568        spec.placement.clusters = Vec::new();
28569        match spec.validate().unwrap_err() {
28570            AplicacaoError::PlacementWithoutClusters { .. } => {}
28571            other => panic!("expected PlacementWithoutClusters, got {other:?}"),
28572        }
28573        assert!(
28574            spec.placement.clusters().is_empty(),
28575            "the pre-flight refusal input must be the empty slice per \
28576             the accessor's projection",
28577        );
28578
28579        // (2) Per-cluster validate loop: a two-cluster cohort with an
28580        // invalid tail entry must trip `PlacementClusterInvalid` on
28581        // the tail — the loop must reach the second entry through
28582        // the accessor.
28583        let mut spec = three_member_spec();
28584        spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
28585        match spec.validate().unwrap_err() {
28586            AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
28587                assert_eq!(
28588                    cluster, "BAD_CLUSTER",
28589                    "PlacementClusterInvalid.cluster must carry the \
28590                     tail entry the loop reached through the accessor",
28591                );
28592            }
28593            other => panic!("expected PlacementClusterInvalid, got {other:?}"),
28594        }
28595        assert_eq!(
28596            spec.placement.clusters().len(),
28597            2,
28598            "the per-cluster validate loop's traversal input must be \
28599             a two-element slice per the accessor's projection",
28600        );
28601
28602        // (3) Per-cluster validate loop: a two-cluster cohort that
28603        // shares a name must trip `PlacementClusterDuplicate` on the
28604        // second entry — the loop must reach both entries through the
28605        // accessor for the dedup HashSet's second insert to collide.
28606        let mut spec = three_member_spec();
28607        spec.placement.clusters = vec!["rio".into(), "rio".into()];
28608        match spec.validate().unwrap_err() {
28609            AplicacaoError::PlacementClusterDuplicate { cluster } => {
28610                assert_eq!(
28611                    cluster, "rio",
28612                    "PlacementClusterDuplicate.cluster must carry the \
28613                     shared cluster name verbatim",
28614                );
28615            }
28616            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
28617        }
28618        assert_eq!(
28619            spec.placement.clusters().len(),
28620            2,
28621            "the per-cluster validate loop's traversal input must be \
28622             a two-element slice per the accessor's projection",
28623        );
28624    }
28625
28626    #[test]
28627    fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
28628        // The canonical per-`:membros` member-list-slice-shape pin:
28629        // [`AplicacaoSpec::membros`] must return the `:membros` typed
28630        // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
28631        // same backing buffer the raw `self.membros.as_slice()` field
28632        // access borrows from, byte-equal across every representative
28633        // fixture in the accept-set — the empty slice (the pre-
28634        // validation sentinel every [`AplicacaoError::NoMembros`]
28635        // refusal keys off), the singleton slice (the minimal one-
28636        // Servico Aplicacao shape), and multi-entry cohorts (the peer
28637        // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
28638        // load-bearing identity of the application graph).
28639        //
28640        // Pins against a future silent detour that returned
28641        // `&Vec<Membro>` (which would type-check but leak the storage-
28642        // side `Vec`'s grow/push/reserve surface no consumer of the
28643        // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
28644        // (which would type-check via a coercion but silently break
28645        // every downstream caller that relied on the slice sharing the
28646        // backing buffer's identity), or an out-of-order or length-
28647        // drifted projection (which would silently split the paired
28648        // `HashSet<&str>` name-set seed's collect input from the
28649        // pre-flight `.is_empty()` refusal probe's input from the per-
28650        // member validate loop's traversal input from the
28651        // programs.yaml emitter's per-entry fan-out loop's input from
28652        // the `feira app graph` per-member print traversal's input).
28653        //
28654        // Peer of the sibling M2
28655        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
28656        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
28657        // `:supervisor` static-child-list axis and the sibling M3
28658        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
28659        // (a6e18d7) `&[String]` byte-equal pin on the per-
28660        // `:placement` distribution-target-list axis — extends the
28661        // slice-return-accessor byte-equal-projection discipline onto
28662        // the outermost M3 mesh-slot type's per-Aplicacao member-list
28663        // `Vec`-carry axis.
28664        let fixtures: Vec<Vec<Membro>> = vec![
28665            Vec::new(),
28666            vec![membro("catalog", "^0.1")],
28667            vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
28668            vec![
28669                membro("catalog", "^0.1"),
28670                membro("cart", "^0.1"),
28671                membro("payment", "^0.2"),
28672            ],
28673        ];
28674        for membros in fixtures {
28675            let s = AplicacaoSpec {
28676                membros: membros.clone(),
28677                contratos: Vec::new(),
28678                politicas: MeshPolicy::default(),
28679                placement: Placement::default(),
28680                entrada: None,
28681            };
28682            assert_eq!(
28683                s.membros(),
28684                membros.as_slice(),
28685                "AplicacaoSpec::membros must return :membros verbatim \
28686                 (got {:?}, expected {:?})",
28687                s.membros(),
28688                membros.as_slice(),
28689            );
28690            assert_eq!(
28691                s.membros(),
28692                s.membros.as_slice(),
28693                "AplicacaoSpec::membros accessor and .membros.as_slice() \
28694                 field access must byte-equal — the accessor is the \
28695                 substrate-primitive typed dispatch every downstream \
28696                 member-list consumer must route through",
28697            );
28698            assert_eq!(
28699                s.membros().len(),
28700                s.membros.len(),
28701                "AplicacaoSpec::membros().len() must byte-equal \
28702                 self.membros.len() — a length-drift would silently \
28703                 split the paired `HashSet<&str>` name-set seed's \
28704                 collect input from the pre-flight `.is_empty()` \
28705                 refusal probe input from the per-member validate \
28706                 loop's traversal input",
28707            );
28708        }
28709    }
28710
28711    #[test]
28712    fn validate_reads_through_lifted_membros_accessor() {
28713        // Three-consumer coherence pin: the
28714        // [`AplicacaoSpec::validate_membros`] pre-flight
28715        // `self.membros().is_empty()` refusal probe (which must trip
28716        // [`AplicacaoError::NoMembros`] when the accessor projects the
28717        // empty slice), the same method's per-member validate loop's
28718        // `for m in self.membros()` traversal (which must reach every
28719        // entry in the same order the accessor projects, so both the
28720        // per-entry empty-`:caixa` gate that trips
28721        // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
28722        // detection `insert_first_seen` that trips
28723        // [`AplicacaoError::MembroDuplicate`] key off the accessor's
28724        // projection), and the peer [`AplicacaoSpec::validate`]'s
28725        // `HashSet<&str>` name-set seed's
28726        // `self.membros().iter().map(Membro::nome).collect()` collect
28727        // input (which every `:contratos` `:de` / `:para` membership
28728        // lookup rejects an unknown name against) must all three key
28729        // off the lifted accessor, so any future rebrand on the typed
28730        // slot's reader shape lands at exactly one place. Pins the
28731        // three-site coherence by exercising each production consumer
28732        // end-to-end: (1) the `NoMembros` refusal under the empty
28733        // slice, (2) the `MembroCaixaEmpty` refusal fires on the
28734        // second entry of a two-member cohort whose head is valid but
28735        // tail has an empty `:caixa` (which requires the loop to
28736        // reach the second entry through the accessor), and (3) the
28737        // `MembroDuplicate` refusal fires on the second entry of a
28738        // two-member cohort that shares a `:caixa` name (which
28739        // requires the loop to reach both entries through the
28740        // accessor for the dedup HashSet's second insert to collide).
28741        //
28742        // Peer of the sibling M2
28743        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
28744        // (bc92bce) coherence pin on the per-`:supervisor` static-
28745        // child-list axis and the sibling M3
28746        // `validate_placement_reads_through_lifted_clusters_accessor`
28747        // (a6e18d7) coherence pin on the per-`:placement` distribution-
28748        // target-list axis — extends the slice-return-accessor
28749        // multi-consumer coherence discipline onto the outermost M3
28750        // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
28751
28752        // (1) Pre-flight `.is_empty()` probe: the empty slice must
28753        // trip `NoMembros`.
28754        let mut spec = three_member_spec();
28755        spec.membros = Vec::new();
28756        assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
28757        assert!(
28758            spec.membros().is_empty(),
28759            "the pre-flight refusal input must be the empty slice per \
28760             the accessor's projection",
28761        );
28762
28763        // (2) Per-member validate loop: a two-member cohort with an
28764        // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
28765        // the tail — the loop must reach the second entry through
28766        // the accessor.
28767        let mut spec = three_member_spec();
28768        spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
28769        assert_eq!(
28770            spec.validate().unwrap_err(),
28771            AplicacaoError::MembroCaixaEmpty,
28772        );
28773        assert_eq!(
28774            spec.membros().len(),
28775            2,
28776            "the per-member validate loop's traversal input must be \
28777             a two-element slice per the accessor's projection",
28778        );
28779
28780        // (3) Per-member validate loop: a two-member cohort that
28781        // shares a `:caixa` name must trip `MembroDuplicate` on the
28782        // second entry — the loop must reach both entries through the
28783        // accessor for the dedup HashSet's second insert to collide.
28784        let mut spec = three_member_spec();
28785        spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
28786        match spec.validate().unwrap_err() {
28787            AplicacaoError::MembroDuplicate { caixa } => {
28788                assert_eq!(
28789                    caixa, "catalog",
28790                    "MembroDuplicate.caixa must carry the shared \
28791                     member name verbatim",
28792                );
28793            }
28794            other => panic!("expected MembroDuplicate, got {other:?}"),
28795        }
28796        assert_eq!(
28797            spec.membros().len(),
28798            2,
28799            "the per-member validate loop's traversal input must be \
28800             a two-element slice per the accessor's projection",
28801        );
28802    }
28803
28804    #[test]
28805    fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
28806        // The canonical per-`:contratos` contract-list-slice-shape pin:
28807        // [`AplicacaoSpec::contratos`] must return the `:contratos`
28808        // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
28809        // slice-view over the same backing buffer the raw
28810        // `self.contratos.as_slice()` field access borrows from, byte-
28811        // equal across every representative fixture in the accept-set —
28812        // the empty slice (the pre-validation "internal-only mesh" shape
28813        // an Aplicacao whose members exchange no typed edges renders
28814        // through), the singleton slice (the minimal one-edge Aplicacao
28815        // shape), and multi-entry cohorts (the peer multi-edge shapes
28816        // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
28817        // of the application graph).
28818        //
28819        // Pins against a future silent detour that returned
28820        // `&Vec<WitContract>` (which would type-check but leak the
28821        // storage-side `Vec`'s grow/push/reserve surface no consumer of
28822        // the typed view reaches for), a fresh-allocated
28823        // `Vec<WitContract>` copy (which would type-check via a coercion
28824        // but silently break every downstream caller that relied on the
28825        // slice sharing the backing buffer's identity), or an out-of-
28826        // order or length-drifted projection (which would silently split
28827        // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
28828        // seed's traversal input from the `detect_sync_cycles` per-edge
28829        // adjacency-list seed's traversal input from the
28830        // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
28831        // BTreeMap grouping loop's traversal input from the
28832        // `feira app graph` per-contract print traversal's input).
28833        //
28834        // Peer of the immediately-adjacent sibling M3
28835        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
28836        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
28837        // node-list axis, the sibling M3
28838        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
28839        // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
28840        // distribution-target-list axis, and the sibling M2
28841        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
28842        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
28843        // `:supervisor` static-child-list axis — extends the slice-
28844        // return-accessor byte-equal-projection discipline onto the
28845        // outermost M3 mesh-slot type's per-Aplicacao contract-list
28846        // `Vec`-carry axis, closing the last unlifted per-
28847        // `AplicacaoSpec` `Vec`-carry axis.
28848        let fixtures: Vec<Vec<WitContract>> = vec![
28849            Vec::new(),
28850            vec![contract_http("cart", "catalog", "/products/:id")],
28851            vec![
28852                contract_http("cart", "catalog", "/products/:id"),
28853                contract_http("cart", "payment", "/charge"),
28854            ],
28855            vec![
28856                contract_http("cart", "catalog", "/products/:id"),
28857                contract_http("cart", "payment", "/charge"),
28858                contract_http("payment", "catalog", "/audit"),
28859            ],
28860        ];
28861        for contratos in fixtures {
28862            let s = AplicacaoSpec {
28863                membros: vec![
28864                    membro("catalog", "^0.1"),
28865                    membro("cart", "^0.1"),
28866                    membro("payment", "^0.2"),
28867                ],
28868                contratos: contratos.clone(),
28869                politicas: MeshPolicy::default(),
28870                placement: Placement::default(),
28871                entrada: None,
28872            };
28873            assert_eq!(
28874                s.contratos(),
28875                contratos.as_slice(),
28876                "AplicacaoSpec::contratos must return :contratos verbatim \
28877                 (got {:?}, expected {:?})",
28878                s.contratos(),
28879                contratos.as_slice(),
28880            );
28881            assert_eq!(
28882                s.contratos(),
28883                s.contratos.as_slice(),
28884                "AplicacaoSpec::contratos accessor and \
28885                 .contratos.as_slice() field access must byte-equal — \
28886                 the accessor is the substrate-primitive typed dispatch \
28887                 every downstream contract-list consumer must route \
28888                 through",
28889            );
28890            assert_eq!(
28891                s.contratos().len(),
28892                s.contratos.len(),
28893                "AplicacaoSpec::contratos().len() must byte-equal \
28894                 self.contratos.len() — a length-drift would silently \
28895                 split the paired per-edge validate-loop's traversal \
28896                 input from the sync-cycle adjacency-list seed's \
28897                 traversal input from the cilium_network_policies \
28898                 per-`(:de, :para)` BTreeMap grouping loop's traversal \
28899                 input from the `feira app graph` per-contract print \
28900                 traversal's input",
28901            );
28902        }
28903    }
28904
28905    #[test]
28906    fn validate_reads_through_lifted_contratos_accessor() {
28907        // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
28908        // per-`:contratos` validate-loop's `for c in self.contratos()`
28909        // traversal (which must reach every entry in the same order the
28910        // accessor projects, so both the per-entry
28911        // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
28912        // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
28913        // dedup `HashSet` insert key off the accessor's projection),
28914        // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
28915        // `for c in self.contratos()` adjacency-list seed (which drives
28916        // the sync-subgraph deadlock-detection gate via
28917        // [`AplicacaoError::SyncCycle`]), and the peer
28918        // [`caixa_mesh::cilium_network_policies`]'s
28919        // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
28920        // grouping loop (which drives the per-CNP fan-out) must all
28921        // three key off the lifted accessor, so any future rebrand on
28922        // the typed slot's reader shape lands at exactly one place. Pins
28923        // the three-site coherence by exercising the two caixa-core
28924        // production consumers end-to-end: (1) the empty-`:contratos`
28925        // slice must validate without a per-edge diagnostic (the
28926        // per-edge loop is a no-op under the empty projection), (2) the
28927        // `ContratoMemberMissing` refusal fires on the second entry of a
28928        // two-edge cohort whose head references a valid member but tail
28929        // references a phantom name (which requires the loop to reach
28930        // the second entry through the accessor), and (3) the
28931        // `SyncCycle` refusal fires on a self-referential two-edge
28932        // cohort through the sync-cycle detector's peer projection
28933        // (which requires the detector to iterate the accessor's
28934        // projection to add the back-edge to its adjacency list).
28935        //
28936        // Peer of the sibling M3
28937        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
28938        // three-consumer coherence pin on the per-`:membros` node-list
28939        // axis and the sibling M3
28940        // `validate_placement_reads_through_lifted_clusters_accessor`
28941        // (a6e18d7) coherence pin on the per-`:placement` distribution-
28942        // target-list axis — extends the slice-return-accessor multi-
28943        // consumer coherence discipline onto the outermost M3 mesh-slot
28944        // type's per-Aplicacao contract-list `Vec`-carry axis.
28945
28946        // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
28947        // and no per-edge diagnostic surfaces. Validate succeeds on
28948        // the well-formed `:membros` head.
28949        let mut spec = three_member_spec();
28950        spec.contratos = Vec::new();
28951        assert!(
28952            spec.validate().is_ok(),
28953            "empty :contratos must validate — the per-edge loop is a \
28954             no-op under the accessor's empty projection",
28955        );
28956        assert!(
28957            spec.contratos().is_empty(),
28958            "the per-edge validate loop's traversal input must be the \
28959             empty slice per the accessor's projection",
28960        );
28961
28962        // (2) Per-edge validate loop: a two-edge cohort whose tail
28963        // references a phantom `:para` member must trip
28964        // `ContratoMemberMissing` on the tail — the loop must reach
28965        // the second entry through the accessor for the membership
28966        // lookup to fail on the phantom name.
28967        let mut spec = three_member_spec();
28968        spec.contratos = vec![
28969            contract_http("cart", "catalog", "/products/:id"),
28970            contract_http("cart", "phantom", "/x"),
28971        ];
28972        let err = spec.validate().unwrap_err();
28973        assert!(
28974            matches!(
28975                err,
28976                AplicacaoError::ContratoMemberMissing { ref caixa }
28977                    if caixa == "phantom"
28978            ),
28979            "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
28980        );
28981        assert_eq!(
28982            spec.contratos().len(),
28983            2,
28984            "the per-edge validate loop's traversal input must be \
28985             a two-element slice per the accessor's projection",
28986        );
28987
28988        // (3) Sync-cycle detector: a two-edge synchronous cohort
28989        // whose second edge closes the sync-subgraph back onto the
28990        // first must trip [`AplicacaoError::ContratoCycle`] — the
28991        // detector must iterate the accessor's projection to add
28992        // both edges to its adjacency list, so a length-drift on
28993        // the accessor's projection would silently disagree with
28994        // the sync-cycle detector on which edge closes the loop.
28995        // Peer projection to the `validate` per-edge loop above:
28996        // the sync-cycle detector routes through the same lifted
28997        // accessor, so a rebrand of the reader shape lands at one
28998        // place. Uses a two-edge cohort (cart → catalog → cart)
28999        // because the per-edge `ContratoSelfLoop` gate fires before
29000        // the sync-cycle detector on a single self-referential edge
29001        // (`cart → cart`) — the cycle-detector's input must be a
29002        // multi-edge cohort for its per-edge traversal input to be
29003        // observably wider than the per-edge validate loop's input.
29004        let mut spec = three_member_spec();
29005        spec.contratos = vec![
29006            contract_http("cart", "catalog", "/products/:id"),
29007            contract_http("catalog", "cart", "/callback"),
29008        ];
29009        let err = spec.validate().unwrap_err();
29010        assert!(
29011            matches!(err, AplicacaoError::ContratoCycle { .. }),
29012            "expected ContratoCycle from the sync-cycle detector on a \
29013             two-edge back-edge cohort, got {err:?}",
29014        );
29015        assert_eq!(
29016            spec.contratos().len(),
29017            2,
29018            "the sync-cycle detector's traversal input must be a \
29019             two-element slice per the accessor's projection",
29020        );
29021    }
29022
29023    #[test]
29024    fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
29025        // The canonical per-`:politicas` outer-composite-reference-shape
29026        // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
29027        // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
29028        // the same backing storage the raw `&self.politicas` field
29029        // access borrows from, byte-equal across every representative
29030        // fixture in the accept-set — the default `MeshPolicy` (the
29031        // author-empty "no policy on any axis" shape whose
29032        // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
29033        // shapes carrying one axis at a time
29034        // (`{mtls_required, timeout, retries, circuit_breaker,
29035        // rate_limit}` — the minimal five-axis fan-out over the
29036        // per-axis lifted accessor family every downstream mesh-artifact
29037        // emitter dispatches on), and the multi-axis composite (the
29038        // canonical `three_member_spec` fixture's `{timeout, retries,
29039        // mtls_required}` triple — the load-bearing shape every
29040        // Aplicacao-scoped fixture in this suite constructs).
29041        //
29042        // Pins against a future silent detour that returned a fresh-
29043        // cloned `MeshPolicy` copy (which would type-check via a `Clone`
29044        // impl but silently break every downstream caller that relied
29045        // on the reference sharing the composite's backing identity), a
29046        // reference to an operator-resolved overlay (the future
29047        // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
29048        // acknowledges — its resolution must land at exactly this
29049        // accessor body, not silently divert the raw slot away from a
29050        // second consumer), or an axis-shuffled projection (a future
29051        // detour that swapped `timeout` and `retries` through the
29052        // accessor would silently split the paired `validate_politicas`
29053        // per-axis bracket-dispatch's traversal input from the peer
29054        // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
29055        // emitter's fan-out input from the peer
29056        // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
29057        // overlay emitter's fan-out input).
29058        //
29059        // Peer of the sibling M3
29060        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
29061        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
29062        // node-list `Vec`-carry axis and the sibling M3
29063        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
29064        // (0dcc926) `&[WitContract]` byte-equal pin on the per-
29065        // `:contratos` edge-list `Vec`-carry axis — extends the outer-
29066        // accessor byte-equal-projection discipline onto the outermost
29067        // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
29068        // reference axis, the first `&Composite`-return accessor on the
29069        // outer [`AplicacaoSpec`] type.
29070        let fixtures: Vec<MeshPolicy> = vec![
29071            MeshPolicy::default(),
29072            MeshPolicy {
29073                mtls_required: Some(true),
29074                ..MeshPolicy::default()
29075            },
29076            MeshPolicy {
29077                mtls_required: Some(false),
29078                ..MeshPolicy::default()
29079            },
29080            MeshPolicy {
29081                timeout: Some(Duration::from_secs(30)),
29082                ..MeshPolicy::default()
29083            },
29084            MeshPolicy {
29085                retries: Some(3),
29086                ..MeshPolicy::default()
29087            },
29088            MeshPolicy {
29089                circuit_breaker: Some(CircuitBreaker {
29090                    max_failures: 5,
29091                    window: Duration::from_secs(30),
29092                }),
29093                ..MeshPolicy::default()
29094            },
29095            MeshPolicy {
29096                rate_limit: Some(RateLimit {
29097                    rate: 100,
29098                    window: Duration::from_secs(1),
29099                }),
29100                ..MeshPolicy::default()
29101            },
29102            MeshPolicy {
29103                timeout: Some(Duration::from_secs(30)),
29104                retries: Some(3),
29105                mtls_required: Some(true),
29106                ..MeshPolicy::default()
29107            },
29108        ];
29109        for politicas in fixtures {
29110            let s = AplicacaoSpec {
29111                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
29112                contratos: Vec::new(),
29113                politicas: politicas.clone(),
29114                placement: Placement::default(),
29115                entrada: None,
29116            };
29117            assert_eq!(
29118                *s.politicas(),
29119                politicas,
29120                "AplicacaoSpec::politicas must return :politicas verbatim \
29121                 (got {:?}, expected {:?})",
29122                s.politicas(),
29123                politicas,
29124            );
29125            assert!(
29126                std::ptr::eq(s.politicas(), &s.politicas),
29127                "AplicacaoSpec::politicas accessor and &self.politicas \
29128                 field access must borrow the same backing storage — \
29129                 the accessor is the substrate-primitive typed dispatch \
29130                 every downstream mesh-policy composite consumer must \
29131                 route through, and a reference-identity split would \
29132                 silently break every consumer that relied on the \
29133                 borrow sharing the composite's storage",
29134            );
29135            assert_eq!(
29136                s.politicas().is_empty(),
29137                s.politicas.is_empty(),
29138                "AplicacaoSpec::politicas().is_empty() must byte-equal \
29139                 self.politicas.is_empty() — an emptiness-drift would \
29140                 silently split the paired `validate_politicas` \
29141                 per-axis bracket-dispatch's seed from the peer \
29142                 caixa-mesh CNP mTLS-overlay emitter's key from the \
29143                 peer caixa-mesh HTTPRoute timeout+retry overlay \
29144                 emitter's key",
29145            );
29146        }
29147    }
29148
29149    #[test]
29150    fn validate_politicas_reads_through_lifted_politicas_accessor() {
29151        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
29152        // per-axis bracket-dispatch seed (`let p = self.politicas();`,
29153        // followed by the per-axis fan-out `p.timeout()` /
29154        // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
29155        // the lifted axis-level accessor family) must key off the
29156        // lifted outer accessor, so any future rebrand on the typed
29157        // slot's outer-composite reader shape lands at exactly one
29158        // place. Pins the multi-axis coherence by exercising each
29159        // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
29160        // a `Some(Duration::ZERO)` timeout under the outer accessor's
29161        // reference projection, (2) `PolicyRetriesZero` fires on a
29162        // `Some(0)` retries under the same projection, and (3) an
29163        // empty [`MeshPolicy::default`] passes `validate_politicas` —
29164        // the outer accessor's reference-projection reaches every
29165        // per-axis branch without silently short-circuiting any.
29166        //
29167        // Peer of the sibling M3
29168        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
29169        // three-consumer coherence pin on the per-`:membros` node-list
29170        // axis and the sibling M3
29171        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
29172        // three-consumer coherence pin on the per-`:contratos`
29173        // edge-list axis — extends the multi-consumer coherence
29174        // discipline onto the outermost M3 mesh-slot type's per-
29175        // Aplicacao mesh-policy composite-reference axis, the first
29176        // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
29177        // type.
29178
29179        // (1) `PolicyTimeoutZero` refusal under the outer accessor's
29180        // reference projection: a `Some(Duration::ZERO)` timeout must
29181        // trip the zero-floor gate. The bracket-dispatch's first arm
29182        // reads `p.timeout()` on the reference returned by the outer
29183        // accessor.
29184        let mut spec = three_member_spec();
29185        spec.politicas.timeout = Some(Duration::ZERO);
29186        spec.politicas.retries = None;
29187        spec.politicas.circuit_breaker = None;
29188        spec.politicas.rate_limit = None;
29189        assert_eq!(
29190            spec.validate().unwrap_err(),
29191            AplicacaoError::PolicyTimeoutZero,
29192        );
29193        assert!(
29194            std::ptr::eq(spec.politicas(), &spec.politicas),
29195            "the `validate_politicas` per-axis bracket-dispatch's \
29196             traversal input must be the same backing composite the \
29197             accessor's reference projection borrows from",
29198        );
29199
29200        // (2) `PolicyRetriesZero` refusal under the outer accessor's
29201        // reference projection: a `Some(0)` retries must trip the
29202        // zero-floor gate. The bracket-dispatch's second arm reads
29203        // `p.retries()` on the reference returned by the outer accessor.
29204        let mut spec = three_member_spec();
29205        spec.politicas.timeout = None;
29206        spec.politicas.retries = Some(0);
29207        spec.politicas.circuit_breaker = None;
29208        spec.politicas.rate_limit = None;
29209        assert_eq!(
29210            spec.validate().unwrap_err(),
29211            AplicacaoError::PolicyRetriesZero,
29212        );
29213
29214        // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
29215        // — every per-axis arm short-circuits on `None`, so the outer
29216        // accessor's reference projection reaches the fall-through
29217        // `Ok(())` without any per-axis refusal firing.
29218        let mut spec = three_member_spec();
29219        spec.politicas = MeshPolicy::default();
29220        assert!(
29221            spec.validate().is_ok(),
29222            "an empty `MeshPolicy` must pass `validate_politicas` — \
29223             every per-axis arm short-circuits on `None` under the \
29224             outer accessor's reference projection",
29225        );
29226        assert!(
29227            spec.politicas().is_empty(),
29228            "the outer accessor's reference projection must be the \
29229             empty composite per the `MeshPolicy::default()` fixture",
29230        );
29231    }
29232
29233    #[test]
29234    #[allow(clippy::too_many_lines)]
29235    fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
29236        // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
29237        // per-axis bracket-dispatch's `:timeout` and `:retries` arms
29238        // must both key off the lifted axis-level accessors
29239        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
29240        // the peer `:circuit-breaker` / `:rate-limit` arms already
29241        // routing through [`MeshPolicy::circuit_breaker`] /
29242        // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
29243        // per axis on the substrate primitive" shape at the fan-out
29244        // (four axes, four accessors, no raw-field-access site
29245        // anywhere on the bracket-dispatch). Pins the per-axis
29246        // coherence at the accept-set boundaries the bracket carves:
29247        //   1. accessor byte-equal to raw field on every representative
29248        //      accept-set value (`None`, sub-cap, at-cap, past-cap
29249        //      sentinel) — a future accessor drift that no longer
29250        //      shipped the raw slot verbatim would surface here,
29251        //   2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
29252        //      routed through the accessor's projection, proving the
29253        //      first arm reads through the accessor rather than a
29254        //      silent-detour peer-axis field access,
29255        //   3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
29256        //      through the accessor's projection, proving the second
29257        //      arm reads through the accessor,
29258        //   4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
29259        //      passes validate under the accessor projection (paired
29260        //      with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
29261        //      sibling axis), pinning the upper-boundary accept-arm
29262        //      also routes through the accessor.
29263        //
29264        // Peer of the sibling M3
29265        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
29266        // outer-composite-reference coherence pin (which asserts the
29267        // `let p = self.politicas()` seed); extends the discipline onto
29268        // the per-axis fan-out layer that consumes the seed's
29269        // reference. Same shape as
29270        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
29271        // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
29272        // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
29273        // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
29274
29275        // (1) Accessor byte-equal to raw field on the `:timeout` axis
29276        // across the accept-set boundaries the bracket dispatch's
29277        // three-arm gate carves out
29278        // ([`crate::render::require_positive_canonical_bounded_duration`]
29279        // — zero-floor + canonical-form + upper-cap).
29280        for timeout in [
29281            None,
29282            Some(Duration::ZERO),
29283            Some(Duration::from_millis(1)),
29284            Some(POLICY_TIMEOUT_MAX),
29285        ] {
29286            let p = MeshPolicy {
29287                timeout,
29288                ..MeshPolicy::default()
29289            };
29290            assert_eq!(
29291                p.timeout(),
29292                p.timeout,
29293                "MeshPolicy::timeout accessor must byte-equal the raw \
29294                 .timeout field across every accept-set boundary the \
29295                 validate_politicas :timeout arm carves out — a drift \
29296                 here would silently split the validate bracket's arm \
29297                 from the peer caixa-mesh HTTPRoute timeout-overlay \
29298                 emitter's read",
29299            );
29300        }
29301
29302        // (2) Accessor byte-equal to raw field on the `:retries` axis
29303        // across the accept-set boundaries the bracket dispatch's
29304        // two-arm gate carves out
29305        // ([`crate::render::require_positive_bounded_u32`] — zero-floor
29306        // + upper-cap).
29307        for retries in [
29308            None,
29309            Some(0u32),
29310            Some(1u32),
29311            Some(POLICY_RETRIES_MAX),
29312            Some(POLICY_RETRIES_MAX + 1),
29313            Some(u32::MAX),
29314        ] {
29315            let p = MeshPolicy {
29316                retries,
29317                ..MeshPolicy::default()
29318            };
29319            assert_eq!(
29320                p.retries(),
29321                p.retries,
29322                "MeshPolicy::retries accessor must byte-equal the raw \
29323                 .retries field across every accept-set boundary the \
29324                 validate_politicas :retries arm carves out — a drift \
29325                 here would silently split the validate bracket's arm \
29326                 from the peer caixa-mesh HTTPRoute retry-overlay \
29327                 emitter's read",
29328            );
29329        }
29330
29331        // (3) `PolicyTimeoutZero` fires on the accessor-projected
29332        // zero-floor boundary. A silent detour that no longer read
29333        // through `p.timeout()` (a peer-axis field read, an accidental
29334        // Option::and-then chain that collapsed the None arm to Some,
29335        // an accessor rebrand that clamped the return through the
29336        // upper cap) would fail to refuse here.
29337        let mut spec = three_member_spec();
29338        spec.politicas.timeout = Some(Duration::ZERO);
29339        spec.politicas.retries = None;
29340        spec.politicas.circuit_breaker = None;
29341        spec.politicas.rate_limit = None;
29342        assert_eq!(
29343            spec.politicas().timeout(),
29344            Some(Duration::ZERO),
29345            "the accessor projection must reflect the fixture's \
29346             `Some(Duration::ZERO)` :timeout verbatim",
29347        );
29348        assert_eq!(
29349            spec.validate().unwrap_err(),
29350            AplicacaoError::PolicyTimeoutZero,
29351            "the validate_politicas :timeout zero-floor arm must fire \
29352             through the lifted accessor's projection — a silent \
29353             detour to a peer-axis field would fail to refuse",
29354        );
29355
29356        // (4) `PolicyRetriesZero` fires on the accessor-projected
29357        // zero-floor boundary on the sibling `:retries` axis.
29358        let mut spec = three_member_spec();
29359        spec.politicas.timeout = None;
29360        spec.politicas.retries = Some(0);
29361        spec.politicas.circuit_breaker = None;
29362        spec.politicas.rate_limit = None;
29363        assert_eq!(
29364            spec.politicas().retries(),
29365            Some(0),
29366            "the accessor projection must reflect the fixture's \
29367             `Some(0)` :retries verbatim",
29368        );
29369        assert_eq!(
29370            spec.validate().unwrap_err(),
29371            AplicacaoError::PolicyRetriesZero,
29372            "the validate_politicas :retries zero-floor arm must fire \
29373             through the lifted accessor's projection — a silent \
29374             detour to a peer-axis field would fail to refuse",
29375        );
29376
29377        // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
29378        // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
29379        // must pass validate under the accessor projection — pins the
29380        // upper-boundary accept-arm also routes through the lifted
29381        // accessor (a drift that clamped or short-circuited at the
29382        // upper boundary would fail the whole-spec validate here).
29383        let mut spec = three_member_spec();
29384        spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
29385        spec.politicas.retries = Some(POLICY_RETRIES_MAX);
29386        spec.politicas.circuit_breaker = None;
29387        spec.politicas.rate_limit = None;
29388        assert_eq!(
29389            spec.politicas().timeout(),
29390            Some(POLICY_TIMEOUT_MAX),
29391            "the accessor projection must reflect the fixture's \
29392             at-cap :timeout verbatim",
29393        );
29394        assert_eq!(
29395            spec.politicas().retries(),
29396            Some(POLICY_RETRIES_MAX),
29397            "the accessor projection must reflect the fixture's \
29398             at-cap :retries verbatim",
29399        );
29400        assert!(
29401            spec.validate().is_ok(),
29402            "at-cap :timeout + :retries must pass validate under the \
29403             accessor projection — the upper-boundary accept-arm on \
29404             both axes routes through the lifted accessor",
29405        );
29406    }
29407
29408    #[test]
29409    fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
29410        // The canonical per-`:placement` outer-composite-reference-shape
29411        // pin: [`AplicacaoSpec::placement`] must return the `:placement`
29412        // typed `Placement` verbatim as a `&Placement` reference over the
29413        // same backing storage the raw `&self.placement` field access
29414        // borrows from, byte-equal across every representative fixture in
29415        // the accept-set — the default `Placement` (the substrate seed
29416        // shape whose [`PlacementStrategy::default`] evaluates to
29417        // `SingleNode` with an empty `:clusters` pool and both
29418        // optional-scalar axes `None`), and every canonical strategy /
29419        // cluster-pool / optional-scalar combination the
29420        // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
29421        // three [`PlacementStrategy`] variants — `SingleNode`,
29422        // `Replicated`, `Sharded` — cross-projected with a non-empty
29423        // `:clusters` pool and, on the `Sharded` arm, a non-empty
29424        // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
29425        // canonical `three_member_spec` `Replicated` fixture's
29426        // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
29427        //
29428        // Pins against a future silent detour that returned a fresh-
29429        // cloned `Placement` copy (which would type-check via a `Clone`
29430        // impl but silently break every downstream caller that relied on
29431        // the reference sharing the composite's backing identity), a
29432        // reference to an operator-resolved overlay (the future per-
29433        // cluster `:placement-overrides` slot MESH-COMPOSITION §V
29434        // acknowledges — its resolution must land at exactly this
29435        // accessor body, not silently divert the raw slot away from a
29436        // second consumer), or an axis-shuffled projection (a future
29437        // detour that swapped `clusters` and `affinity` through the
29438        // accessor would silently split the paired `validate_placement`
29439        // per-axis bracket-dispatch's traversal input from the peer
29440        // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
29441        // programs.yaml distribution-annotation emitter's fan-out input
29442        // from the peer `feira app graph` per-Aplicacao print line's
29443        // input).
29444        //
29445        // Peer of the sibling M3
29446        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
29447        // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
29448        // outer mesh-policy composite-reference axis, and of the sibling
29449        // slice-return `aplicacao_spec_membros_returns_membros_slice_
29450        // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
29451        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
29452        // across_permutations` (0dcc926) `&[WitContract]` pins — extends
29453        // the outer-accessor byte-equal-projection discipline onto the
29454        // outermost M3 mesh-slot type's per-Aplicacao distribution
29455        // composite-reference axis, the second `&Composite`-return
29456        // accessor on the outer [`AplicacaoSpec`] type.
29457        let fixtures: Vec<Placement> = vec![
29458            Placement::default(),
29459            Placement {
29460                estrategia: PlacementStrategy::SingleNode,
29461                clusters: vec!["rio".into()],
29462                affinity: None,
29463                shard_key: None,
29464            },
29465            Placement {
29466                estrategia: PlacementStrategy::Replicated,
29467                clusters: vec!["rio".into(), "mar".into()],
29468                affinity: None,
29469                shard_key: None,
29470            },
29471            Placement {
29472                estrategia: PlacementStrategy::Replicated,
29473                clusters: vec!["rio".into(), "mar".into()],
29474                affinity: Some("data-locality".into()),
29475                shard_key: None,
29476            },
29477            Placement {
29478                estrategia: PlacementStrategy::Sharded,
29479                clusters: vec!["rio".into(), "mar".into()],
29480                affinity: None,
29481                shard_key: Some("tenantId".into()),
29482            },
29483            Placement {
29484                estrategia: PlacementStrategy::Sharded,
29485                clusters: vec!["rio".into(), "mar".into(), "sol".into()],
29486                affinity: Some("low-latency".into()),
29487                shard_key: Some("metadata.tenantId".into()),
29488            },
29489        ];
29490        for placement in fixtures {
29491            let s = AplicacaoSpec {
29492                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
29493                contratos: Vec::new(),
29494                politicas: MeshPolicy::default(),
29495                placement: placement.clone(),
29496                entrada: None,
29497            };
29498            assert_eq!(
29499                *s.placement(),
29500                placement,
29501                "AplicacaoSpec::placement must return :placement verbatim \
29502                 (got {:?}, expected {:?})",
29503                s.placement(),
29504                placement,
29505            );
29506            assert!(
29507                std::ptr::eq(s.placement(), &s.placement),
29508                "AplicacaoSpec::placement accessor and &self.placement \
29509                 field access must borrow the same backing storage — the \
29510                 accessor is the substrate-primitive typed dispatch every \
29511                 downstream distribution-composite consumer must route \
29512                 through, and a reference-identity split would silently \
29513                 break every consumer that relied on the borrow sharing \
29514                 the composite's storage",
29515            );
29516            assert_eq!(
29517                s.placement().estrategia(),
29518                s.placement.estrategia,
29519                "AplicacaoSpec::placement().estrategia() must byte-equal \
29520                 self.placement.estrategia — a strategy-drift would \
29521                 silently split the paired `validate_placement` \
29522                 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
29523                 peer caixa-mesh programs.yaml `placement.estrategia` \
29524                 emitter's key from the peer `feira app graph` printer's \
29525                 strategy label",
29526            );
29527            assert_eq!(
29528                s.placement().clusters(),
29529                s.placement.clusters.as_slice(),
29530                "AplicacaoSpec::placement().clusters() must byte-equal \
29531                 self.placement.clusters — a cluster-pool drift would \
29532                 silently split the paired `validate_placement` \
29533                 pre-flight `.is_empty()` refusal probe's traversal from \
29534                 the peer caixa-mesh programs.yaml `placement.clusters` \
29535                 emitter's fan-out from the peer `feira app graph` \
29536                 printer's cluster list",
29537            );
29538        }
29539    }
29540
29541    #[test]
29542    fn validate_placement_reads_through_lifted_placement_accessor() {
29543        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
29544        // per-axis bracket-dispatch seed (`let p = self.placement();`,
29545        // followed by the per-axis fan-out `p.clusters()` /
29546        // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
29547        // lifted axis-level accessor family) must key off the lifted
29548        // outer accessor, so any future rebrand on the typed slot's
29549        // outer-composite reader shape lands at exactly one place. Pins
29550        // the multi-axis coherence by exercising each per-axis refusal
29551        // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
29552        // `:clusters` pool under the outer accessor's reference
29553        // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
29554        // strategy with a `None` `:shard-key` under the same projection,
29555        // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
29556        // with a `Some` `:shard-key` under the same projection, and
29557        // (4) the canonical `three_member_spec` `Replicated` fixture
29558        // passes `validate_placement` under the outer accessor's
29559        // reference projection — the accessor's reference-projection
29560        // reaches every per-axis branch (cluster-pool refusal, `Sharded`
29561        // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
29562        // without silently short-circuiting any.
29563        //
29564        // Peer of the sibling M3
29565        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
29566        // (534dc21) multi-axis coherence pin on the per-`:politicas`
29567        // outer mesh-policy composite-reference axis — extends the
29568        // multi-consumer coherence discipline onto the outermost M3
29569        // mesh-slot type's per-Aplicacao distribution composite-
29570        // reference axis, the second `&Composite`-return accessor on
29571        // the outer [`AplicacaoSpec`] type.
29572
29573        // (1) `PlacementWithoutClusters` refusal under the outer
29574        // accessor's reference projection: an empty `:clusters` pool
29575        // must trip the pre-flight refusal probe. The bracket-dispatch's
29576        // first arm reads `p.clusters()` on the reference returned by
29577        // the outer accessor.
29578        let mut spec = three_member_spec();
29579        spec.placement.clusters = Vec::new();
29580        assert_eq!(
29581            spec.validate().unwrap_err(),
29582            AplicacaoError::PlacementWithoutClusters {
29583                estrategia: PlacementStrategy::Replicated,
29584            },
29585        );
29586        assert!(
29587            std::ptr::eq(spec.placement(), &spec.placement),
29588            "the `validate_placement` per-axis bracket-dispatch's \
29589             traversal input must be the same backing composite the \
29590             accessor's reference projection borrows from",
29591        );
29592
29593        // (2) `ShardedWithoutKey` refusal under the outer accessor's
29594        // reference projection: a `Sharded` strategy with a `None`
29595        // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
29596        // The bracket-dispatch's third arm reads `p.estrategia()` for
29597        // the match scrutinee then `p.shard_key()` for the cascade
29598        // scrutinee, both on the reference returned by the outer
29599        // accessor.
29600        let mut spec = three_member_spec();
29601        spec.placement.estrategia = PlacementStrategy::Sharded;
29602        spec.placement.shard_key = None;
29603        assert_eq!(
29604            spec.validate().unwrap_err(),
29605            AplicacaoError::ShardedWithoutKey,
29606        );
29607
29608        // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
29609        // reference projection: a non-`Sharded` strategy with a `Some`
29610        // `:shard-key` must trip the declared-but-inert refusal. The
29611        // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
29612        // + `p.estrategia()` for the diagnostic on the reference
29613        // returned by the outer accessor.
29614        let mut spec = three_member_spec();
29615        spec.placement.estrategia = PlacementStrategy::Replicated;
29616        spec.placement.shard_key = Some("tenantId".into());
29617        assert_eq!(
29618            spec.validate().unwrap_err(),
29619            AplicacaoError::ShardKeyOnNonSharded {
29620                estrategia: PlacementStrategy::Replicated,
29621                shard_key: "tenantId".into(),
29622            },
29623        );
29624
29625        // (4) Canonical `three_member_spec` `Replicated` fixture passes
29626        // `validate_placement` — every per-axis arm reaches the fall-
29627        // through `Ok(())` without any per-axis refusal firing under the
29628        // outer accessor's reference projection.
29629        let spec = three_member_spec();
29630        assert!(
29631            spec.validate().is_ok(),
29632            "the canonical Replicated placement fixture must pass \
29633             `validate_placement` — every per-axis arm short-circuits on \
29634             valid input under the outer accessor's reference projection",
29635        );
29636        assert_eq!(
29637            spec.placement().estrategia(),
29638            PlacementStrategy::Replicated,
29639            "the outer accessor's reference projection must be the \
29640             canonical Replicated fixture's strategy",
29641        );
29642        assert_eq!(
29643            spec.placement().clusters(),
29644            &["rio", "mar"],
29645            "the outer accessor's reference projection must be the \
29646             canonical Replicated fixture's cluster pool",
29647        );
29648    }
29649
29650    #[test]
29651    fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
29652        // The canonical per-`:entrada` outer-composite-optional-
29653        // reference-shape pin: [`AplicacaoSpec::entrada`] must return
29654        // the `:entrada` typed `Option<Entrada>` verbatim as an
29655        // `Option<&Entrada>` reference over the same backing storage
29656        // the raw `self.entrada.as_ref()` field access borrows from,
29657        // byte-equal across every representative fixture in the
29658        // accept-set — the author-omitted `None` shape (the
29659        // "internal-only mesh" partition every downstream external-
29660        // gateway emitter treats as "emit nothing"), the minimal
29661        // singleton `:entrada` composite (host + destination + empty
29662        // paths + default port), the paths-carrying composite (the
29663        // canonical `three_member_spec` fixture's ["/api" "/health"]
29664        // path-list shape every HTTPRoute per-rule fan-out emitter
29665        // reads), and the non-default port composite (the canonical
29666        // custom-port shape the port-fallback resolver reads).
29667        //
29668        // Pins against a future silent detour that returned a fresh-
29669        // cloned `Entrada` copy (which would type-check via a `Clone`
29670        // impl but silently break every downstream caller that
29671        // relied on the reference sharing the composite's backing
29672        // identity), a reference to an operator-resolved overlay
29673        // (the future per-cluster `:entrada-overrides` slot the
29674        // MESH-COMPOSITION §V federation roadmap acknowledges — its
29675        // resolution must land at exactly this accessor body, not
29676        // silently divert the raw slot away from a second consumer),
29677        // a `None` → `Some(Entrada::default)` cluster-default
29678        // projection (which would collapse the load-bearing
29679        // "author-omitted `:entrada` ⇒ internal-only mesh" partition
29680        // the peer `gateway_routes` early-return + `feira app graph`
29681        // internal-only-mesh partition both read), or an axis-
29682        // shuffled projection (a future detour that swapped
29683        // `host` and `para` through the accessor would silently
29684        // split the paired `validate` per-`:entrada` shape-and-
29685        // membership gate's traversal input from the peer
29686        // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
29687        // fan-out input from the peer `feira app graph` external-
29688        // gateway summary line).
29689        //
29690        // Peer of the sibling M3
29691        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
29692        // (534dc21) `&MeshPolicy` byte-equal pin on the per-
29693        // `:politicas` outer mesh-policy composite-reference axis
29694        // and of the sibling M3
29695        // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
29696        // (9abb8f0) `&Placement` byte-equal pin on the per-
29697        // `:placement` outer distribution-composite composite-
29698        // reference axis — extends the outer-accessor byte-equal-
29699        // projection discipline onto the last unlifted outermost M3
29700        // mesh-slot type's per-Aplicacao external-gateway composite-
29701        // reference axis, the third and final `&Composite`-return
29702        // accessor on the outer [`AplicacaoSpec`] type.
29703        let fixtures: Vec<Option<Entrada>> = vec![
29704            None,
29705            Some(Entrada {
29706                host: "checkout.quero.cloud".into(),
29707                para: "cart".into(),
29708                paths: Vec::new(),
29709                port: DEFAULT_SERVICO_PORT,
29710            }),
29711            Some(Entrada {
29712                host: "checkout.quero.cloud".into(),
29713                para: "cart".into(),
29714                paths: vec!["/api".into(), "/health".into()],
29715                port: DEFAULT_SERVICO_PORT,
29716            }),
29717            Some(Entrada {
29718                host: "checkout.quero.cloud".into(),
29719                para: "cart".into(),
29720                paths: vec!["/api".into()],
29721                port: 9443,
29722            }),
29723        ];
29724        for entrada in fixtures {
29725            let s = AplicacaoSpec {
29726                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
29727                contratos: Vec::new(),
29728                politicas: MeshPolicy::default(),
29729                placement: Placement::default(),
29730                entrada: entrada.clone(),
29731            };
29732            assert_eq!(
29733                s.entrada(),
29734                entrada.as_ref(),
29735                "AplicacaoSpec::entrada must return :entrada verbatim \
29736                 (got {:?}, expected {:?})",
29737                s.entrada(),
29738                entrada.as_ref(),
29739            );
29740            match (s.entrada(), s.entrada.as_ref()) {
29741                (Some(a), Some(b)) => assert!(
29742                    std::ptr::eq(a, b),
29743                    "AplicacaoSpec::entrada accessor and \
29744                     self.entrada.as_ref() field access must borrow \
29745                     the same backing storage — the accessor is the \
29746                     substrate-primitive typed dispatch every \
29747                     downstream external-gateway composite consumer \
29748                     must route through, and a reference-identity \
29749                     split would silently break every consumer that \
29750                     relied on the borrow sharing the composite's \
29751                     storage",
29752                ),
29753                (None, None) => {}
29754                _ => panic!(
29755                    "AplicacaoSpec::entrada presence bit must byte-\
29756                     equal self.entrada.is_some() — a presence-bit \
29757                     drift would silently split the paired `validate` \
29758                     per-`:entrada` shape-and-membership gate's \
29759                     traversal head from the peer \
29760                     caixa-mesh gateway_routes early-return partition \
29761                     from the peer `feira app graph` internal-only-\
29762                     mesh partition",
29763                ),
29764            }
29765            assert_eq!(
29766                s.entrada().is_some(),
29767                s.entrada.is_some(),
29768                "AplicacaoSpec::entrada().is_some() must byte-equal \
29769                 self.entrada.is_some() — a presence-bit drift would \
29770                 silently split every downstream `Option<&Entrada>` \
29771                 consumer's partition on the internal-only-mesh arm",
29772            );
29773        }
29774    }
29775
29776    #[test]
29777    fn validate_reads_through_lifted_entrada_accessor() {
29778        // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
29779        // per-`:entrada` shape-and-membership gate (`if let Some(e) =
29780        // self.entrada() { … }`, followed by the per-axis fan-out
29781        // `validate_entrada_para(&e.para)` /
29782        // `EntradaMemberMissing` membership lookup /
29783        // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
29784        // per-`e.paths` `validate_entrada_path` traversal) must key
29785        // off the lifted outer accessor, so any future rebrand on
29786        // the typed slot's outer-composite reader shape lands at
29787        // exactly one place. Pins the multi-axis coherence by
29788        // exercising each per-axis refusal end-to-end: (1) the
29789        // author-omitted `None` shape short-circuits past every
29790        // per-`:entrada` refusal (the internal-only mesh partition
29791        // the accessor's `None` arm names), (2) `EntradaMemberMissing`
29792        // fires on a well-shaped but phantom `:para` under the outer
29793        // accessor's reference projection, and (3) the canonical
29794        // `three_member_spec` `:entrada` fixture passes `validate`
29795        // under the outer accessor's reference projection.
29796        //
29797        // Peer of the sibling M3
29798        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
29799        // (534dc21) multi-axis coherence pin on the per-`:politicas`
29800        // outer mesh-policy composite-reference axis and the sibling
29801        // M3
29802        // [`validate_placement_reads_through_lifted_placement_accessor`]
29803        // (9abb8f0) multi-axis coherence pin on the per-`:placement`
29804        // outer distribution-composite composite-reference axis —
29805        // extends the multi-consumer coherence discipline onto the
29806        // last unlifted outermost M3 mesh-slot type's per-Aplicacao
29807        // external-gateway composite-reference axis, the third and
29808        // final `&Composite`-return accessor on the outer
29809        // [`AplicacaoSpec`] type.
29810
29811        // (1) `None` :entrada — the internal-only-mesh partition
29812        // short-circuits past every per-`:entrada` refusal. The outer
29813        // accessor's reference projection reaches the fall-through
29814        // `Ok(())` on the `None` arm without any per-axis refusal
29815        // firing.
29816        let mut spec = three_member_spec();
29817        spec.entrada = None;
29818        assert!(
29819            spec.validate().is_ok(),
29820            "an author-omitted `:entrada` must pass `validate` — the \
29821             internal-only-mesh partition short-circuits past every \
29822             per-`:entrada` refusal under the outer accessor's \
29823             reference projection",
29824        );
29825        assert!(
29826            spec.entrada().is_none(),
29827            "the outer accessor's reference projection must name the \
29828             internal-only-mesh partition per the `None` fixture",
29829        );
29830
29831        // (2) `EntradaMemberMissing` refusal under the outer accessor's
29832        // reference projection: a well-shaped but phantom `:para` must
29833        // trip the membership-lookup refusal. The gate's second arm
29834        // reads `e.para` on the reference returned by the outer
29835        // accessor.
29836        let mut spec = three_member_spec();
29837        if let Some(e) = spec.entrada.as_mut() {
29838            e.para = "phantom".into();
29839        }
29840        assert_eq!(
29841            spec.validate().unwrap_err(),
29842            AplicacaoError::EntradaMemberMissing {
29843                para: "phantom".into(),
29844            },
29845        );
29846        match (spec.entrada(), spec.entrada.as_ref()) {
29847            (Some(a), Some(b)) => assert!(
29848                std::ptr::eq(a, b),
29849                "the `validate` per-`:entrada` gate's traversal head \
29850                 must be the same backing composite the accessor's \
29851                 reference projection borrows from",
29852            ),
29853            _ => panic!("fixture must carry Some(:entrada)"),
29854        }
29855
29856        // (3) Canonical `three_member_spec` `:entrada` fixture passes
29857        // `validate` — every per-axis arm reaches the fall-through
29858        // `Ok(())` without any per-axis refusal firing under the
29859        // outer accessor's reference projection.
29860        let spec = three_member_spec();
29861        assert!(
29862            spec.validate().is_ok(),
29863            "the canonical `:entrada` fixture must pass `validate` — \
29864             every per-axis arm short-circuits on valid input under \
29865             the outer accessor's reference projection",
29866        );
29867        assert!(
29868            spec.entrada().is_some(),
29869            "the outer accessor's reference projection must be the \
29870             canonical `:entrada` fixture's composite",
29871        );
29872    }
29873
29874    #[test]
29875    fn membro_names_matches_inline_membros_projection() {
29876        // Substrate-primitive ≡ inline-projection pin on
29877        // [`AplicacaoSpec::membro_names`]: the lifted membership oracle
29878        // must be byte-for-byte the set the pre-lift inline
29879        // `self.membros().iter().map(Membro::nome).collect()` builder
29880        // produced, on every membership shape the three
29881        // Servico-name-*reference* axes (`:contratos :de`, `:contratos
29882        // :para`, `:entrada :para`) resolve against. Pins the
29883        // projection so a future rebrand of the node-identity axis
29884        // lands at the primitive rather than diverging between the
29885        // per-`:contratos` membership arms still inline at `validate`
29886        // and the lifted `validate_entrada` gate.
29887        for membros in [
29888            vec![],
29889            vec![membro("cart", "^0.1")],
29890            vec![
29891                membro("catalog", "^0.1"),
29892                membro("cart", "^0.1"),
29893                membro("payment", "^0.2"),
29894            ],
29895        ] {
29896            let mut spec = three_member_spec();
29897            spec.membros = membros;
29898            let inline: std::collections::HashSet<&str> =
29899                spec.membros().iter().map(Membro::nome).collect();
29900            assert_eq!(
29901                spec.membro_names(),
29902                inline,
29903                "the lifted membership oracle must discriminate the \
29904                 same node set as the pre-lift inline projection",
29905            );
29906        }
29907    }
29908
29909    #[test]
29910    fn validate_entrada_matches_gate_on_every_per_axis_shape() {
29911        // Per-slot-gate ≡ validate equivalence pin on the lifted
29912        // [`AplicacaoSpec::validate_entrada`]: the named per-slot gate
29913        // must discriminate the same set as [`AplicacaoSpec::validate`]
29914        // on every `:entrada`-covered input, so a future consumer that
29915        // re-validates the one slot (the M4 admission webhook
29916        // re-checking `:entrada` after a gateway-host patch) accepts
29917        // exactly what `feira build` accepts and surfaces the same
29918        // diagnostic on the same input. Covers each of the five gated
29919        // axes plus the two clean-pass shapes (`None` — the
29920        // internal-only-mesh partition — and the canonical fixture).
29921        //
29922        // Peer of the sibling per-slot equivalence pins
29923        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
29924        // / `_on_cross_axis_and_clean_pass_shapes` (f03a154) on the
29925        // `:politicas` slot's compound entry gate, extended here onto
29926        // the `:entrada` slot's newly-named per-slot gate.
29927        /// One `:entrada` equivalence case: a label, the per-axis
29928        /// mutation applied to the canonical fixture's composite, and
29929        /// the diagnostic both the per-slot gate and `validate` must
29930        /// surface on it (`None` = clean pass).
29931        type EntradaCase = (&'static str, fn(&mut Entrada), Option<AplicacaoError>);
29932
29933        let cases: &[EntradaCase] = &[
29934            (
29935                ":para shape — empty",
29936                |e| e.para = String::new(),
29937                Some(AplicacaoError::EntradaParaEmpty),
29938            ),
29939            (
29940                ":para membership — well-shaped phantom",
29941                |e| e.para = "phantom".into(),
29942                Some(AplicacaoError::EntradaMemberMissing {
29943                    para: "phantom".into(),
29944                }),
29945            ),
29946            (
29947                ":host emptiness",
29948                |e| e.host = String::new(),
29949                Some(AplicacaoError::EmptyEntradaHost),
29950            ),
29951            (
29952                ":port structural floor",
29953                |e| e.port = 0,
29954                Some(AplicacaoError::EntradaPortZero),
29955            ),
29956            (
29957                ":paths per-entry emptiness",
29958                |e| e.paths = vec![String::new()],
29959                Some(AplicacaoError::EntradaPathEmpty),
29960            ),
29961            (
29962                ":paths leading-slash grammar",
29963                |e| e.paths = vec!["api/cart".into()],
29964                Some(AplicacaoError::EntradaPathNotAbsolute {
29965                    path: "api/cart".into(),
29966                }),
29967            ),
29968            (
29969                ":paths set-not-multiset",
29970                |e| e.paths = vec!["/api/cart".into(), "/api/cart".into()],
29971                Some(AplicacaoError::EntradaPathDuplicate {
29972                    path: "/api/cart".into(),
29973                }),
29974            ),
29975            ("clean pass — canonical fixture", |_| {}, None),
29976        ];
29977        for (label, mutate, expected) in cases {
29978            let mut spec = three_member_spec();
29979            mutate(spec.entrada.as_mut().expect("fixture carries :entrada"));
29980            assert_eq!(
29981                spec.validate_entrada().err(),
29982                *expected,
29983                "per-slot gate disagreed with the expected diagnostic on {label}",
29984            );
29985            assert_eq!(
29986                spec.validate().err(),
29987                *expected,
29988                "`validate` disagreed with the per-slot gate on {label}",
29989            );
29990        }
29991
29992        // The `None` arm is the internal-only-mesh partition: a clean
29993        // pass through both the per-slot gate and `validate`, not a
29994        // refusal.
29995        let mut spec = three_member_spec();
29996        spec.entrada = None;
29997        assert_eq!(spec.validate_entrada().err(), None);
29998        assert_eq!(spec.validate().err(), None);
29999    }
30000
30001    #[test]
30002    fn validate_entrada_resolves_membership_through_own_oracle() {
30003        // Self-containment pin on the lifted per-slot gate:
30004        // [`AplicacaoSpec::validate_entrada`] resolves `:entrada :para`
30005        // against the oracle *it* builds through
30006        // [`AplicacaoSpec::membro_names`], not one threaded down from
30007        // [`AplicacaoSpec::validate`]. A spec whose `:membros` no
30008        // longer contains the `:entrada :para` target must trip
30009        // `EntradaMemberMissing` when the per-slot gate is called
30010        // directly — the shape a future single-slot re-validator
30011        // (the M4 admission webhook) reaches the axis through, without
30012        // re-walking `:membros` / `:contratos` / the sync-cycle
30013        // detector first. Same self-contained posture
30014        // [`AplicacaoSpec::detect_sync_cycles`] already carries for
30015        // the M4 per-edge policy resolver.
30016        let mut spec = three_member_spec();
30017        spec.membros.retain(|m| m.nome() != "cart");
30018        assert_eq!(
30019            spec.validate_entrada().unwrap_err(),
30020            AplicacaoError::EntradaMemberMissing {
30021                para: "cart".into(),
30022            },
30023            "the per-slot gate must resolve `:para` against the oracle \
30024             it builds itself, with no membership set threaded in",
30025        );
30026        assert!(
30027            !spec.membro_names().contains("cart"),
30028            "fixture must have dropped the `:entrada :para` target \
30029             from the graph's node set",
30030        );
30031    }
30032
30033    #[test]
30034    fn validate_contratos_matches_gate_on_every_per_axis_shape() {
30035        // Per-slot-gate ≡ validate equivalence pin on the lifted
30036        // [`AplicacaoSpec::validate_contratos`]: the named per-slot
30037        // gate must discriminate the same set as
30038        // [`AplicacaoSpec::validate`] on every `:contratos`-covered
30039        // input, so a future consumer that re-validates the one slot
30040        // (the M4 admission webhook re-checking `:contratos` after a
30041        // per-`(:de, :para)` edge patch, the per-`:contratos`-edge
30042        // `:politicas` override MESH-COMPOSITION §III.2 #3
30043        // acknowledges — which resolves an effective per-edge
30044        // [`MeshPolicy`] and must re-check the edge's identity closure
30045        // before it can key a per-edge override off the endpoint
30046        // tuple) accepts exactly what `feira build` accepts and
30047        // surfaces the same diagnostic on the same input. Covers each
30048        // of the six gated axes (`:de`/`:para` per-arm shape,
30049        // per-arm graph-membership, structural self-loop, `:wit`
30050        // emptiness) plus the clean-pass canonical fixture; the
30051        // reason-carrying arms (`ContratoCaixaInvalid` on `:de`/`:para`
30052        // shape, `ContratoWitInvalid` on WIT-shape ↔ target dispatch,
30053        // `ContratoDuplicate` on whole-edge dedup) whose `reason:` /
30054        // `target:` carriers depend on library implementation
30055        // details are pinned separately below with a `matches!`
30056        // predicate on the arm identity plus the mirror equivalence
30057        // between the two entry points.
30058        //
30059        // Peer of the sibling per-slot equivalence pins
30060        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
30061        // / `_on_cross_axis_and_clean_pass_shapes` (f03a154) on the
30062        // `:politicas` slot's compound entry gate, and
30063        // `validate_entrada_matches_gate_on_every_per_axis_shape`
30064        // (20cd523) on the `:entrada` slot's per-slot gate — extended
30065        // here onto the `:contratos` slot's newly-named per-slot gate,
30066        // closing the last unlifted per-slot gate on the M3 mesh-slot
30067        // family.
30068        /// One `:contratos` equivalence case: a label, the per-axis
30069        /// mutation applied to the canonical fixture's spec, and the
30070        /// diagnostic both the per-slot gate and `validate` must
30071        /// surface on it (`None` = clean pass).
30072        type ContratoCase = (&'static str, fn(&mut AplicacaoSpec), Option<AplicacaoError>);
30073
30074        let cases: &[ContratoCase] = &[
30075            (
30076                ":de shape — empty",
30077                |s| s.contratos[0].de = String::new(),
30078                Some(AplicacaoError::ContratoCaixaEmpty {
30079                    slot: crate::render::CONTRATO_AUTHOR_KEY_DE,
30080                }),
30081            ),
30082            (
30083                ":para shape — empty",
30084                |s| s.contratos[0].para = String::new(),
30085                Some(AplicacaoError::ContratoCaixaEmpty {
30086                    slot: crate::render::CONTRATO_AUTHOR_KEY_PARA,
30087                }),
30088            ),
30089            (
30090                ":de membership — well-shaped phantom",
30091                |s| s.contratos[0].de = "phantom".into(),
30092                Some(AplicacaoError::ContratoMemberMissing {
30093                    caixa: "phantom".into(),
30094                }),
30095            ),
30096            (
30097                ":para membership — well-shaped phantom",
30098                |s| s.contratos[0].para = "phantom".into(),
30099                Some(AplicacaoError::ContratoMemberMissing {
30100                    caixa: "phantom".into(),
30101                }),
30102            ),
30103            (
30104                "structural self-loop",
30105                |s| s.contratos[0].para = "cart".into(),
30106                Some(AplicacaoError::ContratoSelfLoop {
30107                    caixa: "cart".into(),
30108                    wit: "wasi:http/proxy".into(),
30109                }),
30110            ),
30111            (
30112                ":wit emptiness",
30113                |s| s.contratos[0].wit = String::new(),
30114                Some(AplicacaoError::EmptyWit {
30115                    de: "cart".into(),
30116                    para: "catalog".into(),
30117                }),
30118            ),
30119            ("clean pass — canonical fixture", |_| {}, None),
30120        ];
30121        for (label, mutate, expected) in cases {
30122            let mut spec = three_member_spec();
30123            mutate(&mut spec);
30124            assert_eq!(
30125                spec.validate_contratos().err(),
30126                *expected,
30127                "per-slot gate disagreed with the expected diagnostic on {label}",
30128            );
30129            assert_eq!(
30130                spec.validate().err(),
30131                *expected,
30132                "`validate` disagreed with the per-slot gate on {label}",
30133            );
30134        }
30135    }
30136
30137    #[test]
30138    fn validate_contratos_matches_gate_on_reason_carrying_arms() {
30139        // Companion pin to
30140        // [`validate_contratos_matches_gate_on_every_per_axis_shape`]:
30141        // the per-slot gate ≡ `validate` equivalence on the three
30142        // `:contratos` refusal arms whose diagnostic carries a
30143        // library-owned string ([`AplicacaoError::ContratoCaixaInvalid`]
30144        // and [`AplicacaoError::ContratoWrongTarget`] via the paired
30145        // `is_dns_1123_label` / `WitContract::target` shape helpers,
30146        // and [`AplicacaoError::ContratoDuplicate`] via [`WitTarget::label`]'s
30147        // library-formatted `target:` scalar). Value equality between
30148        // the per-slot gate and `validate` outputs pins the full
30149        // `Option<AplicacaoError>` (including reason-strings), and the
30150        // per-arm `matches!` predicate pins the arm-discriminator
30151        // identity on the specific `Contrato*` variant. Split from
30152        // the primary equivalence pin so each pin body stays under
30153        // [`clippy::too_many_lines`], the same shape the peer
30154        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
30155        // / `_on_cross_axis_and_clean_pass_shapes` split (f03a154)
30156        // carries on the `:politicas` slot's compound entry gate.
30157        type ContratoReasonCase = (
30158            &'static str,
30159            fn(&mut AplicacaoSpec),
30160            fn(&AplicacaoError) -> bool,
30161        );
30162        let cases: &[ContratoReasonCase] = &[
30163            (
30164                ":de shape — DNS-1123 invalid",
30165                |s| s.contratos[0].de = "Cart".into(),
30166                |err| {
30167                    matches!(
30168                        err,
30169                        AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. }
30170                            if *slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
30171                    )
30172                },
30173            ),
30174            (
30175                ":wit target-shape mismatch — payload on capability arm",
30176                |s| s.contratos[0].wit = "wasi:junk/nope".into(),
30177                |err| {
30178                    matches!(
30179                        err,
30180                        AplicacaoError::ContratoWrongTarget { de, para, wit, .. }
30181                            if de == "cart" && para == "catalog" && wit == "wasi:junk/nope"
30182                    )
30183                },
30184            ),
30185            (
30186                "whole-edge dedup — six-axis identity collision",
30187                |s| {
30188                    let dup = s.contratos[0].clone();
30189                    s.contratos.push(dup);
30190                },
30191                |err| {
30192                    matches!(
30193                        err,
30194                        AplicacaoError::ContratoDuplicate { de, para, wit, .. }
30195                            if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
30196                    )
30197                },
30198            ),
30199        ];
30200        for (label, mutate, arm_matches) in cases {
30201            let mut spec = three_member_spec();
30202            mutate(&mut spec);
30203            let per_slot = spec.validate_contratos().err();
30204            let gate = spec.validate().err();
30205            assert_eq!(
30206                per_slot, gate,
30207                "per-slot gate and `validate` must return byte-equal \
30208                 `Option<AplicacaoError>` on {label} (including \
30209                 library-owned reason strings)",
30210            );
30211            let err = per_slot
30212                .as_ref()
30213                .unwrap_or_else(|| panic!("expected refusal on {label}, got clean pass"));
30214            assert!(
30215                arm_matches(err),
30216                "per-slot gate surfaced the wrong arm on {label}: got {err:?}",
30217            );
30218        }
30219    }
30220
30221    #[test]
30222    fn validate_contratos_resolves_membership_through_own_oracle() {
30223        // Self-containment pin on the lifted per-slot gate:
30224        // [`AplicacaoSpec::validate_contratos`] resolves each edge's
30225        // `:de` / `:para` against the oracle *it* builds through
30226        // [`AplicacaoSpec::membro_names`], not one threaded down from
30227        // [`AplicacaoSpec::validate`]. A spec whose `:membros` no
30228        // longer contains a `:contratos` edge's endpoint must trip
30229        // `ContratoMemberMissing` when the per-slot gate is called
30230        // directly — the shape a future single-slot re-validator
30231        // (the M4 admission webhook re-checking `:contratos` after a
30232        // per-`(:de, :para)` edge patch, the M4 per-edge policy
30233        // resolver on the `:politicas` override axis) reaches the
30234        // axis through, without re-walking `:membros` / `:entrada` /
30235        // `:placement` / `:politicas` first. Same self-contained
30236        // posture the peer per-slot gates
30237        // [`AplicacaoSpec::detect_sync_cycles`] and
30238        // [`AplicacaoSpec::validate_entrada`] already carry for the
30239        // same M4 consumers.
30240        let mut spec = three_member_spec();
30241        spec.membros.retain(|m| m.nome() != "catalog");
30242        assert_eq!(
30243            spec.validate_contratos().unwrap_err(),
30244            AplicacaoError::ContratoMemberMissing {
30245                caixa: "catalog".into(),
30246            },
30247            "the per-slot gate must resolve `:de` / `:para` against \
30248             the oracle it builds itself, with no membership set \
30249             threaded in",
30250        );
30251        assert!(
30252            !spec.membro_names().contains("catalog"),
30253            "fixture must have dropped the `:contratos` edge's \
30254             `:para` target from the graph's node set",
30255        );
30256    }
30257
30258    #[test]
30259    fn validate_contratos_folds_cycle_axis_matches_gate() {
30260        // Fold-into-per-slot-gate equivalence pin on the
30261        // cross-edge cycle axis: an [`AplicacaoError::ContratoCycle`]
30262        // surfaces byte-equal through both
30263        // [`AplicacaoSpec::validate_contratos`] and
30264        // [`AplicacaoSpec::validate`] on a fixture whose only defect is
30265        // a synchronous-edge cycle in `:contratos`. Pins the fold that
30266        // moved the cross-edge cycle axis onto the per-slot gate — a
30267        // future silent regression that de-folded the axis back to the
30268        // outer [`AplicacaoSpec::validate`] dispatch (a rebase artifact,
30269        // a peer per-slot gate lift that skipped the cross-axis half of
30270        // the [`MeshPolicy::validate`]-analogous discipline) would
30271        // surface here as `Some(ContratoCycle)` from `validate` and
30272        // `None` from `validate_contratos`.
30273        //
30274        // Cycle fixture is the same shape as the peer
30275        // [`rejects_three_node_synchronous_cycle`] test carries: a
30276        // clean 3-cycle over the HTTP subgraph (catalog → cart →
30277        // payment → catalog), so the per-entry cascade (shape +
30278        // membership + self-loop + `:wit` emptiness + WIT-target +
30279        // whole-edge dedup) passes cleanly and the sole surviving
30280        // refusal shape is the cross-edge cycle axis. The `cycle`
30281        // vector is normalized to a sorted body set for the equality
30282        // compare (the traversal path's starting node depends on
30283        // BTreeMap iteration order, which is deterministic but is not
30284        // the load-bearing property this pin covers).
30285        //
30286        // Peer of the sibling per-slot ≡ `validate` equivalence pins
30287        // [`validate_contratos_matches_gate_on_every_per_axis_shape`]
30288        // (per-entry axes) and
30289        // [`validate_contratos_matches_gate_on_reason_carrying_arms`]
30290        // (parser-owned reason arms) already carry on the six
30291        // per-entry axes — this extends the discipline onto the
30292        // cross-edge cycle axis newly folded into the per-slot gate,
30293        // matching the peer per-slot compound gate
30294        // [`AplicacaoSpec::validate_politicas`] (f03a154) which folded
30295        // both per-axis and cross-axis surfaces on `:politicas`.
30296        let mut spec = three_member_spec();
30297        spec.contratos = vec![
30298            contract_http("catalog", "cart", "/x"),
30299            contract_http("cart", "payment", "/y"),
30300            contract_http("payment", "catalog", "/z"),
30301        ];
30302        let per_slot_err = spec.validate_contratos().unwrap_err();
30303        let gate_err = spec.validate().unwrap_err();
30304        assert_eq!(
30305            per_slot_err, gate_err,
30306            "the per-slot gate and `validate` must return byte-equal \
30307             `AplicacaoError::ContratoCycle` on a cycle-only fixture \
30308             — the fold pins the cross-edge axis onto the per-slot \
30309             gate the same way the peer `validate_politicas` fold \
30310             pinned the `:politicas` cross-axis surface",
30311        );
30312        match per_slot_err {
30313            AplicacaoError::ContratoCycle { ref cycle } => {
30314                assert_eq!(
30315                    cycle.first(),
30316                    cycle.last(),
30317                    "cycle traversal must close on the back-edge \
30318                     target — the diagnostic shape the peer \
30319                     `rejects_three_node_synchronous_cycle` pins",
30320                );
30321                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
30322                assert_eq!(body.len(), 3, "3-cycle must visit 3 distinct nodes");
30323                assert!(body.contains("cart"));
30324                assert!(body.contains("catalog"));
30325                assert!(body.contains("payment"));
30326            }
30327            other => panic!("expected ContratoCycle, got {other:?}"),
30328        }
30329    }
30330
30331    #[test]
30332    fn validate_contratos_per_entry_arm_fires_before_cycle_arm() {
30333        // Diagnostic-ordering pin on the fold: a `:contratos` fixture
30334        // carrying *both* a per-entry defect (a self-loop, the
30335        // structural-self-edge arm on the per-entry cascade — chosen
30336        // because it never masks or is masked by the cycle diagnostic
30337        // on the peer arms) *and* a would-be synchronous-edge cycle in
30338        // the remaining edges must surface the per-entry diagnostic
30339        // first through both [`AplicacaoSpec::validate_contratos`] and
30340        // [`AplicacaoSpec::validate`] — pinning the fold's canonical
30341        // per-entry-before-cross-edge dispatch ordering, byte-equal to
30342        // the pre-fold `validate`-side sequence
30343        // (`validate_contratos()? → detect_sync_cycles()?`) the
30344        // dispatch encoded verbatim. A silent regression that reversed
30345        // the ordering inside the fold would surface here as a cycle
30346        // diagnostic on a fixture carrying an earlier per-entry defect
30347        // — masking the narrower "this edge is degenerate" arm behind
30348        // the coarser "this graph deadlocks" arm.
30349        //
30350        // Peer of the diagnostic-ordering property the pre-fold
30351        // dispatch encoded at the [`AplicacaoSpec::validate`]
30352        // altitude (`validate_contratos()? → detect_sync_cycles()?`),
30353        // now enforced inside the per-slot gate's own body, so a future
30354        // consumer that reaches only the per-slot gate (the M4
30355        // admission webhook re-checking `:contratos` after a per-edge
30356        // patch) inherits the ordering property by construction.
30357        let mut spec = three_member_spec();
30358        // The three-member fixture already has cart → catalog and
30359        // cart → payment; adding catalog → cart closes a 2-cycle on
30360        // the HTTP subgraph.
30361        spec.contratos
30362            .push(contract_http("catalog", "cart", "/refresh"));
30363        // Add a self-loop on `payment` — the per-entry structural-
30364        // self-edge arm — which must surface first.
30365        spec.contratos
30366            .push(contract_http("payment", "payment", "/loop"));
30367        let per_slot_err = spec.validate_contratos().unwrap_err();
30368        let gate_err = spec.validate().unwrap_err();
30369        assert_eq!(
30370            per_slot_err, gate_err,
30371            "per-slot gate and `validate` must agree on the ordering \
30372             fixture's surfaced diagnostic — a divergence here means \
30373             the fold reshaped one dispatch's ordering without the \
30374             other",
30375        );
30376        assert!(
30377            matches!(
30378                per_slot_err,
30379                AplicacaoError::ContratoSelfLoop { ref caixa, .. }
30380                    if caixa == "payment"
30381            ),
30382            "the per-entry structural-self-edge arm must fire before \
30383             the cross-edge cycle arm — pinning the fold's per-entry-\
30384             before-cross-edge dispatch ordering byte-equal to the \
30385             pre-fold `validate_contratos()? → detect_sync_cycles()?` \
30386             sequence; got {per_slot_err:?}",
30387        );
30388    }
30389
30390    #[test]
30391    fn validate_contratos_cycle_axis_is_self_contained_on_slot() {
30392        // Self-containment pin on the folded cross-edge cycle axis:
30393        // [`AplicacaoSpec::validate_contratos`] surfaces
30394        // [`AplicacaoError::ContratoCycle`] directly against `&self`
30395        // without depending on the peer per-slot gates
30396        // ([`AplicacaoSpec::validate_membros`],
30397        // [`AplicacaoSpec::validate_entrada`],
30398        // [`AplicacaoSpec::validate_placement`],
30399        // [`AplicacaoSpec::validate_politicas`]) running first — the
30400        // shape a future single-slot re-validator (the M4 admission
30401        // webhook re-checking `:contratos` after a per-`(:de, :para)`
30402        // edge patch, the per-edge policy resolver MESH-COMPOSITION
30403        // §III.2 #3 acknowledges) reaches *both* structural axes on
30404        // the slot through one call. A spec with a per-`:politicas`
30405        // refusal shape (zero `:timeout`, the first per-axis arm the
30406        // peer [`MeshPolicy::validate`] gate covers) AND a
30407        // synchronous-edge cycle in `:contratos` must:
30408        //
30409        //   - surface [`AplicacaoError::ContratoCycle`] through the
30410        //     per-slot gate `validate_contratos` directly (proves the
30411        //     cycle axis reaches the per-slot altitude without the
30412        //     peer `:politicas` gate running first);
30413        //   - surface [`AplicacaoError::ContratoCycle`] through
30414        //     `validate` (which reaches `validate_contratos` before
30415        //     `validate_politicas` per the fixed dispatch order), so
30416        //     the fold's cross-slot ordering (`:membros` →
30417        //     `:contratos` → `:entrada` → `:placement` → `:politicas`)
30418        //     is byte-equal to the pre-fold dispatch's ordering.
30419        //
30420        // Same self-contained-on-`&self` posture the peer per-slot
30421        // gates [`AplicacaoSpec::validate_entrada`] (20cd523),
30422        // [`AplicacaoSpec::validate_contratos`] per-entry axis
30423        // (906a5c6), and [`AplicacaoSpec::validate_politicas`]
30424        // (f03a154) already carry — extended here onto the newly-
30425        // folded cross-edge cycle axis. Peer of the sibling per-slot
30426        // self-containment pins
30427        // `validate_entrada_resolves_membership_through_own_oracle`
30428        // and `validate_contratos_resolves_membership_through_own_oracle`
30429        // on the per-entry membership axis — extends the discipline
30430        // onto the cross-edge cycle axis of the same per-slot gate.
30431        let mut spec = three_member_spec();
30432        // Poison `:politicas` — zero-`:timeout` trips the first per-
30433        // axis arm the [`MeshPolicy::validate`] gate covers, so any
30434        // dispatch that reached `:politicas` would surface a
30435        // `:politicas` diagnostic instead of `ContratoCycle`.
30436        spec.politicas.timeout = Some(Duration::from_secs(0));
30437        // Close a synchronous-edge cycle on the HTTP subgraph.
30438        spec.contratos
30439            .push(contract_http("catalog", "cart", "/refresh"));
30440        let per_slot_err = spec.validate_contratos().unwrap_err();
30441        assert!(
30442            matches!(per_slot_err, AplicacaoError::ContratoCycle { .. }),
30443            "the per-slot gate must surface `ContratoCycle` directly \
30444             against `&self` — a peer per-slot gate's regression \
30445             would surface a non-`ContratoCycle` diagnostic here; \
30446             got {per_slot_err:?}",
30447        );
30448        let gate_err = spec.validate().unwrap_err();
30449        assert!(
30450            matches!(gate_err, AplicacaoError::ContratoCycle { .. }),
30451            "`validate`'s five-slot dispatch must reach the fold's \
30452             cross-edge cycle axis on `:contratos` before the peer \
30453             `:politicas` gate — a dispatch-order regression would \
30454             surface a `:politicas` diagnostic here; got {gate_err:?}",
30455        );
30456        // Sanity: the poisoned `:politicas` alone would trip
30457        // [`MeshPolicy::validate`] under the peer per-slot gate, so
30458        // the cycle-first surfacing above is a real ordering property,
30459        // not a case where the `:politicas` axis silently accepts the
30460        // fixture.
30461        let mut politicas_only = three_member_spec();
30462        politicas_only.politicas.timeout = Some(Duration::from_secs(0));
30463        assert!(
30464            politicas_only.validate_politicas().is_err(),
30465            "the poisoned `:politicas` fixture must trip the peer \
30466             per-slot gate on its own — otherwise the self-contained \
30467             cycle-first surfacing above would not be an ordering \
30468             property",
30469        );
30470    }
30471
30472    #[test]
30473    fn wit_contract_require_endpoints_in_folds_per_arm_membership_cascade() {
30474        // Fail-before-pass-after equivalence pin on the lifted
30475        // per-edge substrate primitive [`WitContract::require_endpoints_in`]:
30476        // both arms (`:de` phantom and `:para` phantom) must fire the
30477        // `AplicacaoError::ContratoMemberMissing` diagnostic with a
30478        // `caixa` carrier byte-equal to the offending accessor's
30479        // projection, and `:de` must fire before `:para` when both
30480        // arms would trip on the same call — preserving the canonical
30481        // edge-direction order the peer per-arm shape gate
30482        // [`validate_contrato_caixa`], the [`WitContract::is_self_loop`]
30483        // diagnostic, and every peer per-arm ordering in
30484        // [`AplicacaoSpec::validate_contratos`] already carry.
30485        //
30486        // Two-endpoint oracle covers exactly enough graph nodes to
30487        // exercise each arm in isolation: the `:de` arm fires when
30488        // the source is off-oracle and the destination is on-oracle,
30489        // the `:para` arm fires when the source is on-oracle and the
30490        // destination is off-oracle, and the `:de`-before-`:para`
30491        // ordering falls out from a probe where *both* endpoints are
30492        // off-oracle — the diagnostic's `caixa` field must byte-equal
30493        // the source, not the destination, pinning the primitive's
30494        // arm ordering as `:de` first.
30495        let mut names: std::collections::HashSet<&str> = std::collections::HashSet::new();
30496        names.insert("cart");
30497        names.insert("catalog");
30498
30499        // `:de` phantom, `:para` on-oracle
30500        let de_phantom = contract_http("phantom-de", "catalog", "/x");
30501        let err = de_phantom.require_endpoints_in(&names).unwrap_err();
30502        assert_eq!(
30503            err,
30504            AplicacaoError::ContratoMemberMissing {
30505                caixa: de_phantom.source().to_string(),
30506            },
30507            "the `:de` phantom arm must fire ContratoMemberMissing \
30508             with `caixa` byte-equal to `WitContract::source` — a \
30509             bypass here (a raw `.de.clone()` regression, a divergent \
30510             accessor on a per-CR alias table) would silently split \
30511             the primitive's diagnostic from the substrate-primitive \
30512             scalar accessor every downstream consumer routes through",
30513        );
30514
30515        // `:de` on-oracle, `:para` phantom
30516        let para_phantom = contract_http("cart", "phantom-para", "/x");
30517        let err = para_phantom.require_endpoints_in(&names).unwrap_err();
30518        assert_eq!(
30519            err,
30520            AplicacaoError::ContratoMemberMissing {
30521                caixa: para_phantom.destination().to_string(),
30522            },
30523            "the `:para` phantom arm must fire ContratoMemberMissing \
30524             with `caixa` byte-equal to `WitContract::destination` — \
30525             symmetric callee-side pin to the `:de` arm above",
30526        );
30527
30528        // Both endpoints off-oracle: the `:de` arm must fire first,
30529        // pinning the primitive's canonical edge-direction order.
30530        let both_phantom = contract_http("phantom-de", "phantom-para", "/x");
30531        let err = both_phantom.require_endpoints_in(&names).unwrap_err();
30532        assert_eq!(
30533            err,
30534            AplicacaoError::ContratoMemberMissing {
30535                caixa: both_phantom.source().to_string(),
30536            },
30537            "when both endpoints are off-oracle, the `:de` arm must \
30538             fire before the `:para` arm — preserving byte-equal \
30539             ordering with the pre-lift inline cascade in \
30540             `validate_contratos` and with every peer per-arm \
30541             ordering the sibling per-edge substrate primitives \
30542             already carry",
30543        );
30544
30545        // Both endpoints on-oracle: clean pass.
30546        let clean = contract_http("cart", "catalog", "/x");
30547        clean.require_endpoints_in(&names).unwrap();
30548    }
30549
30550    #[test]
30551    fn validate_contratos_membership_gate_routes_through_require_endpoints_in() {
30552        // Convergence pin: the whole-spec end-to-end route through
30553        // [`AplicacaoSpec::validate_contratos`] must reach the
30554        // per-edge substrate primitive
30555        // [`WitContract::require_endpoints_in`] on every membership
30556        // arm — the diagnostic fired at the per-slot altitude must
30557        // byte-equal the diagnostic the primitive fires when called
30558        // directly on the same edge and the same oracle. Pins the
30559        // primitive as the sole load-bearing gate on the membership
30560        // axis, so any future silent detour that re-inlined the twin
30561        // `if !names.contains(...)` cascade back into the per-slot
30562        // gate (a rebase-artifact regression, an M4 admission-webhook
30563        // consumer that bypassed the primitive) would surface here as
30564        // a byte-equal miss between the two dispatches.
30565        //
30566        // Same equivalence-pin discipline the peer
30567        // [`validate_contratos_matches_gate_on_every_per_axis_shape`]
30568        // pin already carries on the per-slot gate ≡ `validate` axis,
30569        // extended here onto the per-slot gate ≡ per-edge primitive
30570        // axis at one altitude deeper.
30571        for phantom_edge in [
30572            contract_http("phantom-de", "catalog", "/x"),
30573            contract_http("cart", "phantom-para", "/x"),
30574        ] {
30575            let mut spec = three_member_spec();
30576            spec.contratos.push(phantom_edge.clone());
30577            let per_slot_err = spec.validate_contratos().unwrap_err();
30578            let primitive_err = phantom_edge
30579                .require_endpoints_in(&spec.membro_names())
30580                .unwrap_err();
30581            assert_eq!(
30582                per_slot_err, primitive_err,
30583                "the per-slot gate must reach the per-edge substrate \
30584                 primitive on every membership arm — a bypass here \
30585                 would silently split the two dispatches on the \
30586                 same edge + same oracle input",
30587            );
30588            // And the diagnostic's `caixa` carrier must byte-equal
30589            // the offending accessor's projection at both altitudes,
30590            // pinning the accessor routing across the whole-spec
30591            // path.
30592            let AplicacaoError::ContratoMemberMissing { ref caixa } = per_slot_err else {
30593                panic!("expected ContratoMemberMissing, got {per_slot_err:?}");
30594            };
30595            let expected = if spec.membro_names().contains(phantom_edge.source()) {
30596                phantom_edge.destination()
30597            } else {
30598                phantom_edge.source()
30599            };
30600            assert_eq!(
30601                caixa, expected,
30602                "the whole-spec ContratoMemberMissing.caixa carrier \
30603                 must byte-equal the offending edge's accessor \
30604                 projection — a bypass here would silently split \
30605                 the wrap envelope's `caixa` field from the \
30606                 substrate-primitive scalar accessor every \
30607                 downstream consumer routes through",
30608            );
30609        }
30610    }
30611
30612    #[test]
30613    fn port_for_destination_reads_through_lifted_entrada_accessor() {
30614        // Peer coherence pin: the
30615        // [`AplicacaoSpec::port_for_destination`] per-destination
30616        // L4-port fallback resolver's composite-projection seed
30617        // (`self.entrada().filter(…).map_or(…)`) must key off the
30618        // lifted outer accessor. Pins the coherence by exercising
30619        // the resolver end-to-end: (1) the `None` `:entrada` shape
30620        // falls through to `DEFAULT_SERVICO_PORT` under the outer
30621        // accessor's reference projection, (2) a non-matching
30622        // destination falls through to `DEFAULT_SERVICO_PORT` under
30623        // the outer accessor's reference projection, and (3) the
30624        // matching destination resolves to the `:entrada :port`
30625        // value under the outer accessor's reference projection.
30626        //
30627        // Peer of the sibling
30628        // [`validate_reads_through_lifted_entrada_accessor`] multi-
30629        // consumer coherence pin on the same per-`:entrada` outer-
30630        // composite axis — extends the multi-consumer coherence
30631        // discipline onto the second per-`:entrada` production
30632        // consumer, the L4-port fallback resolver.
30633
30634        // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
30635        // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
30636        // arm under the outer accessor's reference projection.
30637        let mut spec = three_member_spec();
30638        spec.entrada = None;
30639        assert_eq!(
30640            spec.port_for_destination("cart"),
30641            DEFAULT_SERVICO_PORT,
30642            "the port-fallback resolver must fall through to \
30643             DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
30644             under the outer accessor's reference projection",
30645        );
30646
30647        // (2) Non-matching destination — the resolver's `filter(…)`
30648        // arm rejects a mismatched destination and falls through
30649        // to `DEFAULT_SERVICO_PORT` under the outer accessor's
30650        // reference projection.
30651        let mut spec = three_member_spec();
30652        if let Some(e) = spec.entrada.as_mut() {
30653            e.para = "cart".into();
30654            e.port = 9443;
30655        }
30656        assert_eq!(
30657            spec.port_for_destination("catalog"),
30658            DEFAULT_SERVICO_PORT,
30659            "the port-fallback resolver must fall through to \
30660             DEFAULT_SERVICO_PORT on a non-matching destination \
30661             under the outer accessor's reference projection",
30662        );
30663
30664        // (3) Matching destination — the resolver's `map_or(…)` arm
30665        // returns the `:entrada :port` value under the outer
30666        // accessor's reference projection.
30667        let mut spec = three_member_spec();
30668        if let Some(e) = spec.entrada.as_mut() {
30669            e.para = "cart".into();
30670            e.port = 9443;
30671        }
30672        assert_eq!(
30673            spec.port_for_destination("cart"),
30674            9443,
30675            "the port-fallback resolver must return the \
30676             `:entrada :port` value on a matching destination \
30677             under the outer accessor's reference projection",
30678        );
30679    }
30680
30681    #[test]
30682    fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
30683        // The canonical per-`:politicas` `:mtls-required` mTLS-
30684        // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
30685        // must return the `:politicas :mtls-required` typed bool
30686        // verbatim as an `Option<bool>`, byte-equal to the raw field
30687        // access across every value in the three-way accept-set —
30688        // `None` (cluster default applies), `Some(true)` (mTLS
30689        // handshake enforced — the sandboxing-by-default arm the
30690        // MeshPolicy's docstring names), `Some(false)` (handshake
30691        // skipped — the explicit debug-edge opt-out).
30692        //
30693        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
30694        // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
30695        // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
30696        // shape — first `Option<Copy-T>`-return accessor on the M3
30697        // mesh-slot family. Pins against a future silent detour that
30698        // re-derived the toggle from a peer axis (an accidental
30699        // `.circuit_breaker.is_some()` collapse that assumed mTLS on
30700        // whenever a breaker is set), a `None` → `Some(false)` cluster-
30701        // default projection (the canonical `Option<bool>` → `bool`
30702        // collapse footgun the surrounding `is_empty()` predicate
30703        // guards on the peer emptiness axis), or a `Some(true)` /
30704        // `Some(false)` variant swap that landed on one consumer
30705        // without the other.
30706        for required in [None, Some(true), Some(false)] {
30707            let p = MeshPolicy {
30708                mtls_required: required,
30709                ..MeshPolicy::default()
30710            };
30711            assert_eq!(
30712                p.mtls_required(),
30713                required,
30714                "MeshPolicy::mtls_required must return :politicas \
30715                 :mtls-required verbatim (got {:?}, expected {required:?})",
30716                p.mtls_required(),
30717            );
30718            assert_eq!(
30719                p.mtls_required(),
30720                p.mtls_required,
30721                "MeshPolicy::mtls_required must byte-equal the raw \
30722                 .mtls_required field access across every value in the \
30723                 three-way accept-set",
30724            );
30725        }
30726    }
30727
30728    #[test]
30729    fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
30730        // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
30731        // arm must key off [`MeshPolicy::mtls_required`], not the raw
30732        // `.mtls_required` field access. Structurally: toggling ONLY
30733        // the `mtls_required` slot on an otherwise-default MeshPolicy
30734        // must flip `is_empty()` from `true` (all-`None`) to `false`
30735        // (one axis carries a value); the flip must be observed for
30736        // both `Some(true)` and `Some(false)` since the emptiness
30737        // semantic reads "any axis carries a value" — not "any axis
30738        // carries a truthy value" — the same non-collapsing shape the
30739        // sibling M2 [`crate::LimitsSpec::is_empty`] /
30740        // [`crate::BehaviorSpec::is_empty`] predicates carry on their
30741        // peer `Option<T>`-typed slot surfaces.
30742        //
30743        // Pins against a future silent detour that re-derived the
30744        // emptiness predicate off a peer axis (an accidental
30745        // `.rate_limit.is_none()`-only chain that dropped the
30746        // `mtls_required` arm entirely), a `mtls_required == Some(_)`
30747        // collapse to a truthy-only check (which would silently
30748        // classify `Some(false)` as empty), or an accessor-side
30749        // detour that no longer names the substrate-primitive typed
30750        // dispatch (an accidental `self.mtls_required.unwrap_or(false)
30751        // == false` fallback in the accessor that would silently
30752        // classify both `None` and `Some(false)` as the same value).
30753        //
30754        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
30755        // (7cd2a28) accessor-composition pin on the sibling optional-
30756        // scalar axis — same "the emptiness / shape-gate predicate
30757        // must route through the substrate-primitive typed dispatch"
30758        // discipline extended onto the peer per-`:politicas` emptiness
30759        // predicate.
30760        let empty = MeshPolicy::default();
30761        assert!(
30762            empty.is_empty(),
30763            "MeshPolicy::default() must be is_empty() — every axis \
30764             defaults to None",
30765        );
30766        for required in [Some(true), Some(false)] {
30767            let p = MeshPolicy {
30768                mtls_required: required,
30769                ..MeshPolicy::default()
30770            };
30771            assert!(
30772                !p.is_empty(),
30773                "MeshPolicy::is_empty must return false when \
30774                 :mtls-required is {required:?} — the emptiness \
30775                 predicate reads \"any axis carries a value\", not \
30776                 \"any axis carries a truthy value\"",
30777            );
30778            assert_eq!(
30779                p.mtls_required().is_none(),
30780                p.is_empty(),
30781                "when :mtls-required is the only set axis, \
30782                 is_empty() must equal mtls_required().is_none() — \
30783                 the accessor and the emptiness predicate must \
30784                 route through the same substrate-primitive typed \
30785                 dispatch on the :mtls-required arm",
30786            );
30787        }
30788    }
30789
30790    #[test]
30791    fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
30792        // The by-copy pin: [`MeshPolicy::mtls_required`] returns
30793        // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
30794        // accessor must return by value, not by reference. Peer of the
30795        // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
30796        // borrow-invariant pin on the sibling `Option<String>` slot,
30797        // but extended onto the peer `Option<bool>` copy-invariant
30798        // shape — the accessor's returned `Option<bool>` must outlive
30799        // `&self` (multiple calls must return equal values from a
30800        // dropped-`&self` copy, since the returned Option carries no
30801        // borrow), and calling the accessor twice on the same
30802        // MeshPolicy must yield the same `Option<bool>` verbatim
30803        // (idempotent, no side effects on `&self`).
30804        //
30805        // Pins against a future silent detour that returned
30806        // `Option<&bool>` (which would type-check but silently break
30807        // every downstream caller — [`single_field_overlay`]'s first
30808        // parameter is `Option<T: Clone>`, and `&bool` would fold to a
30809        // detached copy at the call site), an accidental
30810        // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
30811        // would also type-check but return `Option<&bool>`), or a
30812        // one-arm-only accessor that reads `Some(*b)` in the Some arm
30813        // but reads a fresh Default::default() in the None arm.
30814        for required in [None, Some(true), Some(false)] {
30815            let p = MeshPolicy {
30816                mtls_required: required,
30817                ..MeshPolicy::default()
30818            };
30819            let first = p.mtls_required();
30820            let second = p.mtls_required();
30821            assert_eq!(
30822                first, second,
30823                "MeshPolicy::mtls_required must be idempotent — two \
30824                 successive calls on the same &self must return the \
30825                 same Option<bool>",
30826            );
30827            assert_eq!(
30828                first, required,
30829                "MeshPolicy::mtls_required must return :politicas \
30830                 :mtls-required verbatim by copy — got {first:?}, \
30831                 expected {required:?}",
30832            );
30833        }
30834    }
30835
30836    #[test]
30837    fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
30838        // The canonical per-`:politicas` `:retries` transient-failure-
30839        // retry-budget scalar pin: [`MeshPolicy::retries`] must return
30840        // the `:politicas :retries` typed `u32` verbatim as an
30841        // `Option<u32>`, byte-equal to the raw field access across every
30842        // representative value in the accept-set — `None` (cluster
30843        // default applies — typically "no retries beyond a single
30844        // dispatch attempt" the caixa-mesh `retry_overlay` builder
30845        // documents), `Some(1)` (the lower boundary of the
30846        // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
30847        // `AplicacaoSpec::validate_politicas` gate carves out on the
30848        // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
30849        // (the upper boundary the same gate carves out on the sibling
30850        // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
30851        // past-the-guard sentinel that pins the accessor doesn't perform
30852        // a silent bounds-collapse at the return path).
30853        //
30854        // Sibling of the peer per-`:politicas`
30855        // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
30856        // sibling `Option<Copy-T>` optional-scalar axis, extended to the
30857        // peer per-`:politicas` `Option<u32>` shape — second
30858        // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
30859        // Pins against a future silent detour that re-derived the retry
30860        // cap from a peer axis (an accidental `.circuit_breaker
30861        // .as_ref().map(|b| b.max_failures)` collapse that read the
30862        // breaker's max-failure count as a retry budget), a
30863        // `None → Some(0)` cluster-default projection (which would
30864        // silently re-introduce the `PolicyRetriesZero` refusal case at
30865        // the emit boundary), or a bounds-collapsing accessor that
30866        // clamped the return through `POLICY_RETRIES_MAX` (the
30867        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
30868        // must ship the raw slot verbatim so a validate-time gate
30869        // regression surfaces at the emit boundary rather than being
30870        // silently absorbed).
30871        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
30872            let p = MeshPolicy {
30873                retries,
30874                ..MeshPolicy::default()
30875            };
30876            assert_eq!(
30877                p.retries(),
30878                retries,
30879                "MeshPolicy::retries must return :politicas :retries \
30880                 verbatim (got {:?}, expected {retries:?})",
30881                p.retries(),
30882            );
30883            assert_eq!(
30884                p.retries(),
30885                p.retries,
30886                "MeshPolicy::retries must byte-equal the raw .retries \
30887                 field access across every value in the accept-set",
30888            );
30889        }
30890    }
30891
30892    #[test]
30893    fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
30894        // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
30895        // must key off [`MeshPolicy::retries`], not the raw `.retries`
30896        // field access. Structurally: toggling ONLY the `retries` slot
30897        // on an otherwise-default MeshPolicy must flip `is_empty()`
30898        // from `true` (all-`None`) to `false` (one axis carries a
30899        // value); the flip must be observed for every value in the
30900        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
30901        // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
30902        // the emptiness semantic reads "any axis carries a value" —
30903        // not "any axis carries a value the validate gate accepts" —
30904        // the same non-collapsing shape the peer M2
30905        // [`crate::LimitsSpec::is_empty`] /
30906        // [`crate::BehaviorSpec::is_empty`] predicates carry.
30907        //
30908        // Pins against a future silent detour that re-derived the
30909        // emptiness predicate off a peer axis (an accidental
30910        // `.rate_limit.is_none()`-only chain that dropped the
30911        // `retries` arm entirely), a `retries == Some(_)` collapse
30912        // that key-off a validate-gate-clamped bounds check (which
30913        // would silently classify a past-the-guard `Some(u32::MAX)`
30914        // as empty because it fails the `1..=POLICY_RETRIES_MAX`
30915        // check), or an accessor-side detour that no longer names the
30916        // substrate-primitive typed dispatch.
30917        //
30918        // Sibling of the peer per-`:politicas`
30919        // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
30920        // pin on the sibling `Option<Copy-T>` optional-scalar axis —
30921        // same "the emptiness predicate must route through the
30922        // substrate-primitive typed dispatch" discipline extended onto
30923        // the peer per-`:politicas` `Option<u32>` axis.
30924        let empty = MeshPolicy::default();
30925        assert!(
30926            empty.is_empty(),
30927            "MeshPolicy::default() must be is_empty() — every axis \
30928             defaults to None",
30929        );
30930        for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
30931            let p = MeshPolicy {
30932                retries,
30933                ..MeshPolicy::default()
30934            };
30935            assert!(
30936                !p.is_empty(),
30937                "MeshPolicy::is_empty must return false when \
30938                 :retries is {retries:?} — the emptiness \
30939                 predicate reads \"any axis carries a value\", not \
30940                 \"any axis carries a value the validate gate \
30941                 accepts\"",
30942            );
30943            assert_eq!(
30944                p.retries().is_none(),
30945                p.is_empty(),
30946                "when :retries is the only set axis, is_empty() \
30947                 must equal retries().is_none() — the accessor and \
30948                 the emptiness predicate must route through the same \
30949                 substrate-primitive typed dispatch on the :retries \
30950                 arm",
30951            );
30952        }
30953    }
30954
30955    #[test]
30956    fn mesh_policy_retries_projects_option_u32_by_copy() {
30957        // The by-copy pin: [`MeshPolicy::retries`] returns
30958        // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
30959        // accessor must return by value, not by reference. Sibling of
30960        // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
30961        // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
30962        // extended onto the sibling `Option<u32>` copy-invariant
30963        // shape — the accessor's returned `Option<u32>` must outlive
30964        // `&self` (multiple calls must return equal values from a
30965        // dropped-`&self` copy, since the returned Option carries no
30966        // borrow), and calling the accessor twice on the same
30967        // MeshPolicy must yield the same `Option<u32>` verbatim
30968        // (idempotent, no side effects on `&self`).
30969        //
30970        // Pins against a future silent detour that returned
30971        // `Option<&u32>` (which would type-check but silently break
30972        // every downstream caller — [`crate::render::single_field_overlay`]'s
30973        // first parameter is `Option<T: Clone>`, and `&u32` would
30974        // fold to a detached copy at the call site), an accidental
30975        // `Option::as_ref()` projection (`self.retries.as_ref()` would
30976        // also type-check but return `Option<&u32>`), or a one-arm-
30977        // only accessor that reads `Some(*n)` in the Some arm but
30978        // reads a fresh `Default::default()` (`0_u32`) in the None
30979        // arm.
30980        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
30981            let p = MeshPolicy {
30982                retries,
30983                ..MeshPolicy::default()
30984            };
30985            let first = p.retries();
30986            let second = p.retries();
30987            assert_eq!(
30988                first, second,
30989                "MeshPolicy::retries must be idempotent — two \
30990                 successive calls on the same &self must return the \
30991                 same Option<u32>",
30992            );
30993            assert_eq!(
30994                first, retries,
30995                "MeshPolicy::retries must return :politicas :retries \
30996                 verbatim by copy — got {first:?}, expected {retries:?}",
30997            );
30998        }
30999    }
31000
31001    #[test]
31002    fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
31003        // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
31004        // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
31005        // return the `:politicas :timeout` typed [`Duration`] verbatim
31006        // as an `Option<Duration>`, byte-equal to the raw field access
31007        // across every representative value in the accept-set — `None`
31008        // (cluster default applies — typically the gateway class's
31009        // implementation-side per-request wall-clock cap the caixa-mesh
31010        // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
31011        // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
31012        // set the surrounding `AplicacaoSpec::validate_politicas` gate
31013        // carves out on the sibling `PolicyTimeoutZero` /
31014        // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
31015        // (the upper boundary the same gate carves out on the sibling
31016        // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
31017        // (a past-the-guard sentinel that pins the accessor doesn't
31018        // perform a silent bounds-collapse into `None` on the zero-
31019        // Duration arm — validate rejects zero but the accessor must
31020        // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
31021        // past-the-guard sentinel that pins the accessor doesn't
31022        // perform a silent bounds-collapse at the return path).
31023        //
31024        // Sibling of the peer per-`:politicas`
31025        // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
31026        // `Option<u32>` optional-scalar axis and the peer per-
31027        // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
31028        // pin on the sibling `Option<bool>` optional-scalar axis,
31029        // extended onto the peer per-`:politicas` `Option<Duration>`
31030        // shape — third `Option<Copy-T>`-return accessor on the M3
31031        // mesh-slot family. Pins against a future silent detour that
31032        // re-derived the per-call cap from a peer axis (an accidental
31033        // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
31034        // read the breaker's rolling-window duration as a per-call
31035        // deadline), a `None → Some(Duration::MAX)` cluster-default
31036        // projection (which would silently re-introduce the
31037        // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
31038        // blocking" arm at the emit boundary), or a bounds-collapsing
31039        // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
31040        // (the `AplicacaoSpec::validate` gate owns the bounds; the
31041        // accessor must ship the raw slot verbatim so a validate-time
31042        // gate regression surfaces at the emit boundary rather than
31043        // being silently absorbed).
31044        for timeout in [
31045            None,
31046            Some(Duration::from_millis(1)),
31047            Some(POLICY_TIMEOUT_MAX),
31048            Some(Duration::ZERO),
31049            Some(Duration::MAX),
31050        ] {
31051            let p = MeshPolicy {
31052                timeout,
31053                ..MeshPolicy::default()
31054            };
31055            assert_eq!(
31056                p.timeout(),
31057                timeout,
31058                "MeshPolicy::timeout must return :politicas :timeout \
31059                 verbatim (got {:?}, expected {timeout:?})",
31060                p.timeout(),
31061            );
31062            assert_eq!(
31063                p.timeout(),
31064                p.timeout,
31065                "MeshPolicy::timeout must byte-equal the raw .timeout \
31066                 field access across every value in the accept-set",
31067            );
31068        }
31069    }
31070
31071    #[test]
31072    fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
31073        // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
31074        // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
31075        // field access. Structurally: toggling ONLY the `timeout` slot
31076        // on an otherwise-default MeshPolicy must flip `is_empty()`
31077        // from `true` (all-`None`) to `false` (one axis carries a
31078        // value); the flip must be observed for every value in the
31079        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
31080        // gate accepts (`Some(Duration::from_millis(1))`,
31081        // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
31082        // reads "any axis carries a value" — not "any axis carries a
31083        // value the validate gate accepts" — the same non-collapsing
31084        // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
31085        // [`crate::BehaviorSpec::is_empty`] predicates carry.
31086        //
31087        // Pins against a future silent detour that re-derived the
31088        // emptiness predicate off a peer axis (an accidental
31089        // `.rate_limit.is_none()`-only chain that dropped the
31090        // `timeout` arm entirely), a `timeout == Some(_)` collapse
31091        // that key-off a validate-gate-clamped bounds check (which
31092        // would silently classify a past-the-guard `Some(Duration::MAX)`
31093        // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
31094        // check), or an accessor-side detour that no longer names the
31095        // substrate-primitive typed dispatch.
31096        //
31097        // Sibling of the peer per-`:politicas`
31098        // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
31099        // the sibling `Option<u32>` optional-scalar axis and the peer
31100        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
31101        // accessor-composition pin on the sibling `Option<bool>`
31102        // optional-scalar axis — same "the emptiness predicate must
31103        // route through the substrate-primitive typed dispatch"
31104        // discipline extended onto the peer per-`:politicas`
31105        // `Option<Duration>` axis.
31106        let empty = MeshPolicy::default();
31107        assert!(
31108            empty.is_empty(),
31109            "MeshPolicy::default() must be is_empty() — every axis \
31110             defaults to None",
31111        );
31112        for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
31113            let p = MeshPolicy {
31114                timeout,
31115                ..MeshPolicy::default()
31116            };
31117            assert!(
31118                !p.is_empty(),
31119                "MeshPolicy::is_empty must return false when \
31120                 :timeout is {timeout:?} — the emptiness \
31121                 predicate reads \"any axis carries a value\", not \
31122                 \"any axis carries a value the validate gate \
31123                 accepts\"",
31124            );
31125            assert_eq!(
31126                p.timeout().is_none(),
31127                p.is_empty(),
31128                "when :timeout is the only set axis, is_empty() \
31129                 must equal timeout().is_none() — the accessor and \
31130                 the emptiness predicate must route through the same \
31131                 substrate-primitive typed dispatch on the :timeout \
31132                 arm",
31133            );
31134        }
31135    }
31136
31137    #[test]
31138    fn mesh_policy_timeout_projects_option_duration_by_copy() {
31139        // The by-copy pin: [`MeshPolicy::timeout`] returns
31140        // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
31141        // and the accessor must return by value, not by reference.
31142        // Sibling of the peer per-`:politicas`
31143        // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
31144        // sibling `Option<u32>` optional-scalar axis and the peer
31145        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
31146        // by-copy pin on the sibling `Option<bool>` optional-scalar
31147        // axis, extended onto the peer per-`:politicas`
31148        // `Option<Duration>` copy-invariant shape — the accessor's
31149        // returned `Option<Duration>` must outlive `&self` (multiple
31150        // calls must return equal values from a dropped-`&self`
31151        // copy, since the returned Option carries no borrow), and
31152        // calling the accessor twice on the same MeshPolicy must
31153        // yield the same `Option<Duration>` verbatim (idempotent, no
31154        // side effects on `&self`).
31155        //
31156        // Pins against a future silent detour that returned
31157        // `Option<&Duration>` (which would type-check but silently
31158        // break every downstream caller — [`crate::render::single_field_overlay`]'s
31159        // first parameter is `Option<T: Clone>`, and `&Duration`
31160        // would fold to a detached copy at the call site), an
31161        // accidental `Option::as_ref()` projection
31162        // (`self.timeout.as_ref()` would also type-check but return
31163        // `Option<&Duration>`), or a one-arm-only accessor that
31164        // reads `Some(*d)` in the Some arm but reads a fresh
31165        // `Default::default()` (`Duration::ZERO`) in the None arm
31166        // (which would silently re-classify every unset `:timeout`
31167        // as the `PolicyTimeoutZero`-refused zero-Duration value at
31168        // the accessor boundary).
31169        for timeout in [
31170            None,
31171            Some(Duration::from_millis(1)),
31172            Some(POLICY_TIMEOUT_MAX),
31173            Some(Duration::ZERO),
31174            Some(Duration::MAX),
31175        ] {
31176            let p = MeshPolicy {
31177                timeout,
31178                ..MeshPolicy::default()
31179            };
31180            let first = p.timeout();
31181            let second = p.timeout();
31182            assert_eq!(
31183                first, second,
31184                "MeshPolicy::timeout must be idempotent — two \
31185                 successive calls on the same &self must return the \
31186                 same Option<Duration>",
31187            );
31188            assert_eq!(
31189                first, timeout,
31190                "MeshPolicy::timeout must return :politicas :timeout \
31191                 verbatim by copy — got {first:?}, expected {timeout:?}",
31192            );
31193        }
31194    }
31195
31196    #[test]
31197    fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
31198        // The canonical per-`:politicas` `:rate-limit` Envoy-
31199        // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
31200        // [`MeshPolicy::rate_limit`] must return the `:politicas
31201        // :rate-limit` typed [`RateLimit`] verbatim as an
31202        // `Option<RateLimit>`, byte-equal to the raw field access
31203        // across every representative value in the accept-set — `None`
31204        // (cluster default applies — no per-Aplicacao rate declaration,
31205        // the gateway-class per-listener default arm the future caixa-
31206        // mesh `local_rate_limit_overlay` emitter documents),
31207        // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
31208        // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
31209        // accept-set the surrounding
31210        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
31211        // sibling `PolicyRateLimitZero` refusal, paired with the
31212        // canonical-window "1 second" arm of the three-unit
31213        // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
31214        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
31215        // (the upper boundary the same gate carves out on the sibling
31216        // `PolicyRateLimitExceedsCap` refusal, paired with the
31217        // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
31218        // (a past-the-guard sentinel that pins the accessor doesn't
31219        // perform a silent bounds-collapse into `None` on the
31220        // zero-rate/zero-window arm — validate rejects zero but the
31221        // accessor must ship the raw slot verbatim so a validate-time
31222        // gate regression surfaces at the emit boundary rather than
31223        // being silently absorbed), and
31224        // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
31225        // (a past-the-guard sentinel that pins the accessor doesn't
31226        // perform a silent bounds-collapse at the return path).
31227        //
31228        // First `Option<Copy-composite-T>`-return accessor pin on the
31229        // M3 mesh-slot family (peer of the sibling per-`:politicas`
31230        // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
31231        // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
31232        // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
31233        // Copy accessor pins, extended onto the peer per-`:politicas`
31234        // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
31235        // and the accessor returns by value). Pins against a future
31236        // silent detour that re-derived the rate declaration from a
31237        // peer axis (an accidental
31238        // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
31239        // collapse that read the breaker's trip threshold + rolling
31240        // window as a rate declaration), a `None → Some(default())`
31241        // cluster-default projection (which would silently re-
31242        // introduce a "cluster default is 0/s" arm the emit boundary
31243        // would take as "declared but inert" — the canonical
31244        // declared-but-inert footgun the sibling
31245        // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
31246        // amplification-shape axis), a bounds-collapsing accessor
31247        // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
31248        // clamped `rl.window` through [`is_canonical_rate_limit_window`]
31249        // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
31250        // accessor must ship the raw slot verbatim), or a
31251        // by-reference detour (`Option<&RateLimit>`) that broke every
31252        // downstream consumer keying off `Option<RateLimit>` by-copy.
31253        for rl in [
31254            None,
31255            Some(RateLimit {
31256                rate: 1,
31257                window: Duration::from_secs(1),
31258            }),
31259            Some(RateLimit {
31260                rate: POLICY_RATE_LIMIT_MAX,
31261                window: Duration::from_secs(3600),
31262            }),
31263            Some(RateLimit {
31264                rate: 0,
31265                window: Duration::ZERO,
31266            }),
31267            Some(RateLimit {
31268                rate: u32::MAX,
31269                window: Duration::MAX,
31270            }),
31271        ] {
31272            let p = MeshPolicy {
31273                rate_limit: rl,
31274                ..MeshPolicy::default()
31275            };
31276            assert_eq!(
31277                p.rate_limit(),
31278                rl,
31279                "MeshPolicy::rate_limit must return :politicas :rate-limit \
31280                 verbatim (got {:?}, expected {rl:?})",
31281                p.rate_limit(),
31282            );
31283            assert_eq!(
31284                p.rate_limit(),
31285                p.rate_limit,
31286                "MeshPolicy::rate_limit must byte-equal the raw \
31287                 .rate_limit field access across every value in the \
31288                 accept-set",
31289            );
31290        }
31291    }
31292
31293    #[test]
31294    fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
31295        // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
31296        // must key off [`MeshPolicy::rate_limit`], not the raw
31297        // `.rate_limit` field access. Structurally: toggling ONLY the
31298        // `rate_limit` slot on an otherwise-default MeshPolicy must
31299        // flip `is_empty()` from `true` (all-`None`) to `false` (one
31300        // axis carries a value); the flip must be observed for every
31301        // representative value in the accept-set the surrounding
31302        // [`AplicacaoSpec::validate_politicas`] gate accepts
31303        // (`Some(RateLimit { rate: 1, window: 1s })`,
31304        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
31305        // since the emptiness semantic reads "any axis carries a
31306        // value" — not "any axis carries a value the validate gate
31307        // accepts" — the same non-collapsing shape the peer M2
31308        // [`crate::LimitsSpec::is_empty`] /
31309        // [`crate::BehaviorSpec::is_empty`] predicates carry.
31310        //
31311        // Pins against a future silent detour that re-derived the
31312        // emptiness predicate off a peer axis (an accidental
31313        // `.timeout.is_none()`-only chain that dropped the
31314        // `rate_limit` arm entirely — the last unlifted inline field
31315        // access on `is_empty` before this lift), a `rate_limit ==
31316        // Some(_)` collapse that key-off a validate-gate-clamped
31317        // bounds check (which would silently classify a past-the-
31318        // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
31319        // because it fails the value-shape gate), or an accessor-
31320        // side detour that no longer names the substrate-primitive
31321        // typed dispatch.
31322        //
31323        // Fourth "the emptiness predicate must route through the
31324        // substrate-primitive typed dispatch" composition pin on the
31325        // M3 mesh-slot family — closes the last unlifted composition
31326        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
31327        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
31328        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
31329        // 7073d0f is_empty-composition pins on the sibling primitive-
31330        // Copy axes, extended onto the peer per-`:politicas`
31331        // composite-Copy `Option<RateLimit>` axis).
31332        let empty = MeshPolicy::default();
31333        assert!(
31334            empty.is_empty(),
31335            "MeshPolicy::default() must be is_empty() — every axis \
31336             defaults to None",
31337        );
31338        for rl in [
31339            RateLimit {
31340                rate: 1,
31341                window: Duration::from_secs(1),
31342            },
31343            RateLimit {
31344                rate: POLICY_RATE_LIMIT_MAX,
31345                window: Duration::from_secs(3600),
31346            },
31347        ] {
31348            let p = MeshPolicy {
31349                rate_limit: Some(rl),
31350                ..MeshPolicy::default()
31351            };
31352            assert!(
31353                !p.is_empty(),
31354                "MeshPolicy::is_empty must return false when \
31355                 :rate-limit is {rl:?} — the emptiness predicate \
31356                 reads \"any axis carries a value\", not \"any axis \
31357                 carries a value the validate gate accepts\"",
31358            );
31359            assert_eq!(
31360                p.rate_limit().is_none(),
31361                p.is_empty(),
31362                "when :rate-limit is the only set axis, is_empty() \
31363                 must equal rate_limit().is_none() — the accessor \
31364                 and the emptiness predicate must route through the \
31365                 same substrate-primitive typed dispatch on the \
31366                 :rate-limit arm",
31367            );
31368        }
31369    }
31370
31371    #[test]
31372    fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
31373        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
31374        // `:rate-limit` value-shape gate must key off
31375        // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
31376        // field bind. Structurally: a `MeshPolicy` whose only set
31377        // axis is a `Some(RateLimit { rate: 0, .. })` must surface
31378        // the `PolicyRateLimitZero` refusal exactly, and the same
31379        // MeshPolicy with the rate at the canonical lower boundary
31380        // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
31381        // The pair jointly pins the accessor + validate-gate
31382        // composition: any future silent detour that had the accessor
31383        // omit the `Some(RateLimit { rate: 0, .. })` arm (a
31384        // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
31385        // silently absorb the `PolicyRateLimitZero` refusal at the
31386        // accessor boundary — the composition pin catches that at
31387        // caixa-core build time.
31388        //
31389        // Sibling of the peer [`validate_politicas`]
31390        // `:mtls-required` / `:retries` / `:timeout` composition pins
31391        // on the sibling primitive-Copy optional-scalar axes — same
31392        // "the validate / shape-gate predicate must route through the
31393        // substrate-primitive typed dispatch" discipline extended
31394        // onto the peer per-`:politicas` composite-Copy
31395        // `Option<RateLimit>` axis. Second composition-with-accessor
31396        // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
31397        // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
31398        let mut spec = three_member_spec();
31399        spec.politicas = MeshPolicy {
31400            rate_limit: Some(RateLimit {
31401                rate: 0,
31402                window: Duration::from_secs(1),
31403            }),
31404            ..MeshPolicy::default()
31405        };
31406        assert!(
31407            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
31408            "validate_politicas must reject rate == 0 with \
31409             PolicyRateLimitZero — the accessor and the validate gate \
31410             must route through the same substrate-primitive typed \
31411             dispatch on the :rate-limit zero-floor arm",
31412        );
31413        spec.politicas = MeshPolicy {
31414            rate_limit: Some(RateLimit {
31415                rate: 1,
31416                window: Duration::from_secs(1),
31417            }),
31418            ..MeshPolicy::default()
31419        };
31420        assert!(
31421            spec.validate().is_ok(),
31422            "validate_politicas must accept rate == 1 (the canonical \
31423             lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
31424             set) with a canonical 1s window",
31425        );
31426    }
31427
31428    #[test]
31429    fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
31430        // The canonical per-`:politicas` `:circuit-breaker` Envoy-
31431        // `outlier_detection`-mesh consecutive-failure-ejection scalar
31432        // pin: [`MeshPolicy::circuit_breaker`] must return the
31433        // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
31434        // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
31435        // raw field access across every representative value in the
31436        // accept-set — `None` (cluster default applies — no
31437        // per-Aplicacao breaker declaration, the gateway-class per-
31438        // listener default arm the future caixa-mesh
31439        // `outlier_detection_overlay` emitter documents),
31440        // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
31441        // (the lower boundary of the accept-set the surrounding
31442        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
31443        // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
31444        // refusals),
31445        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
31446        // (the upper boundary the same gate carves out on the sibling
31447        // `PolicyBreakerMaxFailuresExceedsCap` /
31448        // `PolicyBreakerWindowExceedsCap` refusals),
31449        // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
31450        // (a past-the-guard sentinel that pins the accessor doesn't
31451        // perform a silent bounds-collapse into `None` on the
31452        // zero-failures/zero-window arm — validate rejects zero but
31453        // the accessor must ship the raw slot verbatim so a validate-
31454        // time gate regression surfaces at the emit boundary rather
31455        // than being silently absorbed), and
31456        // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
31457        // (a past-the-guard sentinel that pins the accessor doesn't
31458        // perform a silent bounds-collapse at the return path).
31459        //
31460        // Second `Option<Copy-composite-T>`-return accessor pin on the
31461        // M3 mesh-slot family (peer of the sibling per-`:politicas`
31462        // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
31463        // composite-Copy accessor pin, and of the sibling per-
31464        // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
31465        // [`MeshPolicy::retries`] bdfb399 /
31466        // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
31467        // accessor pins). Pins against a future silent detour that
31468        // re-derived the breaker declaration from a peer axis (an
31469        // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
31470        // collapse that read the rate-limit's bucket capacity + refill
31471        // period as a breaker declaration), a `None → Some(default())`
31472        // cluster-default projection (which would silently re-
31473        // introduce the `PolicyBreakerZeroFailures` /
31474        // `PolicyBreakerZeroWindow` refusal cases at the emit
31475        // boundary), a bounds-collapsing accessor that clamped
31476        // `cb.max_failures` through
31477        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
31478        // through [`POLICY_BREAKER_WINDOW_MAX`] (the
31479        // [`AplicacaoSpec::validate`] gate owns the bounds; the
31480        // accessor must ship the raw slot verbatim), or a
31481        // by-reference detour (`Option<&CircuitBreaker>`) that broke
31482        // every downstream consumer keying off `Option<CircuitBreaker>`
31483        // by-copy.
31484        for cb in [
31485            None,
31486            Some(CircuitBreaker {
31487                max_failures: 1,
31488                window: Duration::from_millis(1),
31489            }),
31490            Some(CircuitBreaker {
31491                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
31492                window: POLICY_BREAKER_WINDOW_MAX,
31493            }),
31494            Some(CircuitBreaker {
31495                max_failures: 0,
31496                window: Duration::ZERO,
31497            }),
31498            Some(CircuitBreaker {
31499                max_failures: u32::MAX,
31500                window: Duration::MAX,
31501            }),
31502        ] {
31503            let p = MeshPolicy {
31504                circuit_breaker: cb,
31505                ..MeshPolicy::default()
31506            };
31507            assert_eq!(
31508                p.circuit_breaker(),
31509                cb,
31510                "MeshPolicy::circuit_breaker must return :politicas \
31511                 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
31512                p.circuit_breaker(),
31513            );
31514            assert_eq!(
31515                p.circuit_breaker(),
31516                p.circuit_breaker,
31517                "MeshPolicy::circuit_breaker must byte-equal the raw \
31518                 .circuit_breaker field access across every value in \
31519                 the accept-set",
31520            );
31521        }
31522    }
31523
31524    #[test]
31525    fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
31526        // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
31527        // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
31528        // `.circuit_breaker` field access. Structurally: toggling ONLY
31529        // the `circuit_breaker` slot on an otherwise-default MeshPolicy
31530        // must flip `is_empty()` from `true` (all-`None`) to `false`
31531        // (one axis carries a value); the flip must be observed for
31532        // every representative value in the accept-set the surrounding
31533        // [`AplicacaoSpec::validate_politicas`] gate accepts
31534        // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
31535        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
31536        // since the emptiness semantic reads "any axis carries a
31537        // value" — not "any axis carries a value the validate gate
31538        // accepts" — the same non-collapsing shape the peer M2
31539        // [`crate::LimitsSpec::is_empty`] /
31540        // [`crate::BehaviorSpec::is_empty`] predicates carry.
31541        //
31542        // Pins against a future silent detour that re-derived the
31543        // emptiness predicate off a peer axis (an accidental
31544        // `.rate_limit.is_none()`-only chain that dropped the
31545        // `circuit_breaker` arm entirely — the last unlifted inline
31546        // field access on `is_empty` before this lift), a
31547        // `circuit_breaker == Some(_)` collapse that key-off a
31548        // validate-gate-clamped bounds check (which would silently
31549        // classify a past-the-guard `Some(CircuitBreaker { max_failures:
31550        // 0, window: 0s })` as empty because it fails the value-shape
31551        // gate), or an accessor-side detour that no longer names the
31552        // substrate-primitive typed dispatch.
31553        //
31554        // Fifth "the emptiness predicate must route through the
31555        // substrate-primitive typed dispatch" composition pin on the
31556        // M3 mesh-slot family — closes the last unlifted composition
31557        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
31558        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
31559        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
31560        // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
31561        // composition pins on the sibling primitive-Copy + composite-
31562        // Copy axes, extended onto the peer per-`:politicas`
31563        // composite-Copy `Option<CircuitBreaker>` axis).
31564        let empty = MeshPolicy::default();
31565        assert!(
31566            empty.is_empty(),
31567            "MeshPolicy::default() must be is_empty() — every axis \
31568             defaults to None",
31569        );
31570        for cb in [
31571            CircuitBreaker {
31572                max_failures: 1,
31573                window: Duration::from_millis(1),
31574            },
31575            CircuitBreaker {
31576                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
31577                window: POLICY_BREAKER_WINDOW_MAX,
31578            },
31579        ] {
31580            let p = MeshPolicy {
31581                circuit_breaker: Some(cb),
31582                ..MeshPolicy::default()
31583            };
31584            assert!(
31585                !p.is_empty(),
31586                "MeshPolicy::is_empty must return false when \
31587                 :circuit-breaker is {cb:?} — the emptiness predicate \
31588                 reads \"any axis carries a value\", not \"any axis \
31589                 carries a value the validate gate accepts\"",
31590            );
31591            assert_eq!(
31592                p.circuit_breaker().is_none(),
31593                p.is_empty(),
31594                "when :circuit-breaker is the only set axis, \
31595                 is_empty() must equal circuit_breaker().is_none() — \
31596                 the accessor and the emptiness predicate must route \
31597                 through the same substrate-primitive typed dispatch \
31598                 on the :circuit-breaker arm",
31599            );
31600        }
31601    }
31602
31603    #[test]
31604    fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
31605        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
31606        // `:circuit-breaker` value-shape gate must key off
31607        // [`MeshPolicy::circuit_breaker`], not the raw
31608        // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
31609        // whose only set axis is a `Some(CircuitBreaker { max_failures:
31610        // 0, .. })` must surface the `PolicyBreakerZeroFailures`
31611        // refusal exactly, and the same MeshPolicy with the breaker at
31612        // the canonical lower boundary
31613        // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
31614        // pass validate. The pair jointly pins the accessor +
31615        // validate-gate composition: any future silent detour that had
31616        // the accessor omit the `Some(CircuitBreaker { max_failures:
31617        // 0, .. })` arm (a
31618        // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
31619        // collapse) would silently absorb the
31620        // `PolicyBreakerZeroFailures` refusal at the accessor
31621        // boundary — the composition pin catches that at caixa-core
31622        // build time.
31623        //
31624        // Sibling of the peer [`validate_politicas`]
31625        // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
31626        // composition pins on the sibling primitive-Copy + composite-
31627        // Copy optional-scalar axes — same "the validate / shape-gate
31628        // predicate must route through the substrate-primitive typed
31629        // dispatch" discipline extended onto the peer per-`:politicas`
31630        // composite-Copy `Option<CircuitBreaker>` axis. Second
31631        // composition-with-accessor pin on the M3 mesh-slot
31632        // `Option<CircuitBreaker>` arm alongside the
31633        // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
31634        let mut spec = three_member_spec();
31635        spec.politicas = MeshPolicy {
31636            circuit_breaker: Some(CircuitBreaker {
31637                max_failures: 0,
31638                window: Duration::from_millis(1),
31639            }),
31640            ..MeshPolicy::default()
31641        };
31642        assert!(
31643            matches!(
31644                spec.validate(),
31645                Err(AplicacaoError::PolicyBreakerZeroFailures)
31646            ),
31647            "validate_politicas must reject max_failures == 0 with \
31648             PolicyBreakerZeroFailures — the accessor and the validate \
31649             gate must route through the same substrate-primitive \
31650             typed dispatch on the :circuit-breaker zero-floor arm",
31651        );
31652        spec.politicas = MeshPolicy {
31653            circuit_breaker: Some(CircuitBreaker {
31654                max_failures: 1,
31655                window: Duration::from_millis(1),
31656            }),
31657            ..MeshPolicy::default()
31658        };
31659        assert!(
31660            spec.validate().is_ok(),
31661            "validate_politicas must accept a CircuitBreaker at the \
31662             canonical lower boundary (max_failures = 1, window = \
31663             1ms) — the accessor and the validate gate must route \
31664             through the same substrate-primitive typed dispatch on \
31665             the :circuit-breaker arm",
31666        );
31667    }
31668
31669    #[test]
31670    fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
31671        // The canonical per-`:politicas :circuit-breaker` `:max-failures`
31672        // Envoy-outlier-detection trip-threshold scalar pin:
31673        // [`CircuitBreaker::max_failures`] must return the
31674        // `:politicas :circuit-breaker :max-failures` typed `u32`
31675        // verbatim, byte-equal to the raw field access across every
31676        // representative value in the accept-set — `1` (the lower
31677        // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
31678        // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
31679        // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
31680        // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
31681        // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
31682        // refusal), `0` (a past-the-guard sentinel that pins the accessor
31683        // doesn't perform a silent bounds-collapse into `1` on the zero
31684        // arm — validate rejects zero but the accessor must ship the
31685        // raw slot verbatim so a validate-time gate regression surfaces
31686        // at the emit boundary rather than being silently absorbed),
31687        // `u32::MAX` (a past-the-guard sentinel that pins the accessor
31688        // doesn't perform a silent bounds-collapse through
31689        // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
31690        //
31691        // First sub-struct required-scalar accessor pin on the M3
31692        // mesh-slot family — sibling in shape to the peer per-`:membros`
31693        // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
31694        // (a40b0e3) required-`String`-carry accessor pins and the peer
31695        // per-`:contratos` [`WitContract::source`] /
31696        // [`WitContract::destination`] (7f0fd43) required-`String`-carry
31697        // accessor pins, extended onto the peer per-`CircuitBreaker`
31698        // required-`u32` scalar-value axis. Pins against a future silent
31699        // detour that re-derived the trip threshold from a peer axis (an
31700        // accidental `self.window.as_secs() as u32` collapse that read
31701        // the breaker's rolling-window duration as a failure count), a
31702        // `0 → 1` cluster-default projection (which would silently absorb
31703        // the `PolicyBreakerZeroFailures` refusal case at the accessor
31704        // boundary), or a bounds-collapsing accessor that clamped the
31705        // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
31706        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
31707        // must ship the raw slot verbatim).
31708        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
31709            let cb = CircuitBreaker {
31710                max_failures,
31711                window: Duration::from_secs(60),
31712            };
31713            assert_eq!(
31714                cb.max_failures(),
31715                max_failures,
31716                "CircuitBreaker::max_failures must return :politicas \
31717                 :circuit-breaker :max-failures verbatim (got {}, \
31718                 expected {max_failures})",
31719                cb.max_failures(),
31720            );
31721            assert_eq!(
31722                cb.max_failures(),
31723                cb.max_failures,
31724                "CircuitBreaker::max_failures must byte-equal the raw \
31725                 .max_failures field access across every value in the \
31726                 u32 accept-set",
31727            );
31728        }
31729    }
31730
31731    #[test]
31732    fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
31733        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
31734        // `:circuit-breaker :max-failures` zero-floor arm must key off
31735        // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
31736        // field access. Structurally: a `CircuitBreaker { max_failures:
31737        // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
31738        // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
31739        // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
31740        // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
31741        // pass validate. The pair jointly pins the accessor +
31742        // validate-gate composition: any future silent detour that had
31743        // the accessor return a fresh `1` on the zero arm (a
31744        // `.max_failures().max(1)` collapse) would silently absorb the
31745        // `PolicyBreakerZeroFailures` refusal at the accessor boundary
31746        // and the validate gate would accept a struct-literal
31747        // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
31748        // catches that at caixa-core build time.
31749        //
31750        // Peer of the sibling per-`:politicas`
31751        // [`MeshPolicy::mtls_required`] (c0110f1) /
31752        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
31753        // (7073d0f) accessor-composition pins on the sibling optional-
31754        // scalar axes — same "the validate / shape-gate predicate must
31755        // route through the substrate-primitive typed dispatch"
31756        // discipline extended onto the peer per-`CircuitBreaker`
31757        // required-scalar composition axis.
31758        let mut spec = three_member_spec();
31759        spec.politicas = MeshPolicy {
31760            circuit_breaker: Some(CircuitBreaker {
31761                max_failures: 0,
31762                window: Duration::from_secs(60),
31763            }),
31764            ..MeshPolicy::default()
31765        };
31766        assert!(
31767            matches!(
31768                spec.validate(),
31769                Err(AplicacaoError::PolicyBreakerZeroFailures)
31770            ),
31771            "validate_politicas must reject max_failures == 0 with \
31772             PolicyBreakerZeroFailures — the accessor and the validate \
31773             gate must route through the same substrate-primitive typed \
31774             dispatch on the :max-failures zero-floor arm",
31775        );
31776        spec.politicas = MeshPolicy {
31777            circuit_breaker: Some(CircuitBreaker {
31778                max_failures: 1,
31779                window: Duration::from_secs(60),
31780            }),
31781            ..MeshPolicy::default()
31782        };
31783        assert!(
31784            spec.validate().is_ok(),
31785            "validate_politicas must accept max_failures == 1 (the \
31786             lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
31787             accept-set)",
31788        );
31789    }
31790
31791    #[test]
31792    fn circuit_breaker_max_failures_projects_u32_by_copy() {
31793        // The by-copy pin: [`CircuitBreaker::max_failures`] returns
31794        // `u32` by copy — `u32` is `Copy` and the accessor must return
31795        // by value, not by reference. Peer of the sibling
31796        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
31797        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
31798        // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
31799        // optional-scalar axes, extended onto the peer
31800        // per-`CircuitBreaker` required-`u32` copy-invariant shape —
31801        // the accessor's returned `u32` must outlive `&self` (multiple
31802        // calls must return equal values from a dropped-`&self` copy,
31803        // since the returned scalar carries no borrow), and calling
31804        // the accessor twice on the same CircuitBreaker must yield the
31805        // same `u32` verbatim (idempotent, no side effects on `&self`).
31806        //
31807        // Pins against a future silent detour that returned `&u32`
31808        // (which would type-check but silently break every downstream
31809        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
31810        // first parameter is `u32`, and `&u32` would fold to a detached
31811        // copy at the call site with a `*` deref the sibling accessors
31812        // don't need), an accidental `.max_failures.wrapping_add(0)`
31813        // detour that returned a fresh copy through an arithmetic
31814        // no-op (breaking a future `const fn` regression), or a
31815        // one-arm-only accessor that returned a saturating value on
31816        // some sentinel input (breaking the pass-through invariant the
31817        // sibling required-scalar accessors carry).
31818        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
31819            let cb = CircuitBreaker {
31820                max_failures,
31821                window: Duration::from_secs(60),
31822            };
31823            let first = cb.max_failures();
31824            let second = cb.max_failures();
31825            assert_eq!(
31826                first, second,
31827                "CircuitBreaker::max_failures must be idempotent — two \
31828                 successive calls on the same &self must return the \
31829                 same u32",
31830            );
31831            assert_eq!(
31832                first, max_failures,
31833                "CircuitBreaker::max_failures must return :politicas \
31834                 :circuit-breaker :max-failures verbatim by copy — \
31835                 got {first}, expected {max_failures}",
31836            );
31837        }
31838    }
31839
31840    #[test]
31841    fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
31842        // The canonical per-`:politicas :circuit-breaker` `:window`
31843        // Envoy-outlier-detection rolling-observation-interval scalar
31844        // pin: [`CircuitBreaker::window`] must return the
31845        // `:politicas :circuit-breaker :window` typed `Duration`
31846        // verbatim, byte-equal to the raw field access across every
31847        // representative value in the accept-set — `Duration::from_millis(1)`
31848        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
31849        // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
31850        // gate carves out on the sibling `PolicyBreakerZeroWindow`
31851        // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
31852        // same gate carves out on the sibling
31853        // `PolicyBreakerWindowExceedsCap` refusal),
31854        // `Duration::ZERO` (a past-the-guard sentinel that pins the
31855        // accessor doesn't perform a silent bounds-collapse into
31856        // `Duration::from_millis(1)` on the zero arm — validate rejects
31857        // zero but the accessor must ship the raw slot verbatim so a
31858        // validate-time gate regression surfaces at the emit boundary
31859        // rather than being silently absorbed),
31860        // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
31861        // far above the 1h cap — that pins the accessor doesn't perform
31862        // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
31863        // at the return path).
31864        //
31865        // Second sub-struct required-scalar accessor pin on the M3
31866        // mesh-slot family — sibling in shape to the just-landed
31867        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
31868        // (3a74062) required-`u32` accessor pin on the peer
31869        // per-`CircuitBreaker` required-axis, extended onto the
31870        // per-sub-struct required-`Duration` axis. Pins against a
31871        // future silent detour that re-derived the observation window
31872        // from a peer axis (an accidental
31873        // `Duration::from_secs(self.max_failures as u64)` collapse that
31874        // read the breaker's trip count as an observation-interval
31875        // duration), a `Duration::ZERO → Duration::from_millis(1)`
31876        // cluster-default projection (which would silently absorb the
31877        // `PolicyBreakerZeroWindow` refusal case at the accessor
31878        // boundary), or a bounds-collapsing accessor that clamped the
31879        // return through `POLICY_BREAKER_WINDOW_MAX` (the
31880        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
31881        // must ship the raw slot verbatim).
31882        for window in [
31883            Duration::from_millis(1),
31884            POLICY_BREAKER_WINDOW_MAX,
31885            Duration::ZERO,
31886            Duration::from_secs(86_400),
31887        ] {
31888            let cb = CircuitBreaker {
31889                max_failures: 5,
31890                window,
31891            };
31892            assert_eq!(
31893                cb.window(),
31894                window,
31895                "CircuitBreaker::window must return :politicas \
31896                 :circuit-breaker :window verbatim (got {:?}, \
31897                 expected {window:?})",
31898                cb.window(),
31899            );
31900            assert_eq!(
31901                cb.window(),
31902                cb.window,
31903                "CircuitBreaker::window must byte-equal the raw \
31904                 .window field access across every value in the \
31905                 Duration accept-set",
31906            );
31907        }
31908    }
31909
31910    #[test]
31911    fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
31912        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
31913        // `:circuit-breaker :window` zero-floor arm must key off
31914        // [`CircuitBreaker::window`], not the raw `.window` field
31915        // access. Structurally: a `CircuitBreaker { window:
31916        // Duration::ZERO, .. }` embedded in a
31917        // `:politicas :circuit-breaker` slot must surface the
31918        // `PolicyBreakerZeroWindow` refusal exactly, and a
31919        // `CircuitBreaker { window: Duration::from_millis(1), .. }`
31920        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
31921        // accept-set) must pass validate. The pair jointly pins the
31922        // accessor + validate-gate composition: any future silent
31923        // detour that had the accessor return a fresh
31924        // `Duration::from_millis(1)` on the zero arm (a
31925        // `.window().max(Duration::from_millis(1))` collapse) would
31926        // silently absorb the `PolicyBreakerZeroWindow` refusal at the
31927        // accessor boundary and the validate gate would accept a
31928        // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
31929        // — the composition pin catches that at caixa-core build time.
31930        //
31931        // Peer of the sibling per-`CircuitBreaker`
31932        // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
31933        // pin on the peer required-scalar `:max-failures` axis — same
31934        // "the validate / shape-gate predicate must route through the
31935        // substrate-primitive typed dispatch" discipline extended onto
31936        // the peer per-`CircuitBreaker` required-`Duration` composition
31937        // axis.
31938        let mut spec = three_member_spec();
31939        spec.politicas = MeshPolicy {
31940            circuit_breaker: Some(CircuitBreaker {
31941                max_failures: 5,
31942                window: Duration::ZERO,
31943            }),
31944            ..MeshPolicy::default()
31945        };
31946        assert!(
31947            matches!(
31948                spec.validate(),
31949                Err(AplicacaoError::PolicyBreakerZeroWindow)
31950            ),
31951            "validate_politicas must reject window == Duration::ZERO \
31952             with PolicyBreakerZeroWindow — the accessor and the \
31953             validate gate must route through the same substrate-\
31954             primitive typed dispatch on the :window zero-floor arm",
31955        );
31956        spec.politicas = MeshPolicy {
31957            circuit_breaker: Some(CircuitBreaker {
31958                max_failures: 5,
31959                window: Duration::from_millis(1),
31960            }),
31961            ..MeshPolicy::default()
31962        };
31963        assert!(
31964            spec.validate().is_ok(),
31965            "validate_politicas must accept window == \
31966             Duration::from_millis(1) (the lower boundary of the \
31967             1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
31968        );
31969    }
31970
31971    #[test]
31972    fn circuit_breaker_window_projects_duration_by_copy() {
31973        // The by-copy pin: [`CircuitBreaker::window`] returns
31974        // `Duration` by copy — `Duration` is `Copy` and the accessor
31975        // must return by value, not by reference. Peer of the sibling
31976        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
31977        // (3a74062) by-copy pin on the peer required-scalar
31978        // `:max-failures` axis, extended onto the peer
31979        // per-`CircuitBreaker` required-`Duration` copy-invariant shape
31980        // — the accessor's returned `Duration` must outlive `&self`
31981        // (multiple calls must return equal values from a
31982        // dropped-`&self` copy, since the returned scalar carries no
31983        // borrow), and calling the accessor twice on the same
31984        // CircuitBreaker must yield the same `Duration` verbatim
31985        // (idempotent, no side effects on `&self`).
31986        //
31987        // Pins against a future silent detour that returned
31988        // `&Duration` (which would type-check but silently break every
31989        // downstream `Duration`-by-value consumer —
31990        // [`crate::render::require_positive_canonical_bounded_duration`]'s
31991        // first parameter is `Duration`, and `&Duration` would fold to
31992        // a detached copy at the call site with a `*` deref the sibling
31993        // accessors don't need), an accidental `.window + Duration::ZERO`
31994        // detour that returned a fresh copy through an arithmetic
31995        // no-op (breaking a future `const fn` regression), or a
31996        // one-arm-only accessor that returned a saturating value on
31997        // some sentinel input (breaking the pass-through invariant the
31998        // sibling required-scalar accessors carry).
31999        for window in [
32000            Duration::from_millis(1),
32001            POLICY_BREAKER_WINDOW_MAX,
32002            Duration::ZERO,
32003            Duration::from_secs(86_400),
32004        ] {
32005            let cb = CircuitBreaker {
32006                max_failures: 5,
32007                window,
32008            };
32009            let first = cb.window();
32010            let second = cb.window();
32011            assert_eq!(
32012                first, second,
32013                "CircuitBreaker::window must be idempotent — two \
32014                 successive calls on the same &self must return the \
32015                 same Duration",
32016            );
32017            assert_eq!(
32018                first, window,
32019                "CircuitBreaker::window must return :politicas \
32020                 :circuit-breaker :window verbatim by copy — \
32021                 got {first:?}, expected {window:?}",
32022            );
32023        }
32024    }
32025
32026    #[test]
32027    fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
32028        // Apex-identity pair-invariant pin composing both substrate-
32029        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
32030        // and [`WitContract::destination`] — at the emit-side call shape
32031        // every per-`(:de, :para)` CNP L4 port reader now takes. The
32032        // invariant, evaluated per-edge:
32033        //
32034        //   spec.port_for_destination(c.destination()) == expected_port
32035        //
32036        // where `expected_port` is `entrada.port` when
32037        // `c.destination() == entrada.destination()` and
32038        // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
32039        // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
32040        // pin on the per-`:entrada` axis — that pin encodes the apex
32041        // ingress L4 identity via `entrada.destination()`; this pin
32042        // encodes the per-edge L4 identity via `c.destination()`, and
32043        // both compose on the same substrate-primitive resolver so a
32044        // future refactor that silently split either accessor's apex
32045        // behavior surfaces at caixa-core build time.
32046        let mut spec = three_member_spec();
32047        if let Some(e) = spec.entrada.as_mut() {
32048            e.para = "cart".into();
32049            e.port = 8443;
32050        }
32051        let apex_contract = WitContract {
32052            de: "checkout".into(),
32053            para: "cart".into(),
32054            wit: "wasi:http/proxy".into(),
32055            endpoint: Some("/hello".into()),
32056            subject: None,
32057            slot: None,
32058        };
32059        assert_eq!(
32060            spec.port_for_destination(apex_contract.destination()),
32061            8443,
32062            "`spec.port_for_destination(c.destination())` must equal \
32063             `entrada.port` when the contract callee names the ingress \
32064             apex — the CNP per-edge L4 port and the HTTPRoute apex \
32065             backendRef port share this substrate-primitive resolver.",
32066        );
32067        let non_apex_contract = WitContract {
32068            de: "cart".into(),
32069            para: "payment".into(),
32070            wit: "wasi:http/proxy".into(),
32071            endpoint: Some("/charge".into()),
32072            subject: None,
32073            slot: None,
32074        };
32075        assert_eq!(
32076            spec.port_for_destination(non_apex_contract.destination()),
32077            DEFAULT_SERVICO_PORT,
32078            "`spec.port_for_destination(c.destination())` must fall back \
32079             to the substrate-canonical port floor when the contract \
32080             callee is not the ingress apex — the resolver's non-apex \
32081             arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
32082        );
32083    }
32084
32085    #[test]
32086    fn membro_key_consts_are_lower_camel_case_shape() {
32087        // Shape-pin: every `MEMBRO_KEY_*` const must be a
32088        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
32089        // `kebab-case` hyphens, no leading colon, no `PascalCase`
32090        // leading capital, no whitespace / dots) — the canonical shape
32091        // the `#[serde(rename_all = "camelCase")]` derive produces on
32092        // [`Membro`]. A future flip to a non-camelCase attribute at
32093        // the derive surfaces both here (this test fails on the
32094        // stale-constant shape) and at
32095        // `membro_serde_keys_match_lifted_membro_key_consts` (that test
32096        // fails on the mismatch between const and derive). Peer with
32097        // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
32098        // on the sibling `SupervisorSpec` top-level axis.
32099        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
32100            assert!(
32101                !key.is_empty(),
32102                "MEMBRO_KEY_* must be non-empty (got {key:?})"
32103            );
32104            let first = key.chars().next().unwrap();
32105            assert!(
32106                first.is_ascii_lowercase(),
32107                "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
32108                 (got {key:?}, leads with {first:?})",
32109            );
32110            assert!(
32111                key.chars().all(|c| c.is_ascii_alphanumeric()),
32112                "MEMBRO_KEY_* must be ASCII-alphanumeric only \
32113                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
32114            );
32115        }
32116    }
32117
32118    // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
32119
32120    #[test]
32121    fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
32122        // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
32123        // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
32124        // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
32125        // keys the `#[serde(rename_all = "camelCase")]` attribute on
32126        // [`WitContract`] emits for the required-triad. The three
32127        // sibling payload-arm keys already pin under
32128        // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
32129        // `STORE_FIELD_NAME` — pin all six alongside so a future
32130        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
32131        // verbatim-field-name flip at the derive attribute (any of which
32132        // would silently break every downstream JSON consumer that
32133        // reaches for one of the six via `Value::get(...)`) surfaces
32134        // here as a build-time test failure at `aplicacao.rs`, not as an
32135        // apply-time `.get(<stale-canonical-const>)` returning `None`
32136        // far from the derive-attr drift's commit. Peer with the sibling
32137        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
32138        // pin on the M3 `:membros` per-entry axis — same discipline the
32139        // `Membro` per-entry lift established, extended here to the
32140        // sibling M3 `WitContract` per-`:contratos` entry axis, the last
32141        // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
32142        // axis on the Aplicacao surface without a lifted serde-key peer.
32143        let c = WitContract {
32144            de: "cart".into(),
32145            para: "catalog".into(),
32146            wit: "wasi:http/proxy".into(),
32147            endpoint: Some("/lookup".into()),
32148            subject: None,
32149            slot: None,
32150        };
32151        let json = serde_json::to_string(&c).unwrap();
32152        for key in [
32153            crate::CONTRATO_KEY_DE,
32154            crate::CONTRATO_KEY_PARA,
32155            crate::CONTRATO_KEY_WIT,
32156            WitTarget::HTTP_FIELD_NAME,
32157        ] {
32158            let quoted = format!("\"{key}\"");
32159            assert!(
32160                json.contains(&quoted),
32161                "serialized WitContract must carry the lifted \
32162                 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
32163                 {quoted} verbatim in the JSON emission (got: {json})",
32164            );
32165        }
32166
32167        // Pin the two remaining payload-arm keys by round-tripping a
32168        // `WitContract` under each payload-shape (pub-sub, store) — the
32169        // required-triad appears on every emission but the payload arms
32170        // only surface when their `Option<String>` field is `Some`.
32171        let pubsub = WitContract {
32172            de: "cart".into(),
32173            para: "events".into(),
32174            wit: "nats:pub-sub".into(),
32175            endpoint: None,
32176            subject: Some("orders.placed".into()),
32177            slot: None,
32178        };
32179        let pubsub_json = serde_json::to_string(&pubsub).unwrap();
32180        let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
32181        assert!(
32182            pubsub_json.contains(&pubsub_quoted),
32183            "serialized pub-sub WitContract must carry the lifted \
32184             WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
32185             verbatim in the JSON emission (got: {pubsub_json})",
32186        );
32187        let store = WitContract {
32188            de: "cart".into(),
32189            para: "sessions".into(),
32190            wit: "wasi:keyvalue/store".into(),
32191            endpoint: None,
32192            subject: None,
32193            slot: Some("cart/$id".into()),
32194        };
32195        let store_json = serde_json::to_string(&store).unwrap();
32196        let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
32197        assert!(
32198            store_json.contains(&store_quoted),
32199            "serialized store WitContract must carry the lifted \
32200             WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
32201             verbatim in the JSON emission (got: {store_json})",
32202        );
32203    }
32204
32205    #[test]
32206    fn contrato_key_consts_are_pairwise_distinct() {
32207        // Cross-axis drift-detection pin: a future collapse of the six
32208        // canonical [`WitContract`] per-entry byte-strings onto the same
32209        // value (e.g. an accidental copy-paste flip of
32210        // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
32211        // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
32212        // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
32213        // every downstream probe on one axis onto the sibling axis's
32214        // overlay entry and pass every propagation-probe test that
32215        // expected only the stale axis's value. Peer of the sibling
32216        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
32217        // widened here to the six-way axis the `WitContract`
32218        // required-triad + `WitTarget` payload-triad jointly cover.
32219        let all = [
32220            crate::CONTRATO_KEY_DE,
32221            crate::CONTRATO_KEY_PARA,
32222            crate::CONTRATO_KEY_WIT,
32223            WitTarget::HTTP_FIELD_NAME,
32224            WitTarget::PUBSUB_FIELD_NAME,
32225            WitTarget::STORE_FIELD_NAME,
32226        ];
32227        for (i, a) in all.iter().enumerate() {
32228            for b in all.iter().skip(i + 1) {
32229                assert_ne!(
32230                    a, b,
32231                    "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
32232                     must be pairwise-distinct canonical byte-sequences \
32233                     — got `{a}` == `{b}`",
32234                );
32235            }
32236        }
32237    }
32238
32239    #[test]
32240    fn contrato_key_consts_are_lower_camel_case_shape() {
32241        // Shape-pin: every `CONTRATO_KEY_*` (and every peer
32242        // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
32243        // byte-sequence (no `snake_case` underscores, no `kebab-case`
32244        // hyphens, no leading colon, no `PascalCase` leading capital, no
32245        // whitespace / dots) — the canonical shape the
32246        // `#[serde(rename_all = "camelCase")]` derive produces on
32247        // [`WitContract`]. A future flip to a non-camelCase attribute at
32248        // the derive surfaces both here (this test fails on the
32249        // stale-constant shape) and at
32250        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
32251        // (that test fails on the mismatch between const and derive).
32252        // Peer with `membro_key_consts_are_lower_camel_case_shape`
32253        // (ce80ca0) on the sibling `Membro` per-entry axis.
32254        for key in [
32255            crate::CONTRATO_KEY_DE,
32256            crate::CONTRATO_KEY_PARA,
32257            crate::CONTRATO_KEY_WIT,
32258            WitTarget::HTTP_FIELD_NAME,
32259            WitTarget::PUBSUB_FIELD_NAME,
32260            WitTarget::STORE_FIELD_NAME,
32261        ] {
32262            assert!(
32263                !key.is_empty(),
32264                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
32265                 non-empty (got {key:?})"
32266            );
32267            let first = key.chars().next().unwrap();
32268            assert!(
32269                first.is_ascii_lowercase(),
32270                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
32271                 with an ASCII-lowercase byte (got {key:?}, leads with \
32272                 {first:?})",
32273            );
32274            assert!(
32275                key.chars().all(|c| c.is_ascii_alphanumeric()),
32276                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
32277                 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
32278                 whitespace (got {key:?})",
32279            );
32280        }
32281    }
32282
32283    // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
32284
32285    #[test]
32286    fn entrada_serde_keys_match_lifted_entrada_key_consts() {
32287        // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
32288        // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
32289        // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
32290        // name the exact camelCase JSON keys the
32291        // `#[serde(rename_all = "camelCase")]` attribute on
32292        // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
32293        // pin that each canonical byte-sequence appears verbatim in the
32294        // JSON — a future accidental `rename_all = "snake_case"` /
32295        // `"kebab-case"` / verbatim-field-name flip at the derive
32296        // attribute (any of which would silently break every downstream
32297        // JSON consumer that reaches for one of the four consts via
32298        // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
32299        // emitter's per-Aplicacao hostname/paths/port projection, the
32300        // future `app-operator` reconciler's per-Aplicacao ingress
32301        // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
32302        // materializer's admission-time cross-check) surfaces here as
32303        // a build-time test failure at `aplicacao.rs`, not as an
32304        // apply-time `.get(<stale-canonical-const>)` returning `None`
32305        // far from the derive-attr drift's commit. Peer with the
32306        // sibling
32307        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
32308        // (ca463a4) and
32309        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
32310        // pins on the M3 collection-slot atom axes — same discipline
32311        // both collection-slot lifts established, extended here to the
32312        // singleton `:entrada` mesh-slot atom axis, the last M3
32313        // typed-struct top-level `#[serde(rename_all = "camelCase")]`
32314        // axis on the Aplicacao surface without a lifted serde-key
32315        // peer.
32316        let e = Entrada {
32317            host: "checkout.quero.cloud".into(),
32318            para: "cart".into(),
32319            paths: vec!["/cart".into()],
32320            port: 8080,
32321        };
32322        let json = serde_json::to_string(&e).unwrap();
32323        for key in [
32324            crate::ENTRADA_KEY_HOST,
32325            crate::ENTRADA_KEY_PARA,
32326            crate::ENTRADA_KEY_PATHS,
32327            crate::ENTRADA_KEY_PORT,
32328        ] {
32329            let quoted = format!("\"{key}\"");
32330            assert!(
32331                json.contains(&quoted),
32332                "serialized Entrada must carry the lifted ENTRADA_KEY_* \
32333                 byte-sequence {quoted} verbatim in the JSON emission \
32334                 (got: {json})",
32335            );
32336        }
32337    }
32338
32339    #[test]
32340    fn entrada_key_consts_are_pairwise_distinct() {
32341        // Cross-axis drift-detection pin: a future collapse of the four
32342        // canonical [`Entrada`] singleton byte-strings onto the same
32343        // value (e.g. an accidental copy-paste flip of
32344        // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
32345        // silently reroute every downstream probe on one axis onto the
32346        // sibling axis's overlay entry and pass every propagation-probe
32347        // test that expected only the stale axis's value — the
32348        // Gateway/HTTPRoute emitter would read the hostname string
32349        // where the destination-Servico name was expected (or vice
32350        // versa), the admission-webhook cross-check would compare the
32351        // wrong pair of values, and the resulting Gateway resource
32352        // would either be admitted with garbage or rejected at the
32353        // controller far from the rebrand commit's source. Peer of the
32354        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
32355        // tetrad (40cc4e5), the two-way distinct pin on the
32356        // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
32357        // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
32358        // triad (ca463a4).
32359        let all = [
32360            crate::ENTRADA_KEY_HOST,
32361            crate::ENTRADA_KEY_PARA,
32362            crate::ENTRADA_KEY_PATHS,
32363            crate::ENTRADA_KEY_PORT,
32364        ];
32365        for (i, a) in all.iter().enumerate() {
32366            for b in all.iter().skip(i + 1) {
32367                assert_ne!(
32368                    a, b,
32369                    "ENTRADA_KEY_* consts must be pairwise-distinct \
32370                     canonical byte-sequences — got `{a}` == `{b}`",
32371                );
32372            }
32373        }
32374    }
32375
32376    #[test]
32377    fn entrada_key_consts_are_lower_camel_case_shape() {
32378        // Shape-pin: every `ENTRADA_KEY_*` const must be a
32379        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
32380        // `kebab-case` hyphens, no leading colon, no `PascalCase`
32381        // leading capital, no whitespace / dots) — the canonical shape
32382        // the `#[serde(rename_all = "camelCase")]` derive produces on
32383        // [`Entrada`]. A future flip to a non-camelCase attribute at
32384        // the derive surfaces both here (this test fails on the
32385        // stale-constant shape) and at
32386        // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
32387        // test fails on the mismatch between const and derive). Peer
32388        // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
32389        // and `contrato_key_consts_are_lower_camel_case_shape`
32390        // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
32391        // entry axes.
32392        for key in [
32393            crate::ENTRADA_KEY_HOST,
32394            crate::ENTRADA_KEY_PARA,
32395            crate::ENTRADA_KEY_PATHS,
32396            crate::ENTRADA_KEY_PORT,
32397        ] {
32398            assert!(
32399                !key.is_empty(),
32400                "ENTRADA_KEY_* must be non-empty (got {key:?})"
32401            );
32402            let first = key.chars().next().unwrap();
32403            assert!(
32404                first.is_ascii_lowercase(),
32405                "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
32406                 (got {key:?}, leads with {first:?})",
32407            );
32408            assert!(
32409                key.chars().all(|c| c.is_ascii_alphanumeric()),
32410                "ENTRADA_KEY_* must be ASCII-alphanumeric only \
32411                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
32412            );
32413        }
32414    }
32415
32416    // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
32417
32418    #[test]
32419    fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
32420        // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
32421        // ([`crate::POLITICAS_KEY_TIMEOUT`] /
32422        // [`crate::POLITICAS_KEY_RETRIES`] /
32423        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
32424        // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
32425        // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
32426        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
32427        // on [`MeshPolicy`] emits. Three of the five axes
32428        // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
32429        // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
32430        // camelCase transforms — the derive-attribute is load-bearing
32431        // on those, unlike the sibling `Entrada` / `Membro` /
32432        // `WitContract` structs whose fields are all lowercase-single-
32433        // word and where the derive is a no-op on every axis.
32434        // Serialize a fully-populated [`MeshPolicy`] (every axis
32435        // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
32436        // on none of the five slots) and pin that each canonical
32437        // byte-sequence appears verbatim in the JSON — a future
32438        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
32439        // verbatim-field-name flip at the derive attribute (any of
32440        // which would silently break every downstream JSON consumer
32441        // that reaches for one of the five consts via
32442        // `Value::get(...)` — the future M4 per-edge `:politicas`
32443        // overlay projection onto Cilium `L7Rules` and Gateway API
32444        // `HTTPRoute` backend timeouts, the future
32445        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
32446        // admission-time mesh-policy cross-check, the future
32447        // `feira lint` per-`:politicas` bound-check gate) surfaces here
32448        // as a build-time test failure at `aplicacao.rs`, not as an
32449        // apply-time `.get(<stale-canonical-const>)` returning `None`
32450        // far from the derive-attr drift's commit. Peer with the
32451        // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
32452        // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
32453        // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
32454        // (ce80ca0) pins on the M3 collection-slot / singleton-slot
32455        // atom axes — same discipline every M3 sibling lift
32456        // established, extended here to the singleton `:politicas`
32457        // mesh-slot atom axis, closing the last M3 typed-struct
32458        // top-level `#[serde(rename_all = "camelCase")]` axis on the
32459        // Aplicacao surface without a lifted serde-key peer.
32460        let p = MeshPolicy {
32461            timeout: Some(Duration::from_secs(30)),
32462            retries: Some(3),
32463            circuit_breaker: Some(CircuitBreaker {
32464                max_failures: 5,
32465                window: Duration::from_secs(60),
32466            }),
32467            mtls_required: Some(true),
32468            rate_limit: Some(RateLimit {
32469                rate: 100,
32470                window: Duration::from_secs(1),
32471            }),
32472        };
32473        let json = serde_json::to_string(&p).unwrap();
32474        for key in [
32475            crate::POLITICAS_KEY_TIMEOUT,
32476            crate::POLITICAS_KEY_RETRIES,
32477            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
32478            crate::POLITICAS_KEY_MTLS_REQUIRED,
32479            crate::POLITICAS_KEY_RATE_LIMIT,
32480        ] {
32481            let quoted = format!("\"{key}\"");
32482            assert!(
32483                json.contains(&quoted),
32484                "serialized MeshPolicy must carry the lifted \
32485                 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
32486                 JSON emission (got: {json})",
32487            );
32488        }
32489    }
32490
32491    #[test]
32492    fn politicas_key_consts_are_pairwise_distinct() {
32493        // Cross-axis drift-detection pin: a future collapse of the five
32494        // canonical [`MeshPolicy`] singleton byte-strings onto the same
32495        // value (e.g. an accidental copy-paste flip of
32496        // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
32497        // would silently reroute every downstream probe on one axis
32498        // onto the sibling axis's overlay entry and pass every
32499        // propagation-probe test that expected only the stale axis's
32500        // value — the M4 per-edge `:politicas` overlay projection would
32501        // read the retry-count string where the timeout duration was
32502        // expected (or vice versa), the CR materializer's admission
32503        // cross-check would compare the wrong pair of values, and the
32504        // resulting mesh reconciler would either bind the wrong axis
32505        // or reject the resource at reconcile far from the rebrand
32506        // commit's source. Peer of the sibling four-way distinct pin
32507        // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
32508        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
32509        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
32510        // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
32511        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
32512        let all = [
32513            crate::POLITICAS_KEY_TIMEOUT,
32514            crate::POLITICAS_KEY_RETRIES,
32515            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
32516            crate::POLITICAS_KEY_MTLS_REQUIRED,
32517            crate::POLITICAS_KEY_RATE_LIMIT,
32518        ];
32519        for (i, a) in all.iter().enumerate() {
32520            for b in all.iter().skip(i + 1) {
32521                assert_ne!(
32522                    a, b,
32523                    "POLITICAS_KEY_* consts must be pairwise-distinct \
32524                     canonical byte-sequences — got `{a}` == `{b}`",
32525                );
32526            }
32527        }
32528    }
32529
32530    #[test]
32531    fn politicas_key_consts_are_lower_camel_case_shape() {
32532        // Shape-pin: every `POLITICAS_KEY_*` const must be a
32533        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
32534        // `kebab-case` hyphens, no leading colon, no `PascalCase`
32535        // leading capital, no whitespace / dots) — the canonical shape
32536        // the `#[serde(rename_all = "camelCase")]` derive produces on
32537        // [`MeshPolicy`]. A future flip to a non-camelCase attribute
32538        // at the derive surfaces both here (this test fails on the
32539        // stale-constant shape) and at
32540        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
32541        // (that test fails on the mismatch between const and derive).
32542        // Peer with `entrada_key_consts_are_lower_camel_case_shape`
32543        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
32544        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
32545        // (ca463a4) on the sibling M3 typed-struct axes.
32546        for key in [
32547            crate::POLITICAS_KEY_TIMEOUT,
32548            crate::POLITICAS_KEY_RETRIES,
32549            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
32550            crate::POLITICAS_KEY_MTLS_REQUIRED,
32551            crate::POLITICAS_KEY_RATE_LIMIT,
32552        ] {
32553            assert!(
32554                !key.is_empty(),
32555                "POLITICAS_KEY_* must be non-empty (got {key:?})"
32556            );
32557            let first = key.chars().next().unwrap();
32558            assert!(
32559                first.is_ascii_lowercase(),
32560                "POLITICAS_KEY_* must lead with an ASCII-lowercase \
32561                 byte (got {key:?}, leads with {first:?})",
32562            );
32563            assert!(
32564                key.chars().all(|c| c.is_ascii_alphanumeric()),
32565                "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
32566                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
32567            );
32568        }
32569    }
32570
32571    // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
32572
32573    #[test]
32574    fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
32575        // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
32576        // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
32577        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
32578        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
32579        // [`CircuitBreaker`] emits inside the
32580        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
32581        // two axes (`max_failures` → `maxFailures`) is a non-trivial
32582        // camelCase transform — the derive-attribute is load-bearing on
32583        // that axis, unlike the sibling `window` field where the derive
32584        // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
32585        // pin that each canonical byte-sequence appears verbatim in the
32586        // JSON — a future accidental `rename_all = "snake_case"` /
32587        // `"kebab-case"` / verbatim-field-name flip at the derive
32588        // attribute (any of which would silently break every downstream
32589        // JSON consumer that reaches for one of the two consts via
32590        // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
32591        // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
32592        // per-edge `:politicas` overlay projection onto the mesh's
32593        // per-backend consecutive-failure-counter tripping threshold, the
32594        // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
32595        // admission-time breaker cross-check, the future `feira lint`
32596        // per-`:politicas :circuit-breaker` bound-check gate) surfaces
32597        // here as a build-time test failure at `aplicacao.rs`, not as an
32598        // apply-time `.get(<stale-canonical-const>)` returning `None`
32599        // far from the derive-attr drift's commit. Peer with the sibling
32600        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
32601        // (b55cca7) parent-axis pin — that test pins the outer
32602        // sub-block key the derive on [`MeshPolicy`] emits, this test
32603        // pins the inner keys the derive on the payload type emits, so
32604        // the two together lock the whole [`MeshPolicy`] breaker-tuning
32605        // shape end-to-end at build time.
32606        let cb = CircuitBreaker {
32607            max_failures: 5,
32608            window: Duration::from_secs(60),
32609        };
32610        let json = serde_json::to_string(&cb).unwrap();
32611        for key in [
32612            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
32613            crate::CIRCUIT_BREAKER_KEY_WINDOW,
32614        ] {
32615            let quoted = format!("\"{key}\"");
32616            assert!(
32617                json.contains(&quoted),
32618                "serialized CircuitBreaker must carry the lifted \
32619                 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
32620                 in the JSON emission (got: {json})",
32621            );
32622        }
32623    }
32624
32625    #[test]
32626    fn circuit_breaker_key_consts_are_pairwise_distinct() {
32627        // Cross-axis drift-detection pin: a future collapse of the two
32628        // canonical [`CircuitBreaker`] sub-block byte-strings onto the
32629        // same value (e.g. an accidental copy-paste flip of
32630        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
32631        // `"maxFailures"`) would silently reroute every downstream
32632        // probe on one axis onto the sibling axis's overlay entry and
32633        // pass every propagation-probe test that expected only the
32634        // stale axis's value — the M4 per-edge `:politicas` overlay
32635        // projection would read the failure-count where the window
32636        // duration was expected (or vice versa), the CR materializer's
32637        // admission cross-check would compare the wrong pair of values,
32638        // and the resulting mesh reconciler would either bind the wrong
32639        // axis or reject the resource at reconcile far from the rebrand
32640        // commit's source. Peer of the sibling five-way distinct pin on
32641        // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
32642        // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
32643        // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
32644        // six-way distinct pin on the `CONTRATO_KEY_*` triad +
32645        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
32646        let all = [
32647            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
32648            crate::CIRCUIT_BREAKER_KEY_WINDOW,
32649        ];
32650        for (i, a) in all.iter().enumerate() {
32651            for b in all.iter().skip(i + 1) {
32652                assert_ne!(
32653                    a, b,
32654                    "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
32655                     canonical byte-sequences — got `{a}` == `{b}`",
32656                );
32657            }
32658        }
32659    }
32660
32661    #[test]
32662    fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
32663        // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
32664        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
32665        // `kebab-case` hyphens, no leading colon, no `PascalCase`
32666        // leading capital, no whitespace / dots) — the canonical shape
32667        // the `#[serde(rename_all = "camelCase")]` derive produces on
32668        // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
32669        // at the derive surfaces both here (this test fails on the
32670        // stale-constant shape) and at
32671        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
32672        // (that test fails on the mismatch between const and derive).
32673        // Peer with `politicas_key_consts_are_lower_camel_case_shape`
32674        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
32675        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
32676        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
32677        // (ca463a4) on the sibling M3 typed-struct axes.
32678        for key in [
32679            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
32680            crate::CIRCUIT_BREAKER_KEY_WINDOW,
32681        ] {
32682            assert!(
32683                !key.is_empty(),
32684                "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
32685            );
32686            let first = key.chars().next().unwrap();
32687            assert!(
32688                first.is_ascii_lowercase(),
32689                "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
32690                 byte (got {key:?}, leads with {first:?})",
32691            );
32692            assert!(
32693                key.chars().all(|c| c.is_ascii_alphanumeric()),
32694                "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
32695                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
32696            );
32697        }
32698    }
32699
32700    // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
32701
32702    #[test]
32703    fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
32704        // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
32705        // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
32706        // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
32707        // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
32708        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
32709        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
32710        // [`Placement`] emits. One of the four axes (`shard_key` →
32711        // `shardKey`) is a non-trivial camelCase transform — the
32712        // derive-attribute is load-bearing on that axis, unlike the
32713        // sibling `estrategia` / `clusters` / `affinity` axes whose
32714        // source-side field names carry no `_` and where the derive is a
32715        // no-op. Serialize a fully-populated [`Placement`] (both
32716        // `Option`-carrying axes `Some(_)` so
32717        // `skip_serializing_if = "Option::is_none"` fires on neither of
32718        // the two optional slots) and pin that each canonical
32719        // byte-sequence appears verbatim in the JSON — a future
32720        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
32721        // verbatim-field-name flip at the derive attribute (any of which
32722        // would silently break every downstream consumer that reaches
32723        // for one of the four consts via
32724        // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
32725        // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
32726        // aggregator's per-cluster fanout filter keying off
32727        // `placement.clusters`, the M3 shard-pool dispatch materializer
32728        // keying off `placement.shardKey`, the M3 Adaptive compression
32729        // pass weighting off `placement.affinity`, every downstream
32730        // dispatcher branching on `placement.estrategia`, the future
32731        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
32732        // admission-time placement cross-check, the future `feira lint`
32733        // per-`:placement` bound-check gate) surfaces here as a
32734        // build-time test failure at `aplicacao.rs`, not as an
32735        // apply-time `.get(<stale-canonical-const>)` returning `None`
32736        // far from the derive-attr drift's commit. Peer with the sibling
32737        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
32738        // (b55cca7),
32739        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
32740        // (468e959),
32741        // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
32742        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
32743        // (ca463a4), and
32744        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
32745        // pins on the M3 collection-slot / singleton-slot atom axes —
32746        // closes the last M3 typed-struct top-level
32747        // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
32748        // surface without a drift-detection pin.
32749        let p = Placement {
32750            estrategia: PlacementStrategy::Sharded,
32751            clusters: vec!["rio".into(), "mar".into()],
32752            affinity: Some("data-locality".into()),
32753            shard_key: Some("$tenantId".into()),
32754        };
32755        let json = serde_json::to_string(&p).unwrap();
32756        for key in [
32757            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
32758            crate::M3_PLACEMENT_KEY_CLUSTERS,
32759            crate::M3_PLACEMENT_KEY_AFFINITY,
32760            crate::M3_PLACEMENT_KEY_SHARD_KEY,
32761        ] {
32762            let quoted = format!("\"{key}\"");
32763            assert!(
32764                json.contains(&quoted),
32765                "serialized Placement must carry the lifted \
32766                 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
32767                 the JSON emission (got: {json})",
32768            );
32769        }
32770    }
32771
32772    #[test]
32773    fn m3_placement_key_consts_are_pairwise_distinct() {
32774        // Cross-axis drift-detection pin: a future collapse of the four
32775        // canonical [`Placement`] sub-block byte-strings onto the same
32776        // value (e.g. an accidental copy-paste flip of
32777        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
32778        // `"affinity"`) would silently reroute every downstream probe on
32779        // one axis onto the sibling axis's overlay entry and pass every
32780        // propagation-probe test that expected only the stale axis's
32781        // value — the M3 shard-pool dispatch materializer would read the
32782        // affinity placement-hint where the shard-selection template was
32783        // expected (or vice versa), the M3 Adaptive compression pass's
32784        // cross-check would compare the wrong pair of values, and the
32785        // resulting placement engine would either bind the wrong axis or
32786        // reject the resource at reconcile far from the rebrand commit's
32787        // source. Peer of the sibling two-way distinct pin on the
32788        // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
32789        // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
32790        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
32791        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
32792        // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
32793        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
32794        let all = [
32795            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
32796            crate::M3_PLACEMENT_KEY_CLUSTERS,
32797            crate::M3_PLACEMENT_KEY_AFFINITY,
32798            crate::M3_PLACEMENT_KEY_SHARD_KEY,
32799        ];
32800        for (i, a) in all.iter().enumerate() {
32801            for b in all.iter().skip(i + 1) {
32802                assert_ne!(
32803                    a, b,
32804                    "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
32805                     canonical byte-sequences — got `{a}` == `{b}`",
32806                );
32807            }
32808        }
32809    }
32810
32811    #[test]
32812    fn m3_placement_key_consts_are_lower_camel_case_shape() {
32813        // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
32814        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
32815        // `kebab-case` hyphens, no leading colon, no `PascalCase`
32816        // leading capital, no whitespace / dots) — the canonical shape
32817        // the `#[serde(rename_all = "camelCase")]` derive produces on
32818        // [`Placement`]. A future flip to a non-camelCase attribute at
32819        // the derive surfaces both here (this test fails on the stale-
32820        // constant shape) and at
32821        // `placement_serde_keys_match_lifted_m3_placement_key_consts`
32822        // (that test fails on the mismatch between const and derive).
32823        // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
32824        // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
32825        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
32826        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
32827        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
32828        // (ca463a4) on the sibling M3 typed-struct axes.
32829        for key in [
32830            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
32831            crate::M3_PLACEMENT_KEY_CLUSTERS,
32832            crate::M3_PLACEMENT_KEY_AFFINITY,
32833            crate::M3_PLACEMENT_KEY_SHARD_KEY,
32834        ] {
32835            assert!(
32836                !key.is_empty(),
32837                "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
32838            );
32839            let first = key.chars().next().unwrap();
32840            assert!(
32841                first.is_ascii_lowercase(),
32842                "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
32843                 byte (got {key:?}, leads with {first:?})",
32844            );
32845            assert!(
32846                key.chars().all(|c| c.is_ascii_alphanumeric()),
32847                "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
32848                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
32849            );
32850        }
32851    }
32852
32853    // ── AplicacaoSpec::port_for_destination — the substrate-canonical
32854    //    destination-facing L4 port resolver every per-Aplicacao renderer
32855    //    reaching for a per-destination Servico TCP port axis routes
32856    //    through. The four pin tests below fix the four-way accept-set
32857    //    the resolver must always honor: (:entrada-para-matches,
32858    //    :entrada-para-mismatches, :entrada-none-so-fallback,
32859    //    :entrada-port-non-default-honored) — drift on any arm surfaces
32860    //    at caixa-core build time rather than at cluster-apply time.
32861
32862    #[test]
32863    fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
32864        // The typed `:entrada` block's `:para "cart"` matches the
32865        // queried destination, so the resolver returns the author-
32866        // declared `:port` scalar verbatim — the canonical "the
32867        // destination Servico IS the ingress apex, honor the typed
32868        // listener port" arm of the port-resolution dispatch.
32869        let mut spec = three_member_spec();
32870        if let Some(e) = spec.entrada.as_mut() {
32871            e.para = "cart".into();
32872            e.port = 9090;
32873        }
32874        assert_eq!(
32875            spec.port_for_destination("cart"),
32876            9090,
32877            "port_for_destination(entrada.para) must return entrada.port \
32878             verbatim, not the DEFAULT_SERVICO_PORT fallback"
32879        );
32880    }
32881
32882    #[test]
32883    fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
32884        // The typed `:entrada` block names `:para "cart"`, but the
32885        // queried destination is `"payment"` — a Servico that
32886        // participates in the mesh graph but is not the ingress apex.
32887        // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
32888        // canonical port floor, closing the "non-apex destination reads
32889        // the substrate default" arm. Same fixture the peer
32890        // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
32891        // pin at caixa-mesh exercises through the CNP emit-side path;
32892        // this pin exercises the shared underlying resolver directly.
32893        let spec = three_member_spec();
32894        assert_eq!(
32895            spec.port_for_destination("payment"),
32896            DEFAULT_SERVICO_PORT,
32897            "port_for_destination(non-apex-destination) must route \
32898             through the lifted DEFAULT_SERVICO_PORT canonical port floor"
32899        );
32900    }
32901
32902    #[test]
32903    fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
32904        // Internal-only Aplicacao — no `:entrada` block declared. Every
32905        // per-destination port query falls back to the lifted
32906        // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
32907        // the Aplicacao surface admits `:entrada None` (internal mesh
32908        // with no external gateway); every downstream renderer's per-
32909        // destination port axis must still resolve to a well-defined
32910        // scalar even without an ingress apex.
32911        let mut spec = three_member_spec();
32912        spec.entrada = None;
32913        assert_eq!(
32914            spec.port_for_destination("cart"),
32915            DEFAULT_SERVICO_PORT,
32916            "port_for_destination on an internal-only Aplicacao must \
32917             fall back to the lifted DEFAULT_SERVICO_PORT floor for \
32918             every destination"
32919        );
32920        assert_eq!(
32921            spec.port_for_destination("payment"),
32922            DEFAULT_SERVICO_PORT,
32923            "port_for_destination on an internal-only Aplicacao must \
32924             fall back uniformly across every destination — the fallback \
32925             is not entrada-shape-conditional"
32926        );
32927    }
32928
32929    #[test]
32930    fn port_for_destination_honors_non_default_entrada_port_verbatim() {
32931        // Structural pin against a hypothetical future refactor that
32932        // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
32933        // the resolver (a "normalize to the default when the author's
32934        // port matches the substrate default" collapse) — that would
32935        // break renderer sites that carry meaning on the emitted port
32936        // value beyond bare equality (a future per-cluster listener-
32937        // audit that keys off the author-declared port, not the
32938        // resolved-with-fallback port). Pin that a non-default
32939        // entrada.port is returned verbatim so drift here surfaces at
32940        // caixa-core build time.
32941        let mut spec = three_member_spec();
32942        if let Some(e) = spec.entrada.as_mut() {
32943            e.para = "cart".into();
32944            e.port = 8443;
32945        }
32946        assert_ne!(
32947            8443, DEFAULT_SERVICO_PORT,
32948            "test fixture must probe a port distinct from \
32949             DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
32950        );
32951        assert_eq!(
32952            spec.port_for_destination("cart"),
32953            8443,
32954            "port_for_destination(entrada.para) must return entrada.port \
32955             verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
32956        );
32957    }
32958
32959    #[test]
32960    fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
32961        // Apex-identity pair-invariant pin composing both substrate-
32962        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
32963        // and [`Entrada::destination`] — at the emit-side call shape
32964        // every per-Aplicacao renderer's ingress-apex L4 port reader
32965        // now takes. The invariant:
32966        //
32967        //   spec.port_for_destination(entrada.destination()) == entrada.port
32968        //
32969        // holds by construction under today's single-destination
32970        // `:entrada` slot (`destination()` returns `entrada.para`, and
32971        // the resolver's apex arm matches `para == destination` and
32972        // returns `entrada.port`), and every downstream consumer that
32973        // composes the two accessors at the ingress apex — the
32974        // `caixa_mesh::gateway_routes` HTTPRoute per-rule
32975        // `backendRefs[0].port` emit-site path, the peer future M4 CR
32976        // materializer's admission-webhook that promotes the scalar to
32977        // a per-CR override overlay, every future per-Aplicacao snapshot
32978        // renderer's apex-facing L4 port reader — reaches through the
32979        // same composition. Pin the identity across four permutations
32980        // (`:para` × `:port` including a non-default port to exercise
32981        // the honor-verbatim arm and a non-cart `:para` to exercise
32982        // destination-agnostic identity) so a future refactor that
32983        // silently split either accessor's apex behavior surfaces at
32984        // caixa-core build time — a subtle `destination()` renaming
32985        // that returned `entrada.host.as_str()` instead of
32986        // `entrada.para.as_str()` would blow this pin loudly, closing
32987        // the last quiet failure mode the two lifts admit in composition.
32988        //
32989        // Peer discipline with the sibling caixa-mesh cross-crate pin
32990        // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
32991        // on the two-renderer pair-invariant axis; this pin encodes the
32992        // same two-consumer coherence rule at the substrate-primitive
32993        // level so the invariant survives even if every renderer is
32994        // deleted.
32995        for (para, port) in [
32996            ("cart", DEFAULT_SERVICO_PORT),
32997            ("cart", 8443u16),
32998            ("payment", 9090u16),
32999            ("catalog", 443u16),
33000        ] {
33001            let mut spec = three_member_spec();
33002            if let Some(e) = spec.entrada.as_mut() {
33003                e.para = para.into();
33004                e.port = port;
33005            }
33006            let expected_port = spec
33007                .entrada()
33008                .expect("three_member_spec carries a typed `:entrada` block")
33009                .port();
33010            let composed_port = {
33011                let entrada = spec.entrada().expect("entrada present");
33012                spec.port_for_destination(entrada.destination())
33013            };
33014            assert_eq!(
33015                composed_port, expected_port,
33016                "`spec.port_for_destination(entrada.destination())` must \
33017                 equal `entrada.port` under today's single-destination \
33018                 `:entrada` slot — this is the apex-identity contract \
33019                 every downstream ingress-apex L4 port reader relies on. \
33020                 Input :entrada :para: {para:?}, :entrada :port: {port}"
33021            );
33022        }
33023    }
33024
33025    #[test]
33026    fn port_for_destination_apex_arm_routes_through_destination_accessor() {
33027        // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
33028        // per-`:entrada` apex-arm membership probe must key off
33029        // [`Entrada::destination`], not the raw `.para` field access.
33030        // Structurally: setting ONLY the `:entrada :para` field to a
33031        // fresh non-cart destination on an otherwise-well-formed
33032        // Aplicacao must (1) leave `e.destination()` byte-equal to
33033        // `e.para.as_str()` (the accessor is byte-projective by
33034        // definition), and (2) cause the resolver's apex arm to fire
33035        // and return `entrada.port` at exactly that new destination
33036        // while every other destination string falls through to
33037        // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
33038        // membership check. Pins against a future silent detour that
33039        // (a) re-derived the apex-arm membership probe off
33040        // `e.para == destination` in `port_for_destination` instead of
33041        // `e.destination() == destination`, silently disagreeing with
33042        // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
33043        // consumers (`entrada.destination()` at
33044        // caixa-mesh/src/lib.rs:3173, `c.destination()` at
33045        // caixa-mesh/src/lib.rs:2739) that already reach through the
33046        // accessor, (b) accessor-side introduced a per-tenant alias
33047        // arm the caller was unaware of, silently rewriting an
33048        // author-declared `:para "cart"` value to a canary-aliased
33049        // form — the raw-field-access resolver would fall through to
33050        // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
33051        // while the peer emit-site consumers landed on the aliased
33052        // destination, splitting the ingress-apex L4 port at
33053        // cluster-apply time.
33054        //
33055        // Peer of the sibling
33056        // [`validate_membros_empty_gate_routes_through_nome_accessor`]
33057        // (d0de220) composition pin on the per-`:membros` refusal-arm
33058        // axis — same "the shape-gate predicate must route through the
33059        // substrate-primitive typed dispatch" discipline extended onto
33060        // the per-`:entrada` apex-arm membership-probe axis. Closes
33061        // the last unlifted `.para` production-code read site on
33062        // `Entrada` in `caixa-core` — after this converge every
33063        // `caixa-core` `.para` field access outside the accessor's own
33064        // body and outside the `WitContract` per-`:contratos` sibling
33065        // axis is either a test-side field-setter or a doc-comment
33066        // reference.
33067        for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
33068            let mut spec = three_member_spec();
33069            if let Some(e) = spec.entrada.as_mut() {
33070                e.para = para.into();
33071                e.port = port;
33072            }
33073            let e = spec
33074                .entrada
33075                .as_ref()
33076                .expect("three_member_spec carries a typed `:entrada` block");
33077            assert_eq!(
33078                e.destination(),
33079                e.para.as_str(),
33080                "Entrada::destination must byte-equal the .para field \
33081                 access — an accessor-side detour that no longer \
33082                 projects the raw field would silently split this \
33083                 drift-detection test from the port_for_destination \
33084                 apex-arm membership probe",
33085            );
33086            assert_eq!(
33087                spec.port_for_destination(para),
33088                port,
33089                "port_for_destination must key off the accessor-projected \
33090                 destination and return `entrada.port` on the apex arm — \
33091                 input :entrada :para: {para:?}, :entrada :port: {port}",
33092            );
33093            assert_eq!(
33094                spec.port_for_destination("ghost-destination-never-a-member"),
33095                DEFAULT_SERVICO_PORT,
33096                "port_for_destination must fall through to \
33097                 DEFAULT_SERVICO_PORT on a non-matching destination \
33098                 under the accessor-projected membership check — input \
33099                 :entrada :para: {para:?}, :entrada :port: {port}",
33100            );
33101        }
33102    }
33103
33104    #[test]
33105    fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
33106        // The canonical per-`:politicas :rate-limit` `:rate`
33107        // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
33108        // [`RateLimit::rate`] must return the `:politicas :rate-limit`
33109        // typed `u32` verbatim, byte-equal to the raw field access
33110        // across every representative value in the accept-set — `1` (the
33111        // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
33112        // the surrounding [`AplicacaoSpec::validate_politicas`] gate
33113        // carves out on the sibling `PolicyRateLimitZero` refusal),
33114        // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
33115        // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
33116        // `0` (a past-the-guard sentinel that pins the accessor doesn't
33117        // perform a silent bounds-collapse into `1` on the zero arm —
33118        // validate rejects zero but the accessor must ship the raw slot
33119        // verbatim so a validate-time gate regression surfaces at the
33120        // emit boundary rather than being silently absorbed), `u32::MAX`
33121        // (a past-the-guard sentinel that pins the accessor doesn't
33122        // perform a silent bounds-collapse through
33123        // `POLICY_RATE_LIMIT_MAX` at the return path).
33124        //
33125        // First sub-struct required-scalar accessor pin on the
33126        // `RateLimit` axis — sibling in shape to the peer
33127        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
33128        // required-`u32` accessor pin on the peer per-sub-struct
33129        // required-axis. Pins against a future silent detour that
33130        // re-derived the token capacity from a peer axis (an accidental
33131        // `self.window.as_secs() as u32` collapse that read the
33132        // rate-limit window duration as a token count), a `0 → 1`
33133        // cluster-default projection (which would silently absorb the
33134        // `PolicyRateLimitZero` refusal case at the accessor boundary),
33135        // or a bounds-collapsing accessor that clamped the return
33136        // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
33137        // gate owns the bounds; the accessor must ship the raw slot
33138        // verbatim).
33139        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
33140            let rl = RateLimit {
33141                rate,
33142                window: Duration::from_secs(1),
33143            };
33144            assert_eq!(
33145                rl.rate(),
33146                rate,
33147                "RateLimit::rate must return :politicas :rate-limit :rate \
33148                 verbatim (got {}, expected {rate})",
33149                rl.rate(),
33150            );
33151            assert_eq!(
33152                rl.rate(),
33153                rl.rate,
33154                "RateLimit::rate must byte-equal the raw .rate field \
33155                 access across every value in the u32 accept-set",
33156            );
33157        }
33158    }
33159
33160    #[test]
33161    fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
33162        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
33163        // `:rate-limit :rate` zero-floor arm must key off
33164        // [`RateLimit::rate`], not the raw `.rate` field access.
33165        // Structurally: a `RateLimit { rate: 0, window:
33166        // Duration::from_secs(1) }` embedded in a `:politicas
33167        // :rate-limit` slot must surface the `PolicyRateLimitZero`
33168        // refusal exactly, and a `RateLimit { rate: 1, window:
33169        // Duration::from_secs(1) }` (the lower boundary of the
33170        // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
33171        // The pair jointly pins the accessor + validate-gate composition:
33172        // any future silent detour that had the accessor return a fresh
33173        // `1` on the zero arm (a `.rate().max(1)` collapse) would
33174        // silently absorb the `PolicyRateLimitZero` refusal at the
33175        // accessor boundary and the validate gate would accept a
33176        // struct-literal `RateLimit { rate: 0, .. }` — the composition
33177        // pin catches that at caixa-core build time.
33178        //
33179        // Peer of the sibling per-`CircuitBreaker`
33180        // [`CircuitBreaker::max_failures`] (3a74062) /
33181        // [`CircuitBreaker::window`] (373957f) accessor-composition
33182        // pins on the peer required-scalar axes — same "the validate /
33183        // shape-gate predicate must route through the substrate-primitive
33184        // typed dispatch" discipline extended onto the peer
33185        // per-`RateLimit` required-`u32` composition axis.
33186        let mut spec = three_member_spec();
33187        spec.politicas = MeshPolicy {
33188            rate_limit: Some(RateLimit {
33189                rate: 0,
33190                window: Duration::from_secs(1),
33191            }),
33192            ..MeshPolicy::default()
33193        };
33194        assert!(
33195            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
33196            "validate_politicas must reject rate == 0 with \
33197             PolicyRateLimitZero — the accessor and the validate gate \
33198             must route through the same substrate-primitive typed \
33199             dispatch on the :rate zero-floor arm",
33200        );
33201        spec.politicas = MeshPolicy {
33202            rate_limit: Some(RateLimit {
33203                rate: 1,
33204                window: Duration::from_secs(1),
33205            }),
33206            ..MeshPolicy::default()
33207        };
33208        assert!(
33209            spec.validate().is_ok(),
33210            "validate_politicas must accept rate == 1 (the lower \
33211             boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
33212        );
33213    }
33214
33215    #[test]
33216    fn rate_limit_rate_projects_u32_by_copy() {
33217        // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
33218        // `u32` is `Copy` and the accessor must return by value, not by
33219        // reference. Peer of the sibling per-`CircuitBreaker`
33220        // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
33221        // peer required-scalar `:max-failures` axis, extended onto the
33222        // peer per-`RateLimit` required-`u32` copy-invariant shape —
33223        // the accessor's returned `u32` must outlive `&self` (multiple
33224        // calls must return equal values from a dropped-`&self` copy,
33225        // since the returned scalar carries no borrow), and calling the
33226        // accessor twice on the same RateLimit must yield the same
33227        // `u32` verbatim (idempotent, no side effects on `&self`).
33228        //
33229        // Pins against a future silent detour that returned `&u32`
33230        // (which would type-check but silently break every downstream
33231        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
33232        // first parameter is `u32`, and `&u32` would fold to a detached
33233        // copy at the call site with a `*` deref the sibling accessors
33234        // don't need), an accidental `.rate.wrapping_add(0)` detour that
33235        // returned a fresh copy through an arithmetic no-op (breaking a
33236        // future `const fn` regression), or a one-arm-only accessor
33237        // that returned a saturating value on some sentinel input
33238        // (breaking the pass-through invariant the sibling required-
33239        // scalar accessors carry).
33240        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
33241            let rl = RateLimit {
33242                rate,
33243                window: Duration::from_secs(1),
33244            };
33245            let first = rl.rate();
33246            let second = rl.rate();
33247            assert_eq!(
33248                first, second,
33249                "RateLimit::rate must be idempotent — two successive \
33250                 calls on the same &self must return the same u32",
33251            );
33252            assert_eq!(
33253                first, rate,
33254                "RateLimit::rate must return :politicas :rate-limit :rate \
33255                 verbatim by copy — got {first}, expected {rate}",
33256            );
33257        }
33258    }
33259
33260    #[test]
33261    fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
33262        // The canonical per-`:politicas :rate-limit` `:window`
33263        // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
33264        // pin: [`RateLimit::window`] must return the
33265        // `:politicas :rate-limit :window` typed `Duration` verbatim,
33266        // byte-equal to the raw field access across every
33267        // representative value in the accept-set — `Duration::from_secs(1)`
33268        // (the `"s"` canonical window, the lower row of
33269        // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
33270        // [`AplicacaoSpec::validate_politicas`] gate accepts via
33271        // [`is_canonical_rate_limit_window`]),
33272        // `Duration::from_secs(60)` (the `"m"` canonical window, the
33273        // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
33274        // window, the upper row), `Duration::ZERO` (a past-the-guard
33275        // sentinel that pins the accessor doesn't perform a silent
33276        // bounds-collapse into `Duration::from_secs(1)` on the zero
33277        // arm — validate rejects an off-set window through
33278        // `PolicyRateLimitWindowNotCanonical` but the accessor must
33279        // ship the raw slot verbatim so a validate-time gate
33280        // regression surfaces at the emit boundary rather than being
33281        // silently absorbed), `Duration::from_millis(500)` (a
33282        // sub-canonical past-the-guard sentinel that pins the accessor
33283        // doesn't silently normalize a non-canonical fractional
33284        // magnitude onto the nearest canonical row).
33285        //
33286        // Second sub-struct required-scalar accessor pin on the
33287        // `RateLimit` axis — sibling in shape to the just-landed
33288        // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
33289        // accessor pin on the peer per-sub-struct required-axis,
33290        // extended onto the per-`RateLimit` required-`Duration` axis.
33291        // Pins against a future silent detour that re-derived the
33292        // refill period from a peer axis (an accidental
33293        // `Duration::from_secs(self.rate as u64)` collapse that read
33294        // the rate-limit token capacity as a refill-interval
33295        // duration), a `Duration::ZERO → Duration::from_secs(1)`
33296        // canonical-default projection (which would silently absorb
33297        // the `PolicyRateLimitWindowNotCanonical` refusal case at the
33298        // accessor boundary), or a canonical-set-collapsing accessor
33299        // that clamped the return through [`rate_limit_window_unit`]
33300        // (the `AplicacaoSpec::validate` gate owns the canonical-set
33301        // membership; the accessor must ship the raw slot verbatim).
33302        for window in [
33303            Duration::from_secs(1),
33304            Duration::from_secs(60),
33305            Duration::from_secs(3600),
33306            Duration::ZERO,
33307            Duration::from_millis(500),
33308        ] {
33309            let rl = RateLimit { rate: 100, window };
33310            assert_eq!(
33311                rl.window(),
33312                window,
33313                "RateLimit::window must return :politicas :rate-limit :window \
33314                 verbatim (got {:?}, expected {window:?})",
33315                rl.window(),
33316            );
33317            assert_eq!(
33318                rl.window(),
33319                rl.window,
33320                "RateLimit::window must byte-equal the raw .window field \
33321                 access across every value in the Duration accept-set",
33322            );
33323        }
33324    }
33325
33326    #[test]
33327    fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
33328        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
33329        // `:rate-limit :window` canonical-set arm must key off
33330        // [`RateLimit::window`], not the raw `.window` field access.
33331        // Structurally: a `RateLimit { window: Duration::from_millis(500),
33332        // .. }` embedded in a `:politicas :rate-limit` slot must
33333        // surface the `PolicyRateLimitWindowNotCanonical` refusal
33334        // exactly (with the sub-canonical `Duration::from_millis(500)`
33335        // magnitude carried through verbatim), and a `RateLimit
33336        // { window: Duration::from_secs(1), .. }` (the lower row of
33337        // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
33338        // The pair jointly pins the accessor + validate-gate
33339        // composition: any future silent detour that had the accessor
33340        // normalize the off-set window to the nearest canonical row
33341        // (a `.window().max(Duration::from_secs(1))` collapse, or a
33342        // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
33343        // collapse) would silently absorb the
33344        // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
33345        // boundary — including a drift in the error's `window` payload
33346        // (the emit-side diagnostic reader keys off the offending
33347        // magnitude verbatim, so a normalization at the accessor
33348        // boundary would silently pin the wrong magnitude in the
33349        // refusal). The composition pin catches that at caixa-core
33350        // build time.
33351        //
33352        // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
33353        // (7f81a60) accessor-composition pin on the peer required-
33354        // scalar `:rate` axis — same "the validate / shape-gate
33355        // predicate must route through the substrate-primitive typed
33356        // dispatch, and the error payload must project through the
33357        // same accessor" discipline extended onto the peer
33358        // per-`RateLimit` required-`Duration` composition axis.
33359        let mut spec = three_member_spec();
33360        spec.politicas = MeshPolicy {
33361            rate_limit: Some(RateLimit {
33362                rate: 100,
33363                window: Duration::from_millis(500),
33364            }),
33365            ..MeshPolicy::default()
33366        };
33367        match spec.validate() {
33368            Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
33369                assert_eq!(
33370                    window,
33371                    Duration::from_millis(500),
33372                    "PolicyRateLimitWindowNotCanonical must carry the \
33373                     offending :window magnitude verbatim through the \
33374                     accessor — got {window:?}, expected 500ms",
33375                );
33376            }
33377            other => panic!(
33378                "validate_politicas must reject non-canonical :window \
33379                 with PolicyRateLimitWindowNotCanonical — the accessor \
33380                 and the validate gate must route through the same \
33381                 substrate-primitive typed dispatch on the :window \
33382                 canonical-set arm; got {other:?}",
33383            ),
33384        }
33385        spec.politicas = MeshPolicy {
33386            rate_limit: Some(RateLimit {
33387                rate: 100,
33388                window: Duration::from_secs(1),
33389            }),
33390            ..MeshPolicy::default()
33391        };
33392        assert!(
33393            spec.validate().is_ok(),
33394            "validate_politicas must accept window == Duration::from_secs(1) \
33395             (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
33396        );
33397    }
33398
33399    #[test]
33400    fn rate_limit_window_projects_duration_by_copy() {
33401        // The by-copy pin: [`RateLimit::window`] returns `Duration`
33402        // by copy — `Duration` is `Copy` and the accessor must return
33403        // by value, not by reference. Peer of the sibling per-`RateLimit`
33404        // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
33405        // required-scalar `:rate` axis, extended onto the peer
33406        // per-`RateLimit` required-`Duration` copy-invariant shape —
33407        // the accessor's returned `Duration` must outlive `&self`
33408        // (multiple calls must return equal values from a
33409        // dropped-`&self` copy, since the returned scalar carries no
33410        // borrow), and calling the accessor twice on the same
33411        // RateLimit must yield the same `Duration` verbatim
33412        // (idempotent, no side effects on `&self`).
33413        //
33414        // Pins against a future silent detour that returned
33415        // `&Duration` (which would type-check but silently break every
33416        // downstream `Duration`-by-value consumer —
33417        // [`is_canonical_rate_limit_window`]'s first parameter is
33418        // `Duration`, and `&Duration` would fold to a detached copy at
33419        // the call site with a `*` deref the sibling accessors don't
33420        // need), an accidental `.window + Duration::ZERO` detour that
33421        // returned a fresh copy through an arithmetic no-op (breaking
33422        // a future `const fn` regression), or a one-arm-only accessor
33423        // that returned a canonical fallback on some sentinel input
33424        // (breaking the pass-through invariant the sibling required-
33425        // scalar accessors carry).
33426        for window in [
33427            Duration::from_secs(1),
33428            Duration::from_secs(60),
33429            Duration::from_secs(3600),
33430            Duration::ZERO,
33431            Duration::from_millis(500),
33432        ] {
33433            let rl = RateLimit { rate: 100, window };
33434            let first = rl.window();
33435            let second = rl.window();
33436            assert_eq!(
33437                first, second,
33438                "RateLimit::window must be idempotent — two successive \
33439                 calls on the same &self must return the same Duration",
33440            );
33441            assert_eq!(
33442                first, window,
33443                "RateLimit::window must return :politicas :rate-limit :window \
33444                 verbatim by copy — got {first:?}, expected {window:?}",
33445            );
33446        }
33447    }
33448
33449    #[test]
33450    fn placement_estrategia_default_pins_m3_canonical_value() {
33451        // Pin [`PLACEMENT_ESTRATEGIA_DEFAULT`] at
33452        // [`PlacementStrategy::Replicated`] — MESH-COMPOSITION §II.2's
33453        // active-active-across-every-named-cluster arm, the closest
33454        // canonical M3 production reference the substrate carries and
33455        // the arm the caixa-mesh `programs.yaml` fan-out already keys off
33456        // for every un-`:placement`-declared Aplicacao. Pinning the arm
33457        // here surfaces a future rebrand of the M3-canonical
33458        // distribution default (a widening to `Sharded` once the
33459        // substrate discovers hash-keyed distribution as the more
33460        // common production shape, a tightening to `SingleNode` for
33461        // stateful Erlang/OTP distributed-app-takeover semantics
33462        // MESH-COMPOSITION §II.1 names, a per-cluster overlay the
33463        // operator pins through a future `:placement-overrides` slot)
33464        // as a deliberate test edit, not a silent contract migration.
33465        // Peer of the sibling M2 per-supervisor value pins
33466        // [`crate::supervisor::tests::supervisor_estrategia_default_pins_otp_canonical_value`]
33467        // /
33468        // [`crate::supervisor::tests::supervisor_child_restart_default_pins_otp_canonical_value`]
33469        // extended onto the M3 mesh-primitive-defining `:placement
33470        // :estrategia` axis.
33471        assert_eq!(PLACEMENT_ESTRATEGIA_DEFAULT, PlacementStrategy::Replicated);
33472    }
33473
33474    #[test]
33475    fn placement_strategy_default_routes_through_lifted_default() {
33476        // Composition pin: the [`Default for PlacementStrategy`] impl's
33477        // return arm must route through the substrate-canonical
33478        // [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
33479        // a raw `Self::Replicated` arm. Prior to the lift the impl
33480        // carried an inline `Self::Replicated` arm with no compile-time
33481        // link back to the shared M3-canonical `Replicated` arm the
33482        // paired [`Default for Placement`] impl's struct-literal
33483        // `estrategia` field, the serde-side `#[serde(default)]` on
33484        // [`Placement::estrategia`] that resolves an author-omitted
33485        // wire-form `:placement :estrategia` scalar through the impl,
33486        // and the [`crate::manifest::Caixa::aplicacao_view`] fold's
33487        // `.unwrap_or_default()` `Option<Placement>` collapse arm (which
33488        // routes through [`Placement::default`] which routes through the
33489        // strategy default) all key off — so a future rebrand of the
33490        // M3-canonical distribution default would have had to be threaded
33491        // through the `Default` impl and the three peer routes in
33492        // lockstep or the four consumers would silently split. Byte-
33493        // parity against the lifted constant closes the split. Peer of
33494        // the sibling
33495        // [`crate::supervisor::tests::restart_strategy_default_routes_through_lifted_default`]
33496        // /
33497        // [`crate::supervisor::tests::restart_policy_default_routes_through_lifted_default`]
33498        // composition pins on the M2 per-supervisor axes.
33499        assert_eq!(PlacementStrategy::default(), PLACEMENT_ESTRATEGIA_DEFAULT);
33500    }
33501
33502    #[test]
33503    fn placement_default_estrategia_routes_through_lifted_default() {
33504        // Composition pin: the [`Default for Placement`] impl's
33505        // struct-literal `estrategia` field must route through the
33506        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
33507        // `pub const` (either directly, or via the [`PlacementStrategy::default`]
33508        // impl that the sibling
33509        // `placement_strategy_default_routes_through_lifted_default` pin
33510        // already routes onto the constant). Structurally: every
33511        // `Placement::default()` call must yield an `estrategia` field
33512        // byte-equal to the lifted constant so the two paired defaults —
33513        // the [`Default for PlacementStrategy`] impl arm and the
33514        // struct-literal default arm here — cannot silently split on any
33515        // future M3-canonical distribution-default rebrand. Peer of the
33516        // sibling M2
33517        // [`crate::supervisor::tests::supervisor_spec_default_estrategia_routes_through_lifted_default`]
33518        // byte-parity pin on the [`Default for SupervisorSpec`]
33519        // struct-literal `estrategia` field extended onto the M3
33520        // mesh-primitive-defining slot family.
33521        assert_eq!(
33522            Placement::default().estrategia,
33523            PLACEMENT_ESTRATEGIA_DEFAULT,
33524        );
33525    }
33526
33527    #[test]
33528    fn placement_serde_default_estrategia_routes_through_lifted_default() {
33529        // Composition pin: the serde-side `#[serde(default)]` on
33530        // [`Placement::estrategia`] — the wire-format author-omitted
33531        // `:placement :estrategia` arm — must resolve onto the substrate-
33532        // canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const`
33533        // (via the [`Default for PlacementStrategy`] impl the sibling
33534        // `placement_strategy_default_routes_through_lifted_default` pin
33535        // already routes onto the constant). Structurally: a `Placement`
33536        // deserialized from a payload that omits the `estrategia` key
33537        // must yield an `estrategia` field byte-equal to the lifted
33538        // constant, so the wire-format author-omitted arm and the
33539        // [`PlacementStrategy::default`] impl arm cannot silently split
33540        // on any future M3-canonical distribution-default rebrand. Peer
33541        // of the sibling M2
33542        // [`crate::supervisor::tests::child_spec_serde_default_restart_routes_through_lifted_default`]
33543        // byte-parity pin on the wire-format author-omitted `:children
33544        // :restart` scalar extended onto the M3 mesh-primitive-defining
33545        // slot family.
33546        let omitted: Placement = serde_json::from_str("{}")
33547            .expect("Placement must deserialize with the estrategia key omitted");
33548        assert_eq!(
33549            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
33550            "an author-omitted :placement :estrategia slot must degrade onto \
33551             the PLACEMENT_ESTRATEGIA_DEFAULT typed pub const (got \
33552             {:?}, expected {:?})",
33553            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
33554        );
33555    }
33556
33557    // ── contrato_target_ctors! fold pins ────────────────────────────────
33558    //
33559    // Fixture edge triple + payload-field-name label pair for every
33560    // `contrato_target_ctors!`-generated ctor pin below. Kept as
33561    // non-default `("cart", "catalog", "wasi:http/proxy")` +
33562    // `WitTarget::HTTP_FIELD_NAME` so a byte-equality mistake against
33563    // the fixture default doesn't silently pass. Peer of the sibling
33564    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
33565    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
33566    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
33567    // `missing_entry_ctor_matches_struct_literal_wrap` /
33568    // `<slot>_ctor_matches_tuple_literal_wrap` equivalence pins on the
33569    // four `LayoutError` constructor families each closed on their
33570    // sibling envelopes.
33571    fn contrato_target_ctor_fixture() -> (String, String, String, &'static str) {
33572        (
33573            "cart".to_string(),
33574            "catalog".to_string(),
33575            "wasi:http/proxy".to_string(),
33576            WitTarget::HTTP_FIELD_NAME,
33577        )
33578    }
33579
33580    #[test]
33581    fn contrato_wrong_target_ctor_matches_struct_literal_wrap() {
33582        // Equivalence pin: the ctor produces byte-equal
33583        // `AplicacaoError::ContratoWrongTarget` to the pre-lift open-
33584        // coded struct-literal on the same edge fixture, so the fold
33585        // cannot silently drift on any future field-addition /
33586        // reordering / string-conversion tweak on the variant. Peer of
33587        // the sibling `entrada_host_invalid_ctor_matches_struct_literal_wrap`
33588        // (17dd504) / the four `LayoutError` family equivalence pins.
33589        let (de, para, wit, expected) = contrato_target_ctor_fixture();
33590        let lifted = AplicacaoError::contrato_wrong_target(
33591            (de.clone(), para.clone(), wit.clone()),
33592            expected,
33593        );
33594        let struct_literal = AplicacaoError::ContratoWrongTarget {
33595            de,
33596            para,
33597            wit,
33598            expected,
33599        };
33600        assert_eq!(lifted, struct_literal);
33601    }
33602
33603    #[test]
33604    fn contrato_missing_target_ctor_matches_struct_literal_wrap() {
33605        // Equivalence pin peer of the sibling
33606        // `contrato_wrong_target_ctor_matches_struct_literal_wrap` above
33607        // on the paired `ContratoMissingTarget` variant of the same
33608        // four-slot envelope shape the `contrato_target_ctors!` macro
33609        // closes.
33610        let (de, para, wit, expected) = contrato_target_ctor_fixture();
33611        let lifted = AplicacaoError::contrato_missing_target(
33612            (de.clone(), para.clone(), wit.clone()),
33613            expected,
33614        );
33615        let struct_literal = AplicacaoError::ContratoMissingTarget {
33616            de,
33617            para,
33618            wit,
33619            expected,
33620        };
33621        assert_eq!(lifted, struct_literal);
33622    }
33623
33624    #[test]
33625    fn contrato_target_ctors_route_edge_triple_through_verbatim() {
33626        // Routing pin: the `(de, para, wit)` triple threads verbatim
33627        // onto same-named fields on both generated ctors, no wrapper-
33628        // side lowercase / trim / re-order. Sweeps a non-default triple
33629        // (`"cart-svc" → "catalog-v2"`, `"nats:pub-sub"`) so any
33630        // wrapper-side transformation surfaces here rather than at a
33631        // downstream diagnostic-shape drift. Sibling of
33632        // `entrada_host_invalid_ctor_routes_host_through_to_string`
33633        // (17dd504) on the paired triple-carrying envelope.
33634        let edge = (
33635            "cart-svc".to_string(),
33636            "catalog-v2".to_string(),
33637            "nats:pub-sub".to_string(),
33638        );
33639        let wrong =
33640            AplicacaoError::contrato_wrong_target(edge.clone(), WitTarget::PUBSUB_FIELD_NAME);
33641        let missing = AplicacaoError::contrato_missing_target(edge, WitTarget::PUBSUB_FIELD_NAME);
33642        let AplicacaoError::ContratoWrongTarget {
33643            de: wde,
33644            para: wpara,
33645            wit: wwit,
33646            ..
33647        } = wrong
33648        else {
33649            panic!("contrato_wrong_target must construct the ContratoWrongTarget variant");
33650        };
33651        let AplicacaoError::ContratoMissingTarget {
33652            de: mde,
33653            para: mpara,
33654            wit: mwit,
33655            ..
33656        } = missing
33657        else {
33658            panic!("contrato_missing_target must construct the ContratoMissingTarget variant");
33659        };
33660        assert_eq!(wde, "cart-svc");
33661        assert_eq!(wpara, "catalog-v2");
33662        assert_eq!(wwit, "nats:pub-sub");
33663        assert_eq!(mde, "cart-svc");
33664        assert_eq!(mpara, "catalog-v2");
33665        assert_eq!(mwit, "nats:pub-sub");
33666    }
33667
33668    #[test]
33669    fn contrato_target_ctors_route_expected_through_verbatim() {
33670        // Routing pin: the `expected: &'static str` label threads
33671        // verbatim (identity, not copy-and-transform) onto the
33672        // `expected` field of both variants, so the four canonical
33673        // labels [`WitTarget::HTTP_FIELD_NAME`] /
33674        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
33675        // / [`WitTarget::CAPABILITY_EXPECTED`] survive the fold as
33676        // pointer-equal (not merely value-equal) references — a wrapper-
33677        // side `.to_string()` / `Cow::Owned` promotion would break the
33678        // `&'static str` contract downstream consumers depend on.
33679        for label in [
33680            WitTarget::HTTP_FIELD_NAME,
33681            WitTarget::PUBSUB_FIELD_NAME,
33682            WitTarget::STORE_FIELD_NAME,
33683            WitTarget::CAPABILITY_EXPECTED,
33684        ] {
33685            let (de, para, wit, _) = contrato_target_ctor_fixture();
33686            let wrong = AplicacaoError::contrato_wrong_target(
33687                (de.clone(), para.clone(), wit.clone()),
33688                label,
33689            );
33690            let missing = AplicacaoError::contrato_missing_target((de, para, wit), label);
33691            match wrong {
33692                AplicacaoError::ContratoWrongTarget { expected, .. } => {
33693                    assert!(
33694                        std::ptr::eq(expected.as_ptr(), label.as_ptr())
33695                            && expected.len() == label.len(),
33696                        "contrato_wrong_target must thread the &'static str \
33697                         label pointer-equal onto the `expected` field \
33698                         (label = {label:?})",
33699                    );
33700                }
33701                other => panic!("expected ContratoWrongTarget, got {other:?}"),
33702            }
33703            match missing {
33704                AplicacaoError::ContratoMissingTarget { expected, .. } => {
33705                    assert!(
33706                        std::ptr::eq(expected.as_ptr(), label.as_ptr())
33707                            && expected.len() == label.len(),
33708                        "contrato_missing_target must thread the &'static \
33709                         str label pointer-equal onto the `expected` field \
33710                         (label = {label:?})",
33711                    );
33712                }
33713                other => panic!("expected ContratoMissingTarget, got {other:?}"),
33714            }
33715        }
33716    }
33717
33718    // ── contrato_empty_pair_ctors! fold pins ────────────────────────────
33719    //
33720    // Fixture edge pair for every `contrato_empty_pair_ctors!`-generated
33721    // ctor pin below. Kept as non-default `("cart", "catalog")` so a
33722    // byte-equality mistake against the fixture default doesn't silently
33723    // pass. Peer of the sibling `contrato_target_ctor_fixture` (14b81d5,
33724    // triple + expected-label envelope on
33725    // `contrato_target_ctors!`) / `entrada_host_invalid_ctor_matches_
33726    // struct_literal_wrap` (17dd504, host + reason envelope on
33727    // `entrada_host_invalid`) / the four `LayoutError` family
33728    // equivalence pins.
33729    fn contrato_empty_pair_ctor_fixture() -> (String, String) {
33730        ("cart".to_string(), "catalog".to_string())
33731    }
33732
33733    #[test]
33734    fn empty_wit_ctor_matches_struct_literal_wrap() {
33735        // Equivalence pin: the ctor produces byte-equal
33736        // `AplicacaoError::EmptyWit` to the pre-lift open-coded
33737        // struct-literal on the same edge pair, so the fold cannot
33738        // silently drift on any future field-addition / reordering /
33739        // string-conversion tweak on the variant. Peer of the sibling
33740        // `contrato_wrong_target_ctor_matches_struct_literal_wrap`
33741        // (14b81d5) / `entrada_host_invalid_ctor_matches_struct_literal_wrap`
33742        // (17dd504) / the four `LayoutError` family equivalence pins.
33743        let (de, para) = contrato_empty_pair_ctor_fixture();
33744        let lifted = AplicacaoError::empty_wit((de.clone(), para.clone()));
33745        let struct_literal = AplicacaoError::EmptyWit { de, para };
33746        assert_eq!(lifted, struct_literal);
33747    }
33748
33749    #[test]
33750    fn contrato_endpoint_empty_ctor_matches_struct_literal_wrap() {
33751        // Equivalence pin peer of the sibling
33752        // `empty_wit_ctor_matches_struct_literal_wrap` above on the
33753        // paired `ContratoEndpointEmpty` variant of the same two-slot
33754        // envelope shape the `contrato_empty_pair_ctors!` macro closes.
33755        let (de, para) = contrato_empty_pair_ctor_fixture();
33756        let lifted = AplicacaoError::contrato_endpoint_empty((de.clone(), para.clone()));
33757        let struct_literal = AplicacaoError::ContratoEndpointEmpty { de, para };
33758        assert_eq!(lifted, struct_literal);
33759    }
33760
33761    #[test]
33762    fn contrato_subject_empty_ctor_matches_struct_literal_wrap() {
33763        // Equivalence pin peer of the sibling
33764        // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
33765        // above on the paired `ContratoSubjectEmpty` variant of the
33766        // same two-slot envelope shape.
33767        let (de, para) = contrato_empty_pair_ctor_fixture();
33768        let lifted = AplicacaoError::contrato_subject_empty((de.clone(), para.clone()));
33769        let struct_literal = AplicacaoError::ContratoSubjectEmpty { de, para };
33770        assert_eq!(lifted, struct_literal);
33771    }
33772
33773    #[test]
33774    fn contrato_slot_empty_ctor_matches_struct_literal_wrap() {
33775        // Equivalence pin peer of the sibling
33776        // `contrato_subject_empty_ctor_matches_struct_literal_wrap`
33777        // above on the paired `ContratoSlotEmpty` variant of the same
33778        // two-slot envelope shape.
33779        let (de, para) = contrato_empty_pair_ctor_fixture();
33780        let lifted = AplicacaoError::contrato_slot_empty((de.clone(), para.clone()));
33781        let struct_literal = AplicacaoError::ContratoSlotEmpty { de, para };
33782        assert_eq!(lifted, struct_literal);
33783    }
33784
33785    #[test]
33786    fn contrato_empty_pair_ctors_route_edge_pair_through_verbatim() {
33787        // Routing pin: the `(de, para)` pair threads verbatim onto
33788        // same-named fields on all four generated ctors, no wrapper-
33789        // side lowercase / trim / re-order. Sweeps a non-default pair
33790        // (`"cart-svc" → "catalog-v2"`) so any wrapper-side
33791        // transformation surfaces here rather than at a downstream
33792        // diagnostic-shape drift. Sibling of
33793        // `contrato_target_ctors_route_edge_triple_through_verbatim`
33794        // (14b81d5) on the paired triple-carrying envelope and of
33795        // `entrada_host_invalid_ctor_routes_host_through_to_string`
33796        // (17dd504) on the sibling `{ host, reason }` envelope.
33797        let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
33798        let variants: [(AplicacaoError, &'static str); 4] = [
33799            (AplicacaoError::empty_wit(edge.clone()), "EmptyWit"),
33800            (
33801                AplicacaoError::contrato_endpoint_empty(edge.clone()),
33802                "ContratoEndpointEmpty",
33803            ),
33804            (
33805                AplicacaoError::contrato_subject_empty(edge.clone()),
33806                "ContratoSubjectEmpty",
33807            ),
33808            (
33809                AplicacaoError::contrato_slot_empty(edge.clone()),
33810                "ContratoSlotEmpty",
33811            ),
33812        ];
33813        for (built, label) in variants {
33814            let (de, para) = match built {
33815                AplicacaoError::EmptyWit { de, para }
33816                | AplicacaoError::ContratoEndpointEmpty { de, para }
33817                | AplicacaoError::ContratoSubjectEmpty { de, para }
33818                | AplicacaoError::ContratoSlotEmpty { de, para } => (de, para),
33819                other => panic!("expected {label} pair variant, got {other:?}"),
33820            };
33821            assert_eq!(de, "cart-svc", "de field on {label} must thread verbatim");
33822            assert_eq!(
33823                para, "catalog-v2",
33824                "para field on {label} must thread verbatim",
33825            );
33826        }
33827    }
33828
33829    // ── contrato_pair_value_reason_ctors! fold pins ─────────────────────
33830    //
33831    // Fixture edge pair + value + reason for every
33832    // `contrato_pair_value_reason_ctors!`-generated ctor pin below. Kept
33833    // as non-default `("cart", "catalog")` on the `(de, para)` pair and
33834    // fixed per-axis `<val>` / reason so a byte-equality mistake against
33835    // the fixture default doesn't silently pass. Peer of the sibling
33836    // `contrato_empty_pair_ctor_fixture` (8580068, pair-only envelope on
33837    // `contrato_empty_pair_ctors!`) / `contrato_target_ctor_fixture`
33838    // (14b81d5, triple + expected-label envelope on
33839    // `contrato_target_ctors!`) / `entrada_host_invalid_ctor_matches_
33840    // struct_literal_wrap` (17dd504, host + reason envelope on
33841    // `entrada_host_invalid`).
33842    fn contrato_pair_value_reason_ctor_fixture() -> (String, String) {
33843        ("cart".to_string(), "catalog".to_string())
33844    }
33845
33846    #[test]
33847    fn contrato_endpoint_invalid_ctor_matches_struct_literal_wrap() {
33848        // Equivalence pin: the ctor produces byte-equal
33849        // `AplicacaoError::ContratoEndpointInvalid` to the pre-lift
33850        // open-coded struct-literal on the same
33851        // `(edge_pair, endpoint, reason)` triple, so the fold cannot
33852        // silently drift on any future field-addition / reordering /
33853        // string-conversion tweak on the variant. Peer of the sibling
33854        // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
33855        // (8580068) on the paired two-slot envelope of the same
33856        // `{ de, para, ... }` prefix, and of
33857        // `entrada_host_invalid_ctor_matches_struct_literal_wrap`
33858        // (17dd504) on the sibling `{ <field>: String, reason: String }`
33859        // two-slot envelope.
33860        let (de, para) = contrato_pair_value_reason_ctor_fixture();
33861        let endpoint = "/charge";
33862        let reason = "sample reason text";
33863        let lifted =
33864            AplicacaoError::contrato_endpoint_invalid((de.clone(), para.clone()), endpoint, reason);
33865        let struct_literal = AplicacaoError::ContratoEndpointInvalid {
33866            de,
33867            para,
33868            endpoint: endpoint.to_string(),
33869            reason: reason.to_string(),
33870        };
33871        assert_eq!(lifted, struct_literal);
33872    }
33873
33874    #[test]
33875    fn contrato_subject_invalid_ctor_matches_struct_literal_wrap() {
33876        // Equivalence pin peer of the sibling
33877        // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap`
33878        // above on the paired `ContratoSubjectInvalid` variant of the
33879        // same four-slot envelope shape the
33880        // `contrato_pair_value_reason_ctors!` macro closes.
33881        let (de, para) = contrato_pair_value_reason_ctor_fixture();
33882        let subject = "checkout.events.charge.failed";
33883        let reason = "sample reason text";
33884        let lifted =
33885            AplicacaoError::contrato_subject_invalid((de.clone(), para.clone()), subject, reason);
33886        let struct_literal = AplicacaoError::ContratoSubjectInvalid {
33887            de,
33888            para,
33889            subject: subject.to_string(),
33890            reason: reason.to_string(),
33891        };
33892        assert_eq!(lifted, struct_literal);
33893    }
33894
33895    #[test]
33896    fn contrato_slot_invalid_ctor_matches_struct_literal_wrap() {
33897        // Equivalence pin peer of the sibling
33898        // `contrato_subject_invalid_ctor_matches_struct_literal_wrap`
33899        // above on the paired `ContratoSlotInvalid` variant of the same
33900        // four-slot envelope shape.
33901        let (de, para) = contrato_pair_value_reason_ctor_fixture();
33902        let slot = "checkout/$orderId";
33903        let reason = "sample reason text";
33904        let lifted =
33905            AplicacaoError::contrato_slot_invalid((de.clone(), para.clone()), slot, reason);
33906        let struct_literal = AplicacaoError::ContratoSlotInvalid {
33907            de,
33908            para,
33909            slot: slot.to_string(),
33910            reason: reason.to_string(),
33911        };
33912        assert_eq!(lifted, struct_literal);
33913    }
33914
33915    #[test]
33916    fn contrato_wit_invalid_ctor_matches_struct_literal_wrap() {
33917        // Equivalence pin peer of the sibling
33918        // `contrato_slot_invalid_ctor_matches_struct_literal_wrap` above
33919        // on the paired `ContratoWitInvalid` variant of the same four-
33920        // slot envelope shape the `contrato_pair_value_reason_ctors!`
33921        // macro closes. Fold pinned this test lands with the last
33922        // `{ de, para, <field>: String, reason: String }` open-coded
33923        // struct-literal inside [`WitContract::target`] rewritten to
33924        // route through the macro-generated
33925        // [`AplicacaoError::contrato_wit_invalid`] ctor — a byte-mismatch
33926        // between the ctor and the pre-lift struct-literal trips this
33927        // pin ahead of any downstream diagnostic-shape drift on the
33928        // `:contratos :wit` axis.
33929        let (de, para) = contrato_pair_value_reason_ctor_fixture();
33930        let wit = "wasi-http/proxy";
33931        let reason = "sample reason text";
33932        let lifted = AplicacaoError::contrato_wit_invalid((de.clone(), para.clone()), wit, reason);
33933        let struct_literal = AplicacaoError::ContratoWitInvalid {
33934            de,
33935            para,
33936            wit: wit.to_string(),
33937            reason: reason.to_string(),
33938        };
33939        assert_eq!(lifted, struct_literal);
33940    }
33941
33942    #[test]
33943    fn contrato_pair_value_reason_ctors_route_edge_pair_through_verbatim() {
33944        // Routing pin: the `(de, para)` pair threads verbatim onto
33945        // same-named fields on all four generated ctors, no wrapper-
33946        // side lowercase / trim / re-order. Sweeps a non-default pair
33947        // (`"cart-svc" → "catalog-v2"`) so any wrapper-side
33948        // transformation surfaces here rather than at a downstream
33949        // diagnostic-shape drift. Sibling of
33950        // `contrato_empty_pair_ctors_route_edge_pair_through_verbatim`
33951        // (8580068) on the paired two-slot envelope and of
33952        // `contrato_target_ctors_route_edge_triple_through_verbatim`
33953        // (14b81d5) on the paired triple-carrying envelope.
33954        let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
33955        let variants: [(AplicacaoError, &'static str); 4] = [
33956            (
33957                AplicacaoError::contrato_endpoint_invalid(edge.clone(), "/x", "r"),
33958                "ContratoEndpointInvalid",
33959            ),
33960            (
33961                AplicacaoError::contrato_subject_invalid(edge.clone(), "x.y", "r"),
33962                "ContratoSubjectInvalid",
33963            ),
33964            (
33965                AplicacaoError::contrato_slot_invalid(edge.clone(), "x/y", "r"),
33966                "ContratoSlotInvalid",
33967            ),
33968            (
33969                AplicacaoError::contrato_wit_invalid(edge.clone(), "wasi:http/proxy", "r"),
33970                "ContratoWitInvalid",
33971            ),
33972        ];
33973        for (built, label) in variants {
33974            let (de, para) = match built {
33975                AplicacaoError::ContratoEndpointInvalid { de, para, .. }
33976                | AplicacaoError::ContratoSubjectInvalid { de, para, .. }
33977                | AplicacaoError::ContratoSlotInvalid { de, para, .. }
33978                | AplicacaoError::ContratoWitInvalid { de, para, .. } => (de, para),
33979                other => panic!("expected {label} pair variant, got {other:?}"),
33980            };
33981            assert_eq!(de, "cart-svc", "de field on {label} must thread verbatim");
33982            assert_eq!(
33983                para, "catalog-v2",
33984                "para field on {label} must thread verbatim",
33985            );
33986        }
33987    }
33988
33989    #[test]
33990    fn contrato_pair_value_reason_ctors_route_reason_through_into_uniformly() {
33991        // Cross-arm invariance pin — the four ctors all route
33992        // `reason: impl Into<String>` verbatim onto their respective
33993        // typed variants through the shared
33994        // [`contrato_pair_value_reason_ctors!`] macro. Sweeps a fixture
33995        // pair (`&str` literal, `format!` output) against every ctor to
33996        // pin that no per-arm wrapper transformation drifted in against
33997        // the uniform macro-generated body. Peer of
33998        // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
33999        // (981060b) on the sibling two-slot envelope's cross-arm sweep.
34000        let edge = || ("cart".to_string(), "catalog".to_string());
34001        let via_literal = "literal reason text";
34002        let via_format = format!("{} reason text", "literal");
34003        assert_eq!(
34004            AplicacaoError::contrato_endpoint_invalid(edge(), "/e", via_literal),
34005            AplicacaoError::contrato_endpoint_invalid(edge(), "/e", via_format.clone()),
34006        );
34007        assert_eq!(
34008            AplicacaoError::contrato_subject_invalid(edge(), "s.t", via_literal),
34009            AplicacaoError::contrato_subject_invalid(edge(), "s.t", via_format.clone()),
34010        );
34011        assert_eq!(
34012            AplicacaoError::contrato_slot_invalid(edge(), "k/v", via_literal),
34013            AplicacaoError::contrato_slot_invalid(edge(), "k/v", via_format.clone()),
34014        );
34015        assert_eq!(
34016            AplicacaoError::contrato_wit_invalid(edge(), "wasi:http/proxy", via_literal),
34017            AplicacaoError::contrato_wit_invalid(edge(), "wasi:http/proxy", via_format),
34018        );
34019    }
34020
34021    // ── contrato_endpoint_not_absolute standalone ctor pins ─────────────
34022    //
34023    // Fail-before-pass-after pins for the standalone
34024    // [`AplicacaoError::contrato_endpoint_not_absolute`] inherent ctor
34025    // (see the paired doc-block above the ctor definition) — the fold of
34026    // the last open-coded three-slot `{ de, para, endpoint: <val>
34027    // .to_string() }` struct-literal inside [`WitContract::target`]'s
34028    // HTTP-arm leading-slash gate onto one substrate primitive on the
34029    // envelope. A byte-mismatched ctor body would trip the equivalence
34030    // pin first, ahead of any downstream diagnostic-shape drift.
34031    //
34032    // Peer of the sibling standalone-ctor equivalence pins on the peer
34033    // one-off variants across caixa-core:
34034    // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap` +
34035    // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap` above
34036    // on the paired two-slot and four-slot per-`:contratos :endpoint`
34037    // envelopes; `child_caixa_invalid_ctor_matches_struct_literal_wrap`
34038    // and `child_versao_invalid_ctor_matches_struct_literal_wrap`
34039    // (d2ef2ec) on the sibling `SupervisorError` `{ caixa, [versao,]
34040    // reason }` two- and three-slot envelopes; the
34041    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` (17dd504)
34042    // pin on the sibling standalone `{ host, reason }` two-slot ctor.
34043    fn contrato_endpoint_not_absolute_ctor_fixture() -> (String, String) {
34044        ("cart".to_string(), "catalog".to_string())
34045    }
34046
34047    #[test]
34048    fn contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap() {
34049        // Equivalence pin: the ctor produces byte-equal
34050        // `AplicacaoError::ContratoEndpointNotAbsolute` to the pre-lift
34051        // open-coded struct-literal on the same `(edge_pair, endpoint)`
34052        // pair, so the fold cannot silently drift on any future
34053        // field-addition / reordering / string-conversion tweak on the
34054        // variant. Same equivalence-pin shape as the sibling
34055        // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
34056        // (8580068) on the paired two-slot envelope and
34057        // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap`
34058        // (14e13f1) on the paired four-slot envelope of the same
34059        // `{ de, para, ... }`-prefix `:endpoint` axis.
34060        let (de, para) = contrato_endpoint_not_absolute_ctor_fixture();
34061        let endpoint = "charge";
34062        let lifted =
34063            AplicacaoError::contrato_endpoint_not_absolute((de.clone(), para.clone()), endpoint);
34064        let struct_literal = AplicacaoError::ContratoEndpointNotAbsolute {
34065            de,
34066            para,
34067            endpoint: endpoint.to_string(),
34068        };
34069        assert_eq!(lifted, struct_literal);
34070    }
34071
34072    #[test]
34073    fn contrato_endpoint_not_absolute_ctor_routes_edge_pair_through_verbatim() {
34074        // Routing pin on the `(de, para)` axis: sweep a non-default
34075        // pair (`"cart-svc" → "catalog-v2"`) so any wrapper-side
34076        // lowercase / trim / re-order surfaces here rather than at a
34077        // downstream diagnostic-shape drift. Peer of
34078        // `contrato_empty_pair_ctors_route_edge_pair_through_verbatim`
34079        // (8580068) on the paired two-slot envelope and
34080        // `contrato_pair_value_reason_ctors_route_edge_pair_through_verbatim`
34081        // (14e13f1) on the paired four-slot envelope of the same
34082        // `{ de, para, ... }`-prefix `:contratos` axis.
34083        let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
34084        let built = AplicacaoError::contrato_endpoint_not_absolute(edge, "charge");
34085        match built {
34086            AplicacaoError::ContratoEndpointNotAbsolute { de, para, .. } => {
34087                assert_eq!(de, "cart-svc", "de field must thread verbatim");
34088                assert_eq!(para, "catalog-v2", "para field must thread verbatim");
34089            }
34090            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
34091        }
34092    }
34093
34094    #[test]
34095    fn contrato_endpoint_not_absolute_ctor_routes_endpoint_through_to_string() {
34096        // Routing pin on the `endpoint: &str` axis: sweep a non-default
34097        // value (`"charge"` — no leading `/`, the exact shape the
34098        // [`WitContract::target`] HTTP-arm leading-slash gate rejects)
34099        // through the sole payload-carrier constructor axis so any
34100        // wrapper-side transformation on the `endpoint.to_string()`
34101        // one-field construction surfaces here rather than at a
34102        // downstream diagnostic-shape mismatch. Sibling of
34103        // `contrato_pair_value_reason_ctors_route_reason_through_into_uniformly`
34104        // (14e13f1) on the sibling four-slot envelope's payload-carrier
34105        // routing pin.
34106        let edge = || ("cart".to_string(), "catalog".to_string());
34107        let via_literal = "charge";
34108        let via_string = String::from("charge");
34109        assert_eq!(
34110            AplicacaoError::contrato_endpoint_not_absolute(edge(), via_literal),
34111            AplicacaoError::contrato_endpoint_not_absolute(edge(), via_string.as_str()),
34112        );
34113    }
34114
34115    // ── contrato_self_loop standalone ctor pins ─────────────────────────
34116    //
34117    // Fail-before-pass-after pins for the standalone
34118    // [`AplicacaoError::contrato_self_loop`] inherent ctor (see the paired
34119    // doc-block above the ctor definition) — the fold of the last
34120    // open-coded two-slot `{ caixa: <ct>.source().to_string(), wit:
34121    // <ct>.world_ref().to_string() }` struct-literal inside
34122    // [`AplicacaoSpec::validate_contratos`]'s per-`:contratos` self-edge
34123    // arm onto one substrate primitive on the [`AplicacaoError`]
34124    // envelope, projecting through the paired [`WitContract::source`] /
34125    // [`WitContract::world_ref`] scalar accessors on the substrate
34126    // primitive. A byte-mismatched ctor body would trip the equivalence
34127    // pin first, ahead of any downstream diagnostic-shape drift.
34128    //
34129    // Peer of the sibling standalone-ctor equivalence pins on the peer
34130    // one-off variants across caixa-core:
34131    // `contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap`
34132    // (cdf1a2c) above on the paired three-slot `{ de, para, endpoint }`
34133    // envelope, the sibling
34134    // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap` +
34135    // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap` on
34136    // the paired two-slot and four-slot per-`:contratos :endpoint`
34137    // envelopes, and the sibling
34138    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` (17dd504)
34139    // pin on the sibling standalone `{ host, reason }` two-slot ctor.
34140    fn contrato_self_loop_ctor_fixture() -> WitContract {
34141        WitContract {
34142            de: "cart".to_string(),
34143            para: "cart".to_string(),
34144            wit: "wasi:http/proxy".to_string(),
34145            endpoint: Some("/self".to_string()),
34146            subject: None,
34147            slot: None,
34148        }
34149    }
34150
34151    #[test]
34152    fn contrato_self_loop_ctor_matches_struct_literal_wrap() {
34153        // Equivalence pin: the ctor produces byte-equal
34154        // `AplicacaoError::ContratoSelfLoop` to the pre-lift open-coded
34155        // struct-literal that read the same two fields through
34156        // [`WitContract::source`] and [`WitContract::world_ref`]. Guards
34157        // any future field-addition / reordering / string-conversion
34158        // tweak on the variant. Same equivalence-pin shape as the
34159        // sibling `contrato_endpoint_not_absolute_ctor_matches_
34160        // struct_literal_wrap` (cdf1a2c) on the paired three-slot
34161        // per-`:contratos :endpoint` envelope.
34162        let contract = contrato_self_loop_ctor_fixture();
34163        let lifted = AplicacaoError::contrato_self_loop(&contract);
34164        let struct_literal = AplicacaoError::ContratoSelfLoop {
34165            caixa: contract.source().to_string(),
34166            wit: contract.world_ref().to_string(),
34167        };
34168        assert_eq!(lifted, struct_literal);
34169    }
34170
34171    #[test]
34172    fn contrato_self_loop_ctor_routes_source_and_world_ref_through_verbatim() {
34173        // Routing pin sweeping non-default `caixa` and `:wit` values
34174        // (`"catalog-v2"` / `"nats:pub-sub"`) through the paired
34175        // [`WitContract::source`] / [`WitContract::world_ref`] accessor
34176        // axes so any wrapper-side lowercase / trim / re-order surfaces
34177        // here rather than at a downstream diagnostic-shape drift.
34178        // Peer of the sibling
34179        // `contrato_endpoint_not_absolute_ctor_routes_edge_pair_through_verbatim`
34180        // (cdf1a2c) routing pin on the sibling three-slot envelope.
34181        let contract = WitContract {
34182            de: "catalog-v2".to_string(),
34183            para: "catalog-v2".to_string(),
34184            wit: "nats:pub-sub".to_string(),
34185            endpoint: None,
34186            subject: Some("orders.>".to_string()),
34187            slot: None,
34188        };
34189        let built = AplicacaoError::contrato_self_loop(&contract);
34190        match built {
34191            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
34192                assert_eq!(
34193                    caixa, "catalog-v2",
34194                    "caixa slot must thread WitContract::source() verbatim"
34195                );
34196                assert_eq!(
34197                    wit, "nats:pub-sub",
34198                    "wit slot must thread WitContract::world_ref() verbatim"
34199                );
34200            }
34201            other => panic!("expected ContratoSelfLoop, got {other:?}"),
34202        }
34203    }
34204
34205    #[test]
34206    fn contrato_self_loop_ctor_projects_source_field_not_destination() {
34207        // Accessor-fidelity pin: the ctor's `caixa` slot keys off the
34208        // [`WitContract::source`] accessor (matching the pre-lift open-
34209        // coded body's field selection), not [`WitContract::destination`].
34210        // Under today's `WitContract::is_self_loop()`-gated call site
34211        // the two are equal by that predicate's own contract, but a
34212        // future consumer that constructs the ctor against a not-yet-
34213        // gated candidate contract — an M4
34214        // `mesh.pleme.io/v1alpha1/Aplicacao` CR admission webhook re-
34215        // checking a per-`(:de, :para)`-patched candidate before the
34216        // self-loop gate re-fires, a per-tenant per-Aplicacao overlay
34217        // resolver rejecting a self-edge introduced by a cluster-local
34218        // `:contratos` override — needs the pre-lift field selection
34219        // pinned so a silent `.destination()` swap at the ctor body
34220        // surfaces here rather than at a downstream diagnostic mis-
34221        // attribution far from the self-loop diagnostic's owner
34222        // (the `caller` side per MESH-COMPOSITION §III.1's typed edge
34223        // direction).
34224        //
34225        // Deliberately constructs a non-self-loop pair (`"cart" →
34226        // "catalog"`) so the two accessors yield distinct bytes on the
34227        // fixture — a `.destination()` swap at the ctor body would land
34228        // `"catalog"` in the `caixa` slot instead of `"cart"` and trip
34229        // the assertion here.
34230        let contract = WitContract {
34231            de: "cart".to_string(),
34232            para: "catalog".to_string(),
34233            wit: "wasi:http/proxy".to_string(),
34234            endpoint: Some("/charge".to_string()),
34235            subject: None,
34236            slot: None,
34237        };
34238        let built = AplicacaoError::contrato_self_loop(&contract);
34239        match built {
34240            AplicacaoError::ContratoSelfLoop { caixa, .. } => {
34241                assert_eq!(
34242                    caixa, "cart",
34243                    "caixa slot must project WitContract::source() (not destination)"
34244                );
34245            }
34246            other => panic!("expected ContratoSelfLoop, got {other:?}"),
34247        }
34248    }
34249
34250    // Pin the four-slot `{ de, para, wit, target }` per-`:contratos`
34251    // whole-edge-dedup sibling of the two-slot per-`:contratos` envelope
34252    // family — the sole per-axis ctor projecting through both
34253    // [`WitContract::edge_triple`] (on the leading `de` / `para` / `wit`
34254    // triple) and [`WitTarget::label`] (on the trailing `target` slot).
34255    // Equivalence pin locks the ctor body to the pre-lift struct-literal
34256    // shape under `PartialEq`, so any accessor-side field-selection drift
34257    // or per-arm wrapper transformation surfaces here as a build-time
34258    // test failure rather than at a downstream diagnostic-shape mismatch
34259    // far from the substrate primitive. Peer of the sibling
34260    // `contrato_self_loop_ctor_matches_struct_literal_wrap` (b30edfe)
34261    // equivalence pin on the paired two-slot `{ caixa, wit }` per-self-
34262    // edge envelope's `WitContract`-projection ctor.
34263    #[test]
34264    fn contrato_duplicate_ctor_matches_struct_literal_wrap() {
34265        let contract = contrato_self_loop_ctor_fixture();
34266        let target = contract.target_projected();
34267        let lifted = AplicacaoError::contrato_duplicate(&contract, &target);
34268        let (de, para, wit) = contract.edge_triple();
34269        let struct_literal = AplicacaoError::ContratoDuplicate {
34270            de,
34271            para,
34272            wit,
34273            target: target.label(),
34274        };
34275        assert_eq!(lifted, struct_literal);
34276    }
34277
34278    // Routing pin sweeping a non-self-loop pair (`"cart" → "catalog"`) so
34279    // the paired [`WitContract::edge_triple`] projection's three axes
34280    // (`de`, `para`, `wit`) and the [`WitTarget::label`] projection on
34281    // the `target` axis all yield distinct bytes on the fixture — any
34282    // wrapper-side re-order / accessor-swap on the four axes surfaces
34283    // here rather than at a downstream diagnostic-shape drift. Peer of
34284    // the sibling
34285    // `contrato_self_loop_ctor_routes_source_and_world_ref_through_verbatim`
34286    // (b30edfe) routing pin on the paired two-slot envelope.
34287    #[test]
34288    fn contrato_duplicate_ctor_routes_edge_triple_and_target_label_verbatim() {
34289        let contract = WitContract {
34290            de: "cart".to_string(),
34291            para: "catalog".to_string(),
34292            wit: "wasi:http/proxy".to_string(),
34293            endpoint: Some("/charge".to_string()),
34294            subject: None,
34295            slot: None,
34296        };
34297        let target = contract.target_projected();
34298        let built = AplicacaoError::contrato_duplicate(&contract, &target);
34299        match built {
34300            AplicacaoError::ContratoDuplicate {
34301                de,
34302                para,
34303                wit,
34304                target,
34305            } => {
34306                assert_eq!(
34307                    de, "cart",
34308                    "de slot must thread WitContract::edge_triple().0 verbatim"
34309                );
34310                assert_eq!(
34311                    para, "catalog",
34312                    "para slot must thread WitContract::edge_triple().1 verbatim"
34313                );
34314                assert_eq!(
34315                    wit, "wasi:http/proxy",
34316                    "wit slot must thread WitContract::edge_triple().2 verbatim"
34317                );
34318                assert!(
34319                    target.contains("/charge"),
34320                    "target slot must project through WitTarget::label() \
34321                     (got target = {target:?})"
34322                );
34323            }
34324            other => panic!("expected ContratoDuplicate, got {other:?}"),
34325        }
34326    }
34327
34328    // Per-variant equivalence pins for the [`aplicacao_caixa_only_ctors!`]
34329    // macro definition (see the paired doc-block above the macro definition)
34330    // — every generated `<ctor>(caixa: &str) -> Self` constructor folds the
34331    // uniform `Self::<Variant> { caixa: caixa.to_string() }` one-field
34332    // struct-literal onto one substrate primitive. The four per-variant
34333    // equivalence pins below (fail-before-pass-after by construction — a
34334    // byte-mismatched macro arm would trip its equivalence pin first) lock
34335    // each generated constructor to its struct-literal peer under
34336    // `PartialEq`, so every wire-up in [`WitContract::require_endpoints_in`],
34337    // [`AplicacaoSpec::validate_membros`], and
34338    // [`validate_no_self_membership`] on that variant produces a byte-equal
34339    // `AplicacaoError` to the pre-lift open-coded struct-literal. The
34340    // cross-axis pin that follows (non-default caixa name) routes the sole
34341    // constructor input axis through `.to_string()`, so the fold does not
34342    // silently collapse onto a fixed name.
34343    //
34344    // Peer of the sibling per-variant `<ctor>_matches_struct_literal_wrap`
34345    // and cross-axis `<macro>_route_caixa_through_to_string` pins on the
34346    // sibling `SupervisorError` `{ caixa: String }` envelope (db09650,
34347    // `supervisor_caixa_only_ctors!`), sibling of the peer per-variant +
34348    // cross-axis pins on the peer three `AplicacaoError` sub-family folds
34349    // (14b81d5 / 8580068 / 981060b / 14e13f1), sibling of the peer four
34350    // `LayoutError` families (131ca0d / 0419438 / 1b09f9d / 3fe3dd7), sibling
34351    // of the peer M2 `:behavior` envelope fold (67c31ec,
34352    // `behavior_slot_path_ctors!` `{ slot, path }`), sibling of the peer M2
34353    // `:upgrade-from` envelope folds (8e67041 / 7468ca9), and sibling of the
34354    // peer `DepError` envelope folds (792aa92 / f85f145 / 0e35793).
34355
34356    #[test]
34357    fn contrato_member_missing_ctor_matches_struct_literal_wrap() {
34358        assert_eq!(
34359            AplicacaoError::contrato_member_missing("cart"),
34360            AplicacaoError::ContratoMemberMissing {
34361                caixa: "cart".to_string(),
34362            },
34363            "generated contrato_member_missing ctor must produce byte-equal \
34364             AplicacaoError to the open-coded struct-literal wrap on the \
34365             same &str fixture",
34366        );
34367    }
34368
34369    #[test]
34370    fn membro_versao_empty_ctor_matches_struct_literal_wrap() {
34371        assert_eq!(
34372            AplicacaoError::membro_versao_empty("cart"),
34373            AplicacaoError::MembroVersaoEmpty {
34374                caixa: "cart".to_string(),
34375            },
34376            "generated membro_versao_empty ctor must produce byte-equal \
34377             AplicacaoError to the open-coded struct-literal wrap on the \
34378             same &str fixture",
34379        );
34380    }
34381
34382    #[test]
34383    fn membro_duplicate_ctor_matches_struct_literal_wrap() {
34384        assert_eq!(
34385            AplicacaoError::membro_duplicate("cart"),
34386            AplicacaoError::MembroDuplicate {
34387                caixa: "cart".to_string(),
34388            },
34389            "generated membro_duplicate ctor must produce byte-equal \
34390             AplicacaoError to the open-coded struct-literal wrap on the \
34391             same &str fixture",
34392        );
34393    }
34394
34395    #[test]
34396    fn membro_is_self_aplicacao_ctor_matches_struct_literal_wrap() {
34397        assert_eq!(
34398            AplicacaoError::membro_is_self_aplicacao("checkout"),
34399            AplicacaoError::MembroIsSelfAplicacao {
34400                caixa: "checkout".to_string(),
34401            },
34402            "generated membro_is_self_aplicacao ctor must produce byte-equal \
34403             AplicacaoError to the open-coded struct-literal wrap on the \
34404             same &str fixture",
34405        );
34406    }
34407
34408    #[test]
34409    fn aplicacao_caixa_only_ctors_route_caixa_through_to_string() {
34410        // Cross-axis pin: sweep the sole constructor input axis (`caixa:
34411        // &str`) through a non-default fixture name against every generated
34412        // arm in the [`aplicacao_caixa_only_ctors!`] macro, so any
34413        // wrapper-side lowercase / trim / truncate / re-order on the
34414        // `caixa.to_string()` sole-field construction surfaces here rather
34415        // than at a downstream diagnostic-shape mismatch. Peer of the
34416        // sibling `supervisor_caixa_only_ctors_route_caixa_through_to_string`
34417        // cross-axis pin on the sibling `SupervisorError` `{ caixa: String }`
34418        // envelope (db09650), extended here onto the peer `AplicacaoError`
34419        // `{ caixa: String }` envelope so every substrate-primitive ctor
34420        // family in caixa-core carrying a single-slot `{ caixa: String }`
34421        // shape guarantees the sole-field construction routes the caller's
34422        // `&str` through `.to_string()` verbatim.
34423        let name = "cache-v2";
34424        assert_eq!(
34425            AplicacaoError::contrato_member_missing(name),
34426            AplicacaoError::ContratoMemberMissing {
34427                caixa: name.to_string(),
34428            },
34429        );
34430        assert_eq!(
34431            AplicacaoError::membro_versao_empty(name),
34432            AplicacaoError::MembroVersaoEmpty {
34433                caixa: name.to_string(),
34434            },
34435        );
34436        assert_eq!(
34437            AplicacaoError::membro_duplicate(name),
34438            AplicacaoError::MembroDuplicate {
34439                caixa: name.to_string(),
34440            },
34441        );
34442        assert_eq!(
34443            AplicacaoError::membro_is_self_aplicacao(name),
34444            AplicacaoError::MembroIsSelfAplicacao {
34445                caixa: name.to_string(),
34446            },
34447        );
34448    }
34449
34450    #[test]
34451    fn entrada_path_not_absolute_ctor_matches_struct_literal_wrap() {
34452        assert_eq!(
34453            AplicacaoError::entrada_path_not_absolute("api/cart"),
34454            AplicacaoError::EntradaPathNotAbsolute {
34455                path: "api/cart".to_string(),
34456            },
34457            "generated entrada_path_not_absolute ctor must produce byte-equal \
34458             AplicacaoError to the open-coded struct-literal wrap on the \
34459             same &str fixture",
34460        );
34461    }
34462
34463    #[test]
34464    fn entrada_path_duplicate_ctor_matches_struct_literal_wrap() {
34465        assert_eq!(
34466            AplicacaoError::entrada_path_duplicate("/api/cart"),
34467            AplicacaoError::EntradaPathDuplicate {
34468                path: "/api/cart".to_string(),
34469            },
34470            "generated entrada_path_duplicate ctor must produce byte-equal \
34471             AplicacaoError to the open-coded struct-literal wrap on the \
34472             same &str fixture",
34473        );
34474    }
34475
34476    // ── membro_versao_invalid ctor pins ────────────────────────────────
34477    //
34478    // Per-variant byte-equality + cross-axis routing pins guaranteeing the
34479    // lifted [`AplicacaoError::membro_versao_invalid`] inherent constructor
34480    // produces an `AplicacaoError` structurally identical to the pre-lift
34481    // `Self::MembroVersaoInvalid { caixa: caixa.to_string(), versao:
34482    // versao.to_string(), reason: reason.into() }` open-coded three-slot
34483    // struct-literal on the same `(&str, &str, reason)` fixture. Peer of
34484    // the sibling `child_versao_invalid_ctor_matches_struct_literal_wrap` +
34485    // `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
34486    // pins on the peer `SupervisorError` `{ caixa: String, versao: String,
34487    // reason: String }` envelope's per-`:children :versao` axis (d2ef2ec),
34488    // extended here onto the paired per-`:membros :versao` axis on the
34489    // sibling `AplicacaoError` envelope so both three-slot `{ caixa,
34490    // versao, reason }` per-caixa-versao-invalidation ctors on caixa-core's
34491    // typed-error surface guarantee the shared three-field construction
34492    // routes through one substrate primitive per envelope.
34493
34494    #[test]
34495    fn membro_versao_invalid_ctor_matches_struct_literal_wrap() {
34496        let caixa = "cart";
34497        let versao = "not-a-req";
34498        let reason = "sample reason text";
34499        assert_eq!(
34500            AplicacaoError::membro_versao_invalid(caixa, versao, reason),
34501            AplicacaoError::MembroVersaoInvalid {
34502                caixa: caixa.to_string(),
34503                versao: versao.to_string(),
34504                reason: reason.to_string(),
34505            },
34506            "lifted membro_versao_invalid ctor must produce byte-equal \
34507             AplicacaoError to the open-coded struct-literal wrap on the \
34508             same (&str, &str, reason) fixture",
34509        );
34510    }
34511
34512    #[test]
34513    fn membro_versao_invalid_ctor_routes_caixa_and_versao_through_to_string() {
34514        // Cross-axis pin: sweep the two `&str`-shaped constructor input
34515        // axes (`caixa`, `versao`) through non-default fixtures so any
34516        // wrapper-side lowercase / trim / truncate / re-order on either
34517        // `.to_string()` field construction surfaces here rather than at
34518        // a downstream diagnostic-shape mismatch. Peer of the sibling
34519        // `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
34520        // routing pin on the peer `SupervisorError` envelope.
34521        let caixa = "Cart-V2";
34522        let versao = "0.1.0-alpha+build.42";
34523        let reason = "constructed reason";
34524        let err = AplicacaoError::membro_versao_invalid(caixa, versao, reason);
34525        let AplicacaoError::MembroVersaoInvalid {
34526            caixa: got_caixa,
34527            versao: got_versao,
34528            reason: got_reason,
34529        } = err
34530        else {
34531            panic!("membro_versao_invalid must construct MembroVersaoInvalid variant");
34532        };
34533        assert_eq!(got_caixa, caixa.to_string());
34534        assert_eq!(got_versao, versao.to_string());
34535        assert_eq!(got_reason, reason.to_string());
34536    }
34537
34538    #[test]
34539    fn membro_versao_invalid_ctor_routes_reason_through_into() {
34540        // Route pin: the `reason: impl Into<String>` bound accepts both
34541        // `&str` literals and `format!(…)` / `String` outputs verbatim,
34542        // matching the sibling
34543        // `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
34544        // routing pin on the peer `SupervisorError::child_versao_invalid`.
34545        // Pins the sole `AplicacaoSpec::validate_membros` wire-up's
34546        // `require_valid_versao_requirement`-delivered `reason` closure
34547        // parameter (typed `String`) picks the ctor up without a per-arm
34548        // wrapper transformation, and every future consumer that
34549        // constructs the variant from a `format!(…)` reason surfaces
34550        // byte-equal to the `&str`-literal path.
34551        let caixa = "cart";
34552        let versao = "not-a-req";
34553        let from_literal = AplicacaoError::membro_versao_invalid(caixa, versao, "literal reason");
34554        let from_format =
34555            AplicacaoError::membro_versao_invalid(caixa, versao, format!("{} reason", "literal"));
34556        let from_string =
34557            AplicacaoError::membro_versao_invalid(caixa, versao, "literal reason".to_string());
34558        assert_eq!(from_literal, from_format);
34559        assert_eq!(from_literal, from_string);
34560    }
34561
34562    #[test]
34563    fn aplicacao_path_only_ctors_route_path_through_to_string() {
34564        // Cross-axis pin: sweep the sole constructor input axis (`path:
34565        // &str`) through a non-default fixture path against every generated
34566        // arm in the [`aplicacao_path_only_ctors!`] macro, so any
34567        // wrapper-side lowercase / trim / truncate / re-order on the
34568        // `path.to_string()` sole-field construction surfaces here rather
34569        // than at a downstream diagnostic-shape mismatch. Peer of the
34570        // sibling `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
34571        // cross-axis pin on the peer `AplicacaoError` `{ caixa: String }`
34572        // envelope (d9f6867), extended here onto the sibling
34573        // `AplicacaoError` `{ path: String }` envelope so every substrate-
34574        // primitive ctor family in caixa-core carrying a single-slot
34575        // `{ <slot>: String }` shape guarantees the sole-field construction
34576        // routes the caller's `&str` through `.to_string()` verbatim.
34577        let path = "/api/v2/checkout";
34578        assert_eq!(
34579            AplicacaoError::entrada_path_not_absolute(path),
34580            AplicacaoError::EntradaPathNotAbsolute {
34581                path: path.to_string(),
34582            },
34583        );
34584        assert_eq!(
34585            AplicacaoError::entrada_path_duplicate(path),
34586            AplicacaoError::EntradaPathDuplicate {
34587                path: path.to_string(),
34588            },
34589        );
34590    }
34591
34592    // ── aplicacao_policy_scalar_ctors! per-variant + cross-axis pins ────────
34593    //
34594    // Per-variant byte-equality pins guaranteeing every generated ctor arm in
34595    // the [`aplicacao_policy_scalar_ctors!`] macro produces an `AplicacaoError`
34596    // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
34597    // one-line struct-literal on the same `Copy`-`Duration | u32` fixture, plus
34598    // one cross-axis sweep that routes each per-variant `<field>: <ty>` scalar
34599    // through the sole `$field:ident: $ty:ty` axis the macro exposes so any
34600    // wrapper-side truncation / re-order / silent `.into()` / silent constant-
34601    // substitution on any one variant surfaces here rather than at a downstream
34602    // per-`:politicas` diagnostic-shape drift. Peer of the sibling per-variant
34603    // pins on `aplicacao_field_reason_ctors!` (981060b),
34604    // `aplicacao_caixa_only_ctors!` (d9f6867), `aplicacao_path_only_ctors!`
34605    // (3ba8de6), `contrato_pair_value_reason_ctors!` (14e13f1),
34606    // `contrato_empty_pair_ctors!` (8580068), `contrato_target_ctors!`
34607    // (14b81d5), plus the sibling `DepError` / `SupervisorError` /
34608    // `LayoutError` / `LimitsError` / `BehaviorError` / `UpgradeError`
34609    // per-envelope ctor-macro pins.
34610
34611    #[test]
34612    fn policy_timeout_not_canonical_ctor_matches_struct_literal_wrap() {
34613        let timeout = Duration::from_micros(1_500);
34614        assert_eq!(
34615            AplicacaoError::policy_timeout_not_canonical(timeout),
34616            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
34617            "generated policy_timeout_not_canonical ctor must produce byte-equal \
34618             `AplicacaoError::PolicyTimeoutNotCanonical` to the pre-lift \
34619             struct-literal wrap on the same `Copy`-`Duration` fixture",
34620        );
34621    }
34622
34623    #[test]
34624    fn policy_timeout_exceeds_cap_ctor_matches_struct_literal_wrap() {
34625        let timeout = Duration::from_secs(3_601);
34626        assert_eq!(
34627            AplicacaoError::policy_timeout_exceeds_cap(timeout),
34628            AplicacaoError::PolicyTimeoutExceedsCap { timeout },
34629            "generated policy_timeout_exceeds_cap ctor must produce byte-equal \
34630             `AplicacaoError::PolicyTimeoutExceedsCap` to the pre-lift \
34631             struct-literal wrap on the same `Copy`-`Duration` fixture",
34632        );
34633    }
34634
34635    #[test]
34636    fn policy_retries_exceeds_cap_ctor_matches_struct_literal_wrap() {
34637        let retries = 47_u32;
34638        assert_eq!(
34639            AplicacaoError::policy_retries_exceeds_cap(retries),
34640            AplicacaoError::PolicyRetriesExceedsCap { retries },
34641            "generated policy_retries_exceeds_cap ctor must produce byte-equal \
34642             `AplicacaoError::PolicyRetriesExceedsCap` to the pre-lift \
34643             struct-literal wrap on the same `Copy`-`u32` fixture",
34644        );
34645    }
34646
34647    #[test]
34648    fn policy_breaker_max_failures_exceeds_cap_ctor_matches_struct_literal_wrap() {
34649        let max_failures = 1_337_u32;
34650        assert_eq!(
34651            AplicacaoError::policy_breaker_max_failures_exceeds_cap(max_failures),
34652            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
34653            "generated policy_breaker_max_failures_exceeds_cap ctor must produce \
34654             byte-equal `AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` to \
34655             the pre-lift struct-literal wrap on the same `Copy`-`u32` fixture",
34656        );
34657    }
34658
34659    #[test]
34660    fn policy_breaker_window_not_canonical_ctor_matches_struct_literal_wrap() {
34661        let window = Duration::from_micros(500);
34662        assert_eq!(
34663            AplicacaoError::policy_breaker_window_not_canonical(window),
34664            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
34665            "generated policy_breaker_window_not_canonical ctor must produce \
34666             byte-equal `AplicacaoError::PolicyBreakerWindowNotCanonical` to the \
34667             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
34668        );
34669    }
34670
34671    #[test]
34672    fn policy_breaker_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
34673        let window = Duration::from_secs(3_700);
34674        assert_eq!(
34675            AplicacaoError::policy_breaker_window_exceeds_cap(window),
34676            AplicacaoError::PolicyBreakerWindowExceedsCap { window },
34677            "generated policy_breaker_window_exceeds_cap ctor must produce \
34678             byte-equal `AplicacaoError::PolicyBreakerWindowExceedsCap` to the \
34679             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
34680        );
34681    }
34682
34683    #[test]
34684    fn policy_rate_limit_exceeds_cap_ctor_matches_struct_literal_wrap() {
34685        let rate = 1_000_001_u32;
34686        assert_eq!(
34687            AplicacaoError::policy_rate_limit_exceeds_cap(rate),
34688            AplicacaoError::PolicyRateLimitExceedsCap { rate },
34689            "generated policy_rate_limit_exceeds_cap ctor must produce byte-equal \
34690             `AplicacaoError::PolicyRateLimitExceedsCap` to the pre-lift \
34691             struct-literal wrap on the same `Copy`-`u32` fixture",
34692        );
34693    }
34694
34695    #[test]
34696    fn policy_rate_limit_window_not_canonical_ctor_matches_struct_literal_wrap() {
34697        let window = Duration::from_secs(15);
34698        assert_eq!(
34699            AplicacaoError::policy_rate_limit_window_not_canonical(window),
34700            AplicacaoError::PolicyRateLimitWindowNotCanonical { window },
34701            "generated policy_rate_limit_window_not_canonical ctor must produce \
34702             byte-equal `AplicacaoError::PolicyRateLimitWindowNotCanonical` to \
34703             the pre-lift struct-literal wrap on the same `Copy`-`Duration` \
34704             fixture",
34705        );
34706    }
34707
34708    #[test]
34709    fn aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly() {
34710        // Cross-axis routing pin: sweep each generated `<field>: <ty>`
34711        // constructor input axis through a non-default `Copy` fixture against
34712        // every arm in the [`aplicacao_policy_scalar_ctors!`] macro, so any
34713        // wrapper-side silent `.into()` / silent constant-substitution / silent
34714        // field re-name away from the canonical `timeout | retries |
34715        // max_failures | window | rate` axes on any one variant, or a
34716        // `Duration | u32` axis silently rerouted through some other `Copy`
34717        // coercion, surfaces here rather than at a downstream per-`:politicas`
34718        // diagnostic-shape drift. Peer of the sibling
34719        // `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
34720        // (d9f6867), `aplicacao_path_only_ctors_route_path_through_to_string`
34721        // (3ba8de6), `dep_nome_list_ctors_route_nome_and_list_through_uniformly`
34722        // (6f5e0cd), and `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
34723        // (d2ef2ec) cross-axis routing pins on the peer per-envelope ctor
34724        // families, extended here onto the last M3 per-`:politicas` per-axis
34725        // `AplicacaoError` variant family folded onto a substrate primitive.
34726        //
34727        // Fixtures picked out of each variant's accept-set boundary rather
34728        // than the default value so a silent constant-substitution to `0` /
34729        // `Duration::ZERO` / any per-variant sentinel surfaces here on the
34730        // structural-equality assertion. The two `Duration` fixtures pick the
34731        // sub-millisecond and above-cap ends respectively; the three `u32`
34732        // fixtures pick above-cap magnitudes for `retries` / `max_failures` /
34733        // `rate` respectively (each variant's cap sits well below the fixture
34734        // so the pre-lift struct-literal wrap the fixture is compared against
34735        // is the same shape the pre-lift wire-up produced).
34736        let sub_ms = Duration::from_micros(1_500);
34737        let above_hour = Duration::from_secs(3_700);
34738        let non_canonical_rl_window = Duration::from_secs(15);
34739        assert_eq!(
34740            AplicacaoError::policy_timeout_not_canonical(sub_ms),
34741            AplicacaoError::PolicyTimeoutNotCanonical { timeout: sub_ms },
34742        );
34743        assert_eq!(
34744            AplicacaoError::policy_timeout_exceeds_cap(above_hour),
34745            AplicacaoError::PolicyTimeoutExceedsCap {
34746                timeout: above_hour,
34747            },
34748        );
34749        assert_eq!(
34750            AplicacaoError::policy_retries_exceeds_cap(47),
34751            AplicacaoError::PolicyRetriesExceedsCap { retries: 47 },
34752        );
34753        assert_eq!(
34754            AplicacaoError::policy_breaker_max_failures_exceeds_cap(1_337),
34755            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
34756                max_failures: 1_337,
34757            },
34758        );
34759        assert_eq!(
34760            AplicacaoError::policy_breaker_window_not_canonical(sub_ms),
34761            AplicacaoError::PolicyBreakerWindowNotCanonical { window: sub_ms },
34762        );
34763        assert_eq!(
34764            AplicacaoError::policy_breaker_window_exceeds_cap(above_hour),
34765            AplicacaoError::PolicyBreakerWindowExceedsCap { window: above_hour },
34766        );
34767        assert_eq!(
34768            AplicacaoError::policy_rate_limit_exceeds_cap(1_000_001),
34769            AplicacaoError::PolicyRateLimitExceedsCap { rate: 1_000_001 },
34770        );
34771        assert_eq!(
34772            AplicacaoError::policy_rate_limit_window_not_canonical(non_canonical_rl_window),
34773            AplicacaoError::PolicyRateLimitWindowNotCanonical {
34774                window: non_canonical_rl_window,
34775            },
34776        );
34777    }
34778
34779    #[test]
34780    fn aplicacao_policy_scalar_ctors_are_const_zero_runtime_work() {
34781        // Const-eval pin: the [`aplicacao_policy_scalar_ctors!`] macro spells
34782        // every generated ctor `const fn` so a caller can pin an
34783        // `AplicacaoError` at compile time — the same zero-runtime-work
34784        // property the pre-lift `|<slot>| AplicacaoError::<Variant> { <slot> }`
34785        // closure carried on its `Copy`-pass-through construction path (no
34786        // `.to_string()` / `.into()` allocation, no branching). If any future
34787        // edit silently drops the `const` qualifier from the macro body the
34788        // per-arm `const` bindings below fail to compile, which surfaces the
34789        // regression at the substrate-primitive definition rather than at
34790        // some downstream consumer that had come to rely on the `const`-
34791        // constructibility. Peer of the sibling per-variant
34792        // `_ctor_matches_struct_literal_wrap` pins above on the runtime-
34793        // equality axis; this pin closes the compile-time-const axis on the
34794        // same generated family.
34795        const TIMEOUT_NC: AplicacaoError =
34796            AplicacaoError::policy_timeout_not_canonical(Duration::from_micros(1));
34797        const TIMEOUT_CAP: AplicacaoError =
34798            AplicacaoError::policy_timeout_exceeds_cap(Duration::from_secs(3_601));
34799        const RETRIES_CAP: AplicacaoError = AplicacaoError::policy_retries_exceeds_cap(11);
34800        const MAX_FAIL_CAP: AplicacaoError =
34801            AplicacaoError::policy_breaker_max_failures_exceeds_cap(1_001);
34802        const CB_WIN_NC: AplicacaoError =
34803            AplicacaoError::policy_breaker_window_not_canonical(Duration::from_micros(1));
34804        const CB_WIN_CAP: AplicacaoError =
34805            AplicacaoError::policy_breaker_window_exceeds_cap(Duration::from_secs(3_601));
34806        const RATE_CAP: AplicacaoError = AplicacaoError::policy_rate_limit_exceeds_cap(1_000_001);
34807        const RL_WIN_NC: AplicacaoError =
34808            AplicacaoError::policy_rate_limit_window_not_canonical(Duration::from_secs(15));
34809        assert!(matches!(
34810            TIMEOUT_NC,
34811            AplicacaoError::PolicyTimeoutNotCanonical { .. }
34812        ));
34813        assert!(matches!(
34814            TIMEOUT_CAP,
34815            AplicacaoError::PolicyTimeoutExceedsCap { .. }
34816        ));
34817        assert!(matches!(
34818            RETRIES_CAP,
34819            AplicacaoError::PolicyRetriesExceedsCap { .. }
34820        ));
34821        assert!(matches!(
34822            MAX_FAIL_CAP,
34823            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { .. }
34824        ));
34825        assert!(matches!(
34826            CB_WIN_NC,
34827            AplicacaoError::PolicyBreakerWindowNotCanonical { .. }
34828        ));
34829        assert!(matches!(
34830            CB_WIN_CAP,
34831            AplicacaoError::PolicyBreakerWindowExceedsCap { .. }
34832        ));
34833        assert!(matches!(
34834            RATE_CAP,
34835            AplicacaoError::PolicyRateLimitExceedsCap { .. }
34836        ));
34837        assert!(matches!(
34838            RL_WIN_NC,
34839            AplicacaoError::PolicyRateLimitWindowNotCanonical { .. }
34840        ));
34841    }
34842
34843    // Per-variant equivalence + routing pins for the
34844    // [`AplicacaoError::placement_cluster_duplicate`] standalone ctor
34845    // (see the paired doc-block above the ctor definition) — the
34846    // generated `pub fn placement_cluster_duplicate(cluster: &str) ->
34847    // Self` inherent constructor folds the uniform
34848    // `Self::PlacementClusterDuplicate { cluster: cluster.to_string() }`
34849    // one-field struct-literal onto one substrate primitive. Same
34850    // shape as the sibling
34851    // `contrato_self_loop_ctor_matches_struct_literal_wrap` (b30edfe) /
34852    // `contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap`
34853    // (cdf1a2c) equivalence pins on the paired standalone `AplicacaoError`
34854    // ctors — extended here onto the single-slot per-`:placement
34855    // :clusters` dedup-envelope.
34856
34857    #[test]
34858    fn placement_cluster_duplicate_ctor_matches_struct_literal_wrap() {
34859        // Equivalence pin: the ctor produces byte-equal
34860        // `AplicacaoError::PlacementClusterDuplicate` to the pre-lift
34861        // open-coded struct-literal that read the same field through
34862        // `c.clone()` at the caller site inside
34863        // [`AplicacaoSpec::validate_placement_shape`]. Guards any future
34864        // field-addition / reordering / string-conversion tweak on the
34865        // variant.
34866        let cluster = "rio";
34867        let lifted = AplicacaoError::placement_cluster_duplicate(cluster);
34868        let struct_literal = AplicacaoError::PlacementClusterDuplicate {
34869            cluster: cluster.to_string(),
34870        };
34871        assert_eq!(lifted, struct_literal);
34872    }
34873
34874    #[test]
34875    fn placement_cluster_duplicate_ctor_routes_cluster_through_to_string() {
34876        // Routing pin: sweep the sole constructor input axis
34877        // (`cluster: &str`) through a non-default fixture name so any
34878        // wrapper-side lowercase / trim / truncate / re-order on the
34879        // `cluster.to_string()` sole-field construction surfaces here
34880        // rather than at a downstream diagnostic-shape mismatch. Peer of
34881        // the sibling
34882        // `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
34883        // (d9f6867) cross-axis pin on the sibling one-slot
34884        // `{ caixa: String }` envelope — extended here onto the sibling
34885        // `{ cluster: String }` envelope so the sole `String`-slot
34886        // construction routes the caller's `&str` through `.to_string()`
34887        // verbatim.
34888        let cluster = "sao-paulo-2";
34889        let built = AplicacaoError::placement_cluster_duplicate(cluster);
34890        match built {
34891            AplicacaoError::PlacementClusterDuplicate { cluster: c } => {
34892                assert_eq!(
34893                    c, cluster,
34894                    "cluster slot must thread the caller's `&str` verbatim through .to_string()"
34895                );
34896            }
34897            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
34898        }
34899    }
34900
34901    // Per-variant equivalence + routing pins for the
34902    // [`AplicacaoError::placement_without_clusters`] standalone ctor
34903    // (see the paired doc-block above the ctor definition) — the
34904    // generated `pub const fn placement_without_clusters(placement:
34905    // &Placement) -> Self` inherent constructor folds the uniform
34906    // `Self::PlacementWithoutClusters { estrategia: placement.estrategia()
34907    // }` one-field `Copy`-pass-through struct-literal onto one substrate
34908    // primitive. Same shape as the sibling
34909    // `placement_cluster_duplicate_ctor_matches_struct_literal_wrap`
34910    // (92b1c92) / `contrato_self_loop_ctor_matches_struct_literal_wrap`
34911    // (b30edfe) equivalence pins on the paired standalone `AplicacaoError`
34912    // ctors — extended here onto the one-slot per-`:placement`
34913    // empty-clusters envelope.
34914
34915    #[test]
34916    fn placement_without_clusters_ctor_matches_struct_literal_wrap() {
34917        // Equivalence pin: the ctor produces byte-equal
34918        // `AplicacaoError::PlacementWithoutClusters` to the pre-lift
34919        // open-coded struct-literal that read the same field through
34920        // `p.estrategia()` at the caller site inside
34921        // [`AplicacaoSpec::validate_placement`]. Guards any future
34922        // field-addition / reordering / accessor-return tweak on the
34923        // variant.
34924        let placement = Placement {
34925            estrategia: PlacementStrategy::Replicated,
34926            clusters: vec![],
34927            affinity: None,
34928            shard_key: None,
34929        };
34930        let lifted = AplicacaoError::placement_without_clusters(&placement);
34931        let struct_literal = AplicacaoError::PlacementWithoutClusters {
34932            estrategia: placement.estrategia(),
34933        };
34934        assert_eq!(lifted, struct_literal);
34935    }
34936
34937    #[test]
34938    fn placement_without_clusters_ctor_routes_estrategia_through_accessor() {
34939        // Routing pin: sweep the sole constructor input axis
34940        // (`placement: &Placement`) through every variant in the closed
34941        // [`PlacementStrategy::ALL`] accept-set so any wrapper-side
34942        // re-derivation / off-by-one arm-swap / stale-field read on the
34943        // `placement.estrategia()` sole-field projection surfaces here
34944        // rather than at a downstream diagnostic-shape mismatch. Peer of
34945        // the sibling
34946        // `validate_placement_reads_through_lifted_estrategia_accessor`
34947        // three-consumer coherence pin — extended here onto the ctor
34948        // itself so the accessor-projection posture is byte-witnessed at
34949        // the substrate primitive rather than only at the caller-site
34950        // fan-out. Sweeps all three [`PlacementStrategy`] variants so any
34951        // future addition to the closed accept-set surfaces as an
34952        // exhaustiveness gap on this iteration list.
34953        for estrategia in [
34954            PlacementStrategy::SingleNode,
34955            PlacementStrategy::Replicated,
34956            PlacementStrategy::Sharded,
34957        ] {
34958            let placement = Placement {
34959                estrategia,
34960                clusters: vec![],
34961                affinity: None,
34962                shard_key: None,
34963            };
34964            let built = AplicacaoError::placement_without_clusters(&placement);
34965            match built {
34966                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
34967                    assert_eq!(
34968                        e,
34969                        placement.estrategia(),
34970                        "estrategia slot must thread the caller's `Placement` verbatim \
34971                         through Placement::estrategia() — the ctor reads through the \
34972                         lifted accessor",
34973                    );
34974                    assert_eq!(
34975                        e, estrategia,
34976                        "estrategia slot must byte-equal the fixture-declared variant",
34977                    );
34978                }
34979                other => panic!("expected PlacementWithoutClusters, got {other:?}"),
34980            }
34981        }
34982    }
34983
34984    #[test]
34985    fn placement_without_clusters_ctor_is_const_fn() {
34986        // Fail-before-pass-after pin on
34987        // [`AplicacaoError::placement_without_clusters`]'s `const`-eval-
34988        // surface posture. The ctor threads the paired
34989        // [`Placement::estrategia`] `const fn` `Copy`-scalar accessor's
34990        // return through one `const fn` construction — any future
34991        // accidental downgrade to non-`const` (a `.clone()` on the
34992        // `Copy`-scalar `estrategia:` field expression, an owned-`String`
34993        // materialization on the sibling non-`estrategia:` axis) fails
34994        // `placement_without_clusters_via_const_fn` at caixa-core build
34995        // time with E0015 (`cannot call non-const method`), strictly
34996        // stronger than a runtime `assert!`. Sibling of the peer
34997        // [`aplicacao_policy_scalar_ctors!`] (7ef425e) family's `const fn`
34998        // posture on the sibling per-`:politicas` cap-scalar envelopes
34999        // and the peer [`Placement::estrategia`] const-fn accessor pin at
35000        // [`placement_estrategia_accessor_is_const_fn`] on the paired
35001        // substrate primitive.
35002        const fn placement_without_clusters_via_const_fn(p: &Placement) -> AplicacaoError {
35003            AplicacaoError::placement_without_clusters(p)
35004        }
35005        let placement = Placement {
35006            estrategia: PlacementStrategy::Sharded,
35007            clusters: vec![],
35008            affinity: None,
35009            shard_key: Some("tenantId".into()),
35010        };
35011        assert_eq!(
35012            placement_without_clusters_via_const_fn(&placement),
35013            AplicacaoError::placement_without_clusters(&placement),
35014        );
35015    }
35016
35017    #[test]
35018    fn entrada_member_missing_ctor_matches_struct_literal_wrap() {
35019        // Equivalence pin: the ctor produces byte-equal
35020        // `AplicacaoError::EntradaMemberMissing` to the pre-lift
35021        // open-coded struct-literal that read the same `:para` value
35022        // through `e.destination().to_string()` at the caller site
35023        // inside [`AplicacaoSpec::validate_entrada`]. Guards any future
35024        // field-addition / reordering / accessor-return tweak on the
35025        // variant. Sibling of the peer
35026        // `placement_without_clusters_ctor_matches_struct_literal_wrap`
35027        // and `shard_key_on_non_sharded_ctor_matches_struct_literal_wrap`
35028        // pins on the sibling per-`:placement` envelope, and sibling of
35029        // the peer `contrato_member_missing_ctor_matches_struct_literal_wrap`
35030        // pin on the sibling per-`:membros :caixa` envelope.
35031        let entrada = Entrada {
35032            host: "checkout.quero.cloud".into(),
35033            para: "phantom-shim".into(),
35034            paths: vec!["/api".into()],
35035            port: 8080,
35036        };
35037        let via_ctor = AplicacaoError::entrada_member_missing(&entrada);
35038        let via_literal = AplicacaoError::EntradaMemberMissing {
35039            para: entrada.destination().to_string(),
35040        };
35041        assert_eq!(
35042            via_ctor, via_literal,
35043            "entrada_member_missing(&entrada) must byte-equal the open-coded \
35044             EntradaMemberMissing struct-literal on the same &Entrada fixture"
35045        );
35046        assert_eq!(
35047            via_ctor.to_string(),
35048            via_literal.to_string(),
35049            "Display byte-string must byte-equal the open-coded struct-literal"
35050        );
35051    }
35052
35053    #[test]
35054    fn entrada_member_missing_ctor_routes_para_through_entrada_accessor() {
35055        // Boundary-sweep pin on the ctor's substrate-primitive
35056        // projection: the `para` slot is stored verbatim from
35057        // [`Entrada::destination`] across a representative set of
35058        // `:entrada :para` byte-strings, so any wrapper-side silent
35059        // normalization, `.into()` divergence, accidental field
35060        // rebrand, or per-arm ctor divergence on the sole-field
35061        // projection surfaces at caixa-core build time rather than at
35062        // a downstream diagnostic consumer that reads `err.para` back
35063        // and gets a different value than the one it stored. Peer of
35064        // the sibling
35065        // `shard_key_on_non_sharded_routes_estrategia_through_placement_accessor`
35066        // boundary-sweep pin on the sibling per-`:placement :shard-key`
35067        // envelope and the peer `placement_without_clusters_ctor_routes_estrategia_through_accessor`
35068        // sweep on the sibling per-`:placement` empty-clusters envelope
35069        // — extended here onto the [`Entrada`]-borrow-projected sole
35070        // `para` slot on the sibling per-`:entrada :para` envelope. The
35071        // sweep list carries a mixed set (well-shaped phantom, hyphen-
35072        // digit tail, single-character floor, and the digit-start form
35073        // the peer `accepts_canonical_entrada_para_forms` positive-
35074        // control test also sweeps) so a future silent per-input
35075        // normalization surfaces on the arm that diverges.
35076        for para in [
35077            "phantom-shim",
35078            "cart-v2",
35079            "a",
35080            "c0",
35081            "3rd-party-shim",
35082            "x-1-2-3-4",
35083        ] {
35084            let entrada = Entrada {
35085                host: "checkout.quero.cloud".into(),
35086                para: para.into(),
35087                paths: vec!["/api".into()],
35088                port: 8080,
35089            };
35090            let err = AplicacaoError::entrada_member_missing(&entrada);
35091            let AplicacaoError::EntradaMemberMissing { para: stored_para } = err else {
35092                panic!("entrada_member_missing must construct EntradaMemberMissing for {para:?}");
35093            };
35094            assert_eq!(
35095                stored_para,
35096                entrada.destination(),
35097                "para slot must round-trip verbatim through Entrada::destination() \
35098                 for {para:?}"
35099            );
35100            assert_eq!(
35101                stored_para, para,
35102                "para slot must byte-equal the fixture-declared value for {para:?}"
35103            );
35104        }
35105    }
35106
35107    #[test]
35108    fn validate_entrada_phantom_arm_routes_through_entrada_member_missing_ctor() {
35109        // End-to-end pin: the sole in-crate wire-up site
35110        // (`AplicacaoSpec::validate_entrada`'s membership-lookup arm)
35111        // routes through [`AplicacaoError::entrada_member_missing`] and
35112        // the observed `Err` byte-equals the ctor's output on the same
35113        // well-shaped-phantom `:para` fixture. A future silent de-lift
35114        // of the wire-up back to the open-coded struct-literal trips
35115        // this test at caixa-core build time rather than at a
35116        // downstream diagnostic consumer far from the wire-up commit.
35117        // Sibling of the peer
35118        // `validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor`
35119        // end-to-end pin on the sibling per-`:placement :shard-key`
35120        // envelope, and sibling of the peer
35121        // `entrada_para_well_shaped_phantom_still_raises_member_missing`
35122        // pattern-match pin on the same wire-up — extended here from a
35123        // `matches!` shape check to a byte-identity + Display parity
35124        // route through the ctor.
35125        let mut s = three_member_spec();
35126        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
35127        let observed = s.validate().unwrap_err();
35128        let expected = AplicacaoError::entrada_member_missing(s.entrada.as_ref().unwrap());
35129        assert_eq!(
35130            observed, expected,
35131            "validate_entrada's phantom-reference-arm Err must byte-equal \
35132             entrada_member_missing(&entrada)"
35133        );
35134        assert_eq!(
35135            observed.to_string(),
35136            expected.to_string(),
35137            "Display byte-string parity"
35138        );
35139    }
35140
35141    #[test]
35142    fn contrato_cycle_ctor_matches_struct_literal_wrap() {
35143        // Equivalence pin: the ctor produces byte-equal
35144        // `AplicacaoError::ContratoCycle` to the pre-lift open-coded
35145        // struct-literal that stored the caller-side reconstructed
35146        // cycle path verbatim at the gray-arm cycle-close return inside
35147        // [`AplicacaoSpec::detect_sync_cycles`]. Guards any future
35148        // field-addition / reordering / re-collect divergence on the
35149        // variant. Sibling of the peer
35150        // `entrada_member_missing_ctor_matches_struct_literal_wrap`
35151        // (deeae5c) pin on the sibling per-`:entrada :para`
35152        // phantom-reference envelope, and sibling of the peer
35153        // `placement_without_clusters_ctor_matches_struct_literal_wrap`
35154        // pin on the sibling per-`:placement` empty-clusters envelope.
35155        let cycle = vec![
35156            "cart".to_string(),
35157            "catalog".to_string(),
35158            "cart".to_string(),
35159        ];
35160        let via_ctor = AplicacaoError::contrato_cycle(cycle.clone());
35161        let via_literal = AplicacaoError::ContratoCycle {
35162            cycle: cycle.clone(),
35163        };
35164        assert_eq!(
35165            via_ctor, via_literal,
35166            "contrato_cycle(cycle) must byte-equal the open-coded \
35167             ContratoCycle struct-literal on the same Vec<String> fixture"
35168        );
35169        assert_eq!(
35170            via_ctor.to_string(),
35171            via_literal.to_string(),
35172            "Display byte-string must byte-equal the open-coded struct-literal"
35173        );
35174    }
35175
35176    #[test]
35177    fn contrato_cycle_ctor_routes_path_verbatim() {
35178        // Boundary-sweep pin on the ctor's substrate-primitive
35179        // pass-through: the `cycle` slot is stored verbatim across a
35180        // representative set of reconstructed cycle paths (two-node
35181        // closed loop; three-node loop; long chain with repeated
35182        // interior nodes; a fixture whose first/last coincide by the
35183        // gray-arm's own append-target-once-more discipline), so any
35184        // wrapper-side silent normalization, dedup, sort, `.into()`
35185        // divergence, accidental field rebrand, or re-collect on the
35186        // sole-field pass-through surfaces at caixa-core build time
35187        // rather than at a downstream diagnostic consumer that reads
35188        // `err.cycle` back and gets a different value than the one it
35189        // stored. Peer of the sibling
35190        // `entrada_member_missing_ctor_routes_para_through_entrada_accessor`
35191        // (deeae5c) boundary-sweep pin on the sibling per-`:entrada
35192        // :para` envelope — extended here onto the owned-[`Vec<String>`]
35193        // pass-through on the sibling per-`:contratos` cycle envelope.
35194        for cycle in [
35195            vec![
35196                "cart".to_string(),
35197                "catalog".to_string(),
35198                "cart".to_string(),
35199            ],
35200            vec![
35201                "cart".to_string(),
35202                "catalog".to_string(),
35203                "payment".to_string(),
35204                "cart".to_string(),
35205            ],
35206            vec![
35207                "a".to_string(),
35208                "b".to_string(),
35209                "c".to_string(),
35210                "d".to_string(),
35211                "b".to_string(),
35212            ],
35213            vec!["only".to_string(), "only".to_string()],
35214        ] {
35215            let err = AplicacaoError::contrato_cycle(cycle.clone());
35216            let AplicacaoError::ContratoCycle { cycle: stored } = err else {
35217                panic!("contrato_cycle must construct ContratoCycle for {cycle:?}");
35218            };
35219            assert_eq!(
35220                stored, cycle,
35221                "cycle slot must round-trip the caller-side Vec<String> verbatim \
35222                 for {cycle:?}"
35223            );
35224        }
35225    }
35226
35227    #[test]
35228    fn detect_sync_cycles_arm_routes_through_contrato_cycle_ctor() {
35229        // End-to-end pin: the sole in-crate wire-up site
35230        // (`AplicacaoSpec::detect_sync_cycles`'s gray-arm cycle-close
35231        // return) routes through [`AplicacaoError::contrato_cycle`] and
35232        // the observed `Err` byte-equals the ctor's output on the same
35233        // reconstructed cycle path. A future silent de-lift of the
35234        // wire-up back to the open-coded `AplicacaoError::ContratoCycle
35235        // { cycle }` struct-literal trips this test at caixa-core build
35236        // time rather than at a downstream diagnostic consumer far from
35237        // the wire-up commit. Sibling of the peer
35238        // `validate_entrada_phantom_arm_routes_through_entrada_member_missing_ctor`
35239        // (deeae5c) end-to-end pin on the sibling per-`:entrada :para`
35240        // envelope, and sibling of the peer
35241        // `validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor`
35242        // (14bafca) end-to-end pin on the sibling per-`:placement
35243        // :shard-key` envelope — extended here from a bare
35244        // `matches!(err, AplicacaoError::ContratoCycle { .. })` shape
35245        // check to a byte-identity route through the ctor.
35246        let mut s = three_member_spec();
35247        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
35248        s.contratos = vec![
35249            contract_http("catalog", "cart", "/x"),
35250            contract_http("cart", "payment", "/y"),
35251            contract_http("payment", "catalog", "/z"),
35252        ];
35253        let observed = s.validate().unwrap_err();
35254        let AplicacaoError::ContratoCycle { ref cycle } = observed else {
35255            panic!("expected ContratoCycle from the sync-cycle detector, got {observed:?}");
35256        };
35257        let expected = AplicacaoError::contrato_cycle(cycle.clone());
35258        assert_eq!(
35259            observed, expected,
35260            "detect_sync_cycles's gray-arm Err must byte-equal \
35261             contrato_cycle(cycle) on the reconstructed cycle path"
35262        );
35263        assert_eq!(
35264            observed.to_string(),
35265            expected.to_string(),
35266            "Display byte-string parity"
35267        );
35268    }
35269
35270    // ── policy_breaker_window_below_timeout standalone ctor pins ────────
35271    //
35272    // Fail-before-pass-after pins for the standalone
35273    // [`AplicacaoError::policy_breaker_window_below_timeout`] inherent
35274    // ctor (see the paired doc-block above the ctor definition) — the
35275    // fold of the last open-coded two-slot `{ window: cb.window(),
35276    // timeout: t }` struct-literal inside
35277    // [`MeshPolicy::first_cross_axis_violation`]'s window-below-timeout
35278    // arm onto one substrate primitive on the [`AplicacaoError`]
35279    // envelope, projecting through the [`CircuitBreaker::window`] scalar
35280    // accessor on the substrate primitive. A byte-mismatched ctor body
35281    // would trip the equivalence pin first, ahead of any downstream
35282    // diagnostic-shape drift.
35283    //
35284    // Peer of the sibling standalone-ctor equivalence pins on the peer
35285    // per-envelope substrate-primitive-projection ctors across
35286    // caixa-core: `contrato_self_loop_ctor_matches_struct_literal_wrap`
35287    // (b30edfe) on the sibling `{ caixa: String, wit: String }` two-slot
35288    // per-`:contratos` self-edge envelope,
35289    // `entrada_member_missing_ctor_matches_struct_literal_wrap` (deeae5c)
35290    // on the sibling `{ para: String }` one-slot per-`:entrada :para`
35291    // phantom-reference envelope, and
35292    // `shard_key_on_non_sharded_ctor_matches_struct_literal_wrap`
35293    // (14bafca) on the sibling `{ estrategia, shard_key }` two-slot
35294    // per-`:placement :shard-key` envelope.
35295
35296    #[test]
35297    fn policy_breaker_window_below_timeout_ctor_matches_struct_literal_wrap() {
35298        // Equivalence pin: the ctor produces byte-equal
35299        // `AplicacaoError::PolicyBreakerWindowBelowTimeout` to the pre-
35300        // lift open-coded struct-literal that read the same two fields
35301        // through [`CircuitBreaker::window`] and the paired
35302        // `:politicas :timeout` destructure. Guards any future
35303        // field-addition / reordering / accessor-swap tweak on the
35304        // variant. Same equivalence-pin shape as the sibling
35305        // `contrato_self_loop_ctor_matches_struct_literal_wrap`
35306        // (b30edfe) on the sibling per-`:contratos` self-edge envelope.
35307        let cb = CircuitBreaker {
35308            max_failures: 5,
35309            window: Duration::from_secs(10),
35310        };
35311        let timeout = Duration::from_secs(30);
35312        let via_ctor = AplicacaoError::policy_breaker_window_below_timeout(&cb, timeout);
35313        let via_literal = AplicacaoError::PolicyBreakerWindowBelowTimeout {
35314            window: cb.window(),
35315            timeout,
35316        };
35317        assert_eq!(
35318            via_ctor, via_literal,
35319            "policy_breaker_window_below_timeout(&cb, t) must byte-equal \
35320             the open-coded PolicyBreakerWindowBelowTimeout struct-literal \
35321             on the same Copy-Duration fixture"
35322        );
35323        assert_eq!(
35324            via_ctor.to_string(),
35325            via_literal.to_string(),
35326            "Display byte-string must byte-equal the open-coded struct-literal"
35327        );
35328    }
35329
35330    #[test]
35331    fn policy_breaker_window_below_timeout_ctor_routes_cb_window_and_timeout_verbatim() {
35332        // Routing pin sweeping non-default `:circuit-breaker :window`
35333        // and `:timeout` pairs (below-boundary window / above-boundary
35334        // window; sub-second window / multi-minute timeout;
35335        // millisecond-precision fixture) through the paired
35336        // [`CircuitBreaker::window`] accessor and the direct `timeout`
35337        // parameter, so any wrapper-side silent normalization,
35338        // rounding, argument re-order, or accidental slot rebrand on
35339        // the two-slot pass-through surfaces at caixa-core build time
35340        // rather than at a downstream diagnostic consumer that reads
35341        // the two [`Duration`]s back and gets different values than
35342        // the ones it stored.
35343        //
35344        // Deliberately routes through a fixture whose `cb.window` and
35345        // `timeout` are distinct — a silent accessor swap
35346        // (`cb.max_failures` casting to `Duration` would fail to
35347        // compile; a hypothetical field-rename swap swapping the two
35348        // slots at the ctor body would land `timeout` in the `window`
35349        // slot instead of `cb.window()` and vice-versa, tripping the
35350        // per-field assertion here). Peer of the sibling
35351        // `contrato_self_loop_ctor_routes_source_and_world_ref_through_verbatim`
35352        // (b30edfe) routing pin on the sibling two-slot per-`:contratos`
35353        // envelope.
35354        for (max_failures, window, timeout) in [
35355            (5_u32, Duration::from_secs(10), Duration::from_secs(30)),
35356            (
35357                1_u32,
35358                Duration::from_millis(29_999),
35359                Duration::from_secs(30),
35360            ),
35361            (42_u32, Duration::from_millis(500), Duration::from_secs(120)),
35362            (7_u32, Duration::from_secs(1), Duration::from_secs(60)),
35363        ] {
35364            let cb = CircuitBreaker {
35365                max_failures,
35366                window,
35367            };
35368            let built = AplicacaoError::policy_breaker_window_below_timeout(&cb, timeout);
35369            let AplicacaoError::PolicyBreakerWindowBelowTimeout {
35370                window: stored_window,
35371                timeout: stored_timeout,
35372            } = built
35373            else {
35374                panic!(
35375                    "policy_breaker_window_below_timeout must construct \
35376                     PolicyBreakerWindowBelowTimeout for cb={cb:?}/timeout={timeout:?}"
35377                );
35378            };
35379            assert_eq!(
35380                stored_window, window,
35381                "window slot must thread CircuitBreaker::window() verbatim \
35382                 for cb={cb:?}/timeout={timeout:?}"
35383            );
35384            assert_eq!(
35385                stored_timeout, timeout,
35386                "timeout slot must thread the caller-side :timeout scalar verbatim \
35387                 for cb={cb:?}/timeout={timeout:?}"
35388            );
35389        }
35390    }
35391
35392    #[test]
35393    fn first_cross_axis_violation_arm_routes_through_policy_breaker_window_below_timeout_ctor() {
35394        // End-to-end pin: the sole in-crate wire-up site
35395        // ([`MeshPolicy::first_cross_axis_violation`]'s
35396        // window-below-timeout arm) routes through
35397        // [`AplicacaoError::policy_breaker_window_below_timeout`] and
35398        // the observed `Err` byte-equals the ctor's output on the same
35399        // sub-boundary `(:window, :timeout)` fixture. A future silent
35400        // de-lift of the wire-up back to the open-coded
35401        // `AplicacaoError::PolicyBreakerWindowBelowTimeout { window,
35402        // timeout }` struct-literal trips this test at caixa-core build
35403        // time rather than at a downstream diagnostic consumer far from
35404        // the wire-up commit. Sibling of the peer
35405        // `detect_sync_cycles_arm_routes_through_contrato_cycle_ctor`
35406        // (5cfcab8) end-to-end pin on the sibling per-`:contratos`
35407        // cross-edge cycle envelope,
35408        // `validate_entrada_phantom_arm_routes_through_entrada_member_missing_ctor`
35409        // (deeae5c) on the sibling per-`:entrada :para` phantom-
35410        // reference envelope, and
35411        // `validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor`
35412        // (14bafca) on the sibling per-`:placement :shard-key`
35413        // envelope — extended here from a bare `matches!(err,
35414        // AplicacaoError::PolicyBreakerWindowBelowTimeout { .. })`
35415        // shape check to a byte-identity route through the ctor.
35416        let mut s = three_member_spec();
35417        s.politicas.timeout = Some(Duration::from_secs(30));
35418        s.politicas.circuit_breaker = Some(CircuitBreaker {
35419            max_failures: 5,
35420            window: Duration::from_secs(10),
35421        });
35422        let observed = s.validate().unwrap_err();
35423        let cb = s.politicas.circuit_breaker.unwrap();
35424        let timeout = s.politicas.timeout.unwrap();
35425        let expected = AplicacaoError::policy_breaker_window_below_timeout(&cb, timeout);
35426        assert_eq!(
35427            observed, expected,
35428            "MeshPolicy::first_cross_axis_violation's window-below-timeout \
35429             arm's Err must byte-equal policy_breaker_window_below_timeout(&cb, t)"
35430        );
35431        assert_eq!(
35432            observed.to_string(),
35433            expected.to_string(),
35434            "Display byte-string parity"
35435        );
35436    }
35437
35438    #[test]
35439    fn policy_breaker_cannot_trip_under_rate_limit_ctor_matches_struct_literal_wrap() {
35440        // Equivalence pin: the ctor produces byte-equal
35441        // `AplicacaoError::PolicyBreakerCannotTripUnderRateLimit` to the
35442        // pre-lift open-coded struct-literal that read the same four fields
35443        // through [`RateLimit::rate`], [`RateLimit::window`],
35444        // [`CircuitBreaker::max_failures`], and [`CircuitBreaker::window`].
35445        // Guards any future field-addition / reordering / accessor-swap
35446        // tweak on the variant. Same equivalence-pin shape as the sibling
35447        // `policy_breaker_window_below_timeout_ctor_matches_struct_literal_wrap`
35448        // (9b30c07) on the sibling per-`(:timeout, :circuit-breaker)`
35449        // cross-axis envelope.
35450        let rl = RateLimit {
35451            rate: 1,
35452            window: Duration::from_secs(3600),
35453        };
35454        let cb = CircuitBreaker {
35455            max_failures: 5,
35456            window: Duration::from_secs(10),
35457        };
35458        let via_ctor = AplicacaoError::policy_breaker_cannot_trip_under_rate_limit(&rl, &cb);
35459        let via_literal = AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
35460            rate: rl.rate(),
35461            rl_window: rl.window(),
35462            max_failures: cb.max_failures(),
35463            cb_window: cb.window(),
35464        };
35465        assert_eq!(
35466            via_ctor, via_literal,
35467            "policy_breaker_cannot_trip_under_rate_limit(&rl, &cb) must \
35468             byte-equal the open-coded PolicyBreakerCannotTripUnderRateLimit \
35469             struct-literal on the same Copy-(u32|Duration) fixture"
35470        );
35471        assert_eq!(
35472            via_ctor.to_string(),
35473            via_literal.to_string(),
35474            "Display byte-string must byte-equal the open-coded struct-literal"
35475        );
35476    }
35477
35478    #[test]
35479    fn policy_breaker_cannot_trip_under_rate_limit_ctor_routes_rl_and_cb_verbatim() {
35480        // Routing pin sweeping non-default `(:rate, :rate-limit :window,
35481        // :max-failures, :circuit-breaker :window)` tuples across the
35482        // production-playbook starve band — Envoy 5-in-10s vs 1/hour,
35483        // sub-second breaker window, multi-minute rate-limit window,
35484        // multi-tenant per-cluster ratio — through the paired
35485        // [`RateLimit::rate`] / [`RateLimit::window`] /
35486        // [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
35487        // accessors, so any wrapper-side silent normalization, rounding,
35488        // argument re-order, or accidental slot rebrand on the four-slot
35489        // pass-through surfaces at caixa-core build time rather than at a
35490        // downstream diagnostic consumer that reads the four scalars back
35491        // and gets different values than the ones it stored.
35492        //
35493        // Deliberately routes through fixtures whose four scalars are
35494        // pairwise distinct (`rate ≠ max_failures`, `rl_window ≠
35495        // cb_window`) — a hypothetical field-rename swap swapping any
35496        // two adjacent slots at the ctor body would land the value from
35497        // the wrong axis, tripping the per-field assertion here. Peer of
35498        // the sibling
35499        // `policy_breaker_window_below_timeout_ctor_routes_cb_window_and_timeout_verbatim`
35500        // (9b30c07) routing pin on the sibling two-slot per-`(:timeout,
35501        // :circuit-breaker)` cross-axis envelope.
35502        for (rate, rl_window, max_failures, cb_window) in [
35503            (
35504                1_u32,
35505                Duration::from_secs(3600),
35506                5_u32,
35507                Duration::from_secs(10),
35508            ),
35509            (4_u32, Duration::from_secs(1), 5_u32, Duration::from_secs(1)),
35510            (
35511                2_u32,
35512                Duration::from_millis(500),
35513                10_u32,
35514                Duration::from_secs(300),
35515            ),
35516            (
35517                7_u32,
35518                Duration::from_secs(120),
35519                42_u32,
35520                Duration::from_millis(750),
35521            ),
35522        ] {
35523            let rl = RateLimit {
35524                rate,
35525                window: rl_window,
35526            };
35527            let cb = CircuitBreaker {
35528                max_failures,
35529                window: cb_window,
35530            };
35531            let built = AplicacaoError::policy_breaker_cannot_trip_under_rate_limit(&rl, &cb);
35532            let AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
35533                rate: stored_rate,
35534                rl_window: stored_rl_window,
35535                max_failures: stored_max_failures,
35536                cb_window: stored_cb_window,
35537            } = built
35538            else {
35539                panic!(
35540                    "policy_breaker_cannot_trip_under_rate_limit must \
35541                     construct PolicyBreakerCannotTripUnderRateLimit for \
35542                     rl={rl:?}/cb={cb:?}"
35543                );
35544            };
35545            assert_eq!(
35546                stored_rate, rate,
35547                "rate slot must thread RateLimit::rate() verbatim for \
35548                 rl={rl:?}/cb={cb:?}"
35549            );
35550            assert_eq!(
35551                stored_rl_window, rl_window,
35552                "rl_window slot must thread RateLimit::window() verbatim \
35553                 for rl={rl:?}/cb={cb:?}"
35554            );
35555            assert_eq!(
35556                stored_max_failures, max_failures,
35557                "max_failures slot must thread CircuitBreaker::max_failures() \
35558                 verbatim for rl={rl:?}/cb={cb:?}"
35559            );
35560            assert_eq!(
35561                stored_cb_window, cb_window,
35562                "cb_window slot must thread CircuitBreaker::window() verbatim \
35563                 for rl={rl:?}/cb={cb:?}"
35564            );
35565        }
35566    }
35567
35568    #[test]
35569    fn first_cross_axis_violation_arm_routes_through_policy_breaker_cannot_trip_under_rate_limit_ctor()
35570     {
35571        // End-to-end pin: the sole in-crate wire-up site
35572        // ([`MeshPolicy::first_cross_axis_violation`]'s
35573        // starve-under-rate-limit arm) routes through
35574        // [`AplicacaoError::policy_breaker_cannot_trip_under_rate_limit`]
35575        // and the observed `Err` byte-equals the ctor's output on the same
35576        // token-bucket-starves-breaker fixture. A future silent de-lift of
35577        // the wire-up back to the open-coded
35578        // `AplicacaoError::PolicyBreakerCannotTripUnderRateLimit { rate,
35579        // rl_window, max_failures, cb_window }` struct-literal trips this
35580        // test at caixa-core build time rather than at a downstream
35581        // diagnostic consumer far from the wire-up commit. Sibling of the
35582        // peer
35583        // `first_cross_axis_violation_arm_routes_through_policy_breaker_window_below_timeout_ctor`
35584        // (9b30c07) end-to-end pin on the sibling per-`(:timeout,
35585        // :circuit-breaker)` cross-axis envelope — extended here from a
35586        // bare `matches!(err,
35587        // AplicacaoError::PolicyBreakerCannotTripUnderRateLimit { .. })`
35588        // shape check to a byte-identity route through the ctor. Clears
35589        // `:timeout` so the sibling window-below-timeout arm does not
35590        // fire first on the ordering-precedent it holds over this arm.
35591        let mut s = three_member_spec();
35592        s.politicas.timeout = None;
35593        s.politicas.circuit_breaker = Some(CircuitBreaker {
35594            max_failures: 5,
35595            window: Duration::from_secs(10),
35596        });
35597        s.politicas.rate_limit = Some(RateLimit {
35598            rate: 1,
35599            window: Duration::from_secs(3600),
35600        });
35601        let observed = s.validate().unwrap_err();
35602        let rl = s.politicas.rate_limit.unwrap();
35603        let cb = s.politicas.circuit_breaker.unwrap();
35604        let expected = AplicacaoError::policy_breaker_cannot_trip_under_rate_limit(&rl, &cb);
35605        assert_eq!(
35606            observed, expected,
35607            "MeshPolicy::first_cross_axis_violation's starve-under-rate-limit \
35608             arm's Err must byte-equal \
35609             policy_breaker_cannot_trip_under_rate_limit(&rl, &cb)"
35610        );
35611        assert_eq!(
35612            observed.to_string(),
35613            expected.to_string(),
35614            "Display byte-string parity"
35615        );
35616    }
35617
35618    #[test]
35619    fn policy_breaker_trips_before_retries_exhausted_ctor_matches_struct_literal_wrap() {
35620        // Equivalence pin: the ctor produces byte-equal
35621        // `AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted` to the
35622        // pre-lift open-coded struct-literal that read the same two fields
35623        // through the bare `retries` destructure and
35624        // [`CircuitBreaker::max_failures`]. Guards any future field-addition
35625        // / reordering / accessor-swap tweak on the variant. Same
35626        // equivalence-pin shape as the sibling
35627        // `policy_breaker_cannot_trip_under_rate_limit_ctor_matches_struct_literal_wrap`
35628        // (6bb4e46) on the sibling per-`(:rate-limit, :circuit-breaker)`
35629        // second cross-axis envelope and
35630        // `policy_breaker_window_below_timeout_ctor_matches_struct_literal_wrap`
35631        // (9b30c07) on the sibling per-`(:timeout, :circuit-breaker)` first
35632        // cross-axis envelope.
35633        let retries = 5_u32;
35634        let cb = CircuitBreaker {
35635            max_failures: 3,
35636            window: Duration::from_secs(60),
35637        };
35638        let via_ctor = AplicacaoError::policy_breaker_trips_before_retries_exhausted(retries, &cb);
35639        let via_literal = AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
35640            retries,
35641            max_failures: cb.max_failures(),
35642        };
35643        assert_eq!(
35644            via_ctor, via_literal,
35645            "policy_breaker_trips_before_retries_exhausted(retries, &cb) must \
35646             byte-equal the open-coded PolicyBreakerTripsBeforeRetriesExhausted \
35647             struct-literal on the same Copy-u32 fixture"
35648        );
35649        assert_eq!(
35650            via_ctor.to_string(),
35651            via_literal.to_string(),
35652            "Display byte-string must byte-equal the open-coded struct-literal"
35653        );
35654    }
35655
35656    #[test]
35657    fn policy_breaker_trips_before_retries_exhausted_ctor_routes_retries_and_cb_verbatim() {
35658        // Routing pin sweeping non-default `(retries, max_failures)` tuples
35659        // across the production-playbook retries-saturate band — Envoy 5
35660        // retries vs 3 max-failures, boundary retries==max_failures pair (a
35661        // rejecting arm on the strict-inequality invariant), multi-tenant
35662        // high-retries-vs-low-trip ratio, sub-cap high-max-failures ceiling —
35663        // through the paired bare-`retries` destructure and
35664        // [`CircuitBreaker::max_failures`] accessor, so any wrapper-side
35665        // silent normalization, rounding, argument re-order, or accidental
35666        // slot rebrand on the two-slot pass-through surfaces at caixa-core
35667        // build time rather than at a downstream diagnostic consumer that
35668        // reads the two scalars back and gets different values than the ones
35669        // it stored.
35670        //
35671        // Deliberately routes through fixtures whose two scalars are
35672        // pairwise distinct (`retries ≠ max_failures` on every non-boundary
35673        // arm) — a hypothetical field-rename swap swapping the two slots at
35674        // the ctor body would land the value from the wrong axis, tripping
35675        // the per-field assertion here. Peer of the sibling
35676        // `policy_breaker_cannot_trip_under_rate_limit_ctor_routes_rl_and_cb_verbatim`
35677        // (6bb4e46) routing pin on the sibling four-slot per-`(:rate-limit,
35678        // :circuit-breaker)` second cross-axis envelope.
35679        for (retries, max_failures) in [
35680            (5_u32, 3_u32),
35681            (3_u32, 3_u32),
35682            (100_u32, 1_u32),
35683            (7_u32, 42_u32),
35684        ] {
35685            let cb = CircuitBreaker {
35686                max_failures,
35687                window: Duration::from_secs(60),
35688            };
35689            let built = AplicacaoError::policy_breaker_trips_before_retries_exhausted(retries, &cb);
35690            let AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
35691                retries: stored_retries,
35692                max_failures: stored_max_failures,
35693            } = built
35694            else {
35695                panic!(
35696                    "policy_breaker_trips_before_retries_exhausted must \
35697                     construct PolicyBreakerTripsBeforeRetriesExhausted for \
35698                     retries={retries}/cb={cb:?}"
35699                );
35700            };
35701            assert_eq!(
35702                stored_retries, retries,
35703                "retries slot must thread the bare-`retries` destructure \
35704                 verbatim for retries={retries}/cb={cb:?}"
35705            );
35706            assert_eq!(
35707                stored_max_failures, max_failures,
35708                "max_failures slot must thread CircuitBreaker::max_failures() \
35709                 verbatim for retries={retries}/cb={cb:?}"
35710            );
35711        }
35712    }
35713
35714    #[test]
35715    fn first_cross_axis_violation_arm_routes_through_policy_breaker_trips_before_retries_exhausted_ctor()
35716     {
35717        // End-to-end pin: the sole in-crate wire-up site
35718        // ([`MeshPolicy::first_cross_axis_violation`]'s retries-saturate
35719        // arm) routes through
35720        // [`AplicacaoError::policy_breaker_trips_before_retries_exhausted`]
35721        // and the observed `Err` byte-equals the ctor's output on the same
35722        // retries-saturate fixture. A future silent de-lift of the wire-up
35723        // back to the open-coded
35724        // `AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted { retries,
35725        // max_failures }` struct-literal trips this test at caixa-core build
35726        // time rather than at a downstream diagnostic consumer far from the
35727        // wire-up commit. Sibling of the peer
35728        // `first_cross_axis_violation_arm_routes_through_policy_breaker_cannot_trip_under_rate_limit_ctor`
35729        // (6bb4e46) end-to-end pin on the sibling per-`(:rate-limit,
35730        // :circuit-breaker)` second cross-axis envelope — extended here from
35731        // a bare `matches!(err,
35732        // AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted { .. })`
35733        // shape check to a byte-identity route through the ctor. Clears
35734        // `:timeout` and `:rate-limit` so the sibling window-below-timeout
35735        // and starve-under-rate-limit arms do not fire first on the
35736        // ordering-precedent they hold over this arm.
35737        let mut s = three_member_spec();
35738        s.politicas.timeout = None;
35739        s.politicas.rate_limit = None;
35740        s.politicas.retries = Some(5);
35741        s.politicas.circuit_breaker = Some(CircuitBreaker {
35742            max_failures: 3,
35743            window: Duration::from_secs(60),
35744        });
35745        let observed = s.validate().unwrap_err();
35746        let retries = s.politicas.retries.unwrap();
35747        let cb = s.politicas.circuit_breaker.unwrap();
35748        let expected = AplicacaoError::policy_breaker_trips_before_retries_exhausted(retries, &cb);
35749        assert_eq!(
35750            observed, expected,
35751            "MeshPolicy::first_cross_axis_violation's retries-saturate arm's \
35752             Err must byte-equal \
35753             policy_breaker_trips_before_retries_exhausted(retries, &cb)"
35754        );
35755        assert_eq!(
35756            observed.to_string(),
35757            expected.to_string(),
35758            "Display byte-string parity"
35759        );
35760    }
35761
35762    #[test]
35763    fn policy_rate_limit_cannot_admit_retry_burst_ctor_matches_struct_literal_wrap() {
35764        // Equivalence pin: the ctor produces byte-equal
35765        // `AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst` to the
35766        // pre-lift open-coded struct-literal that read the same two fields
35767        // through the bare `retries` destructure and [`RateLimit::rate`].
35768        // Guards any future field-addition / reordering / accessor-swap
35769        // tweak on the variant. Same equivalence-pin shape as the sibling
35770        // `policy_breaker_trips_before_retries_exhausted_ctor_matches_struct_literal_wrap`
35771        // (f54c539) on the sibling per-`(:retries, :circuit-breaker)`
35772        // third cross-axis envelope,
35773        // `policy_breaker_cannot_trip_under_rate_limit_ctor_matches_struct_literal_wrap`
35774        // (6bb4e46) on the sibling per-`(:rate-limit, :circuit-breaker)`
35775        // second cross-axis envelope, and
35776        // `policy_breaker_window_below_timeout_ctor_matches_struct_literal_wrap`
35777        // (9b30c07) on the sibling per-`(:timeout, :circuit-breaker)`
35778        // first cross-axis envelope.
35779        let retries = 3_u32;
35780        let rl = RateLimit {
35781            rate: 3,
35782            window: Duration::from_secs(1),
35783        };
35784        let via_ctor = AplicacaoError::policy_rate_limit_cannot_admit_retry_burst(retries, &rl);
35785        let via_literal = AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
35786            retries,
35787            rate: rl.rate(),
35788        };
35789        assert_eq!(
35790            via_ctor, via_literal,
35791            "policy_rate_limit_cannot_admit_retry_burst(retries, &rl) must \
35792             byte-equal the open-coded PolicyRateLimitCannotAdmitRetryBurst \
35793             struct-literal on the same Copy-u32 fixture"
35794        );
35795        assert_eq!(
35796            via_ctor.to_string(),
35797            via_literal.to_string(),
35798            "Display byte-string must byte-equal the open-coded struct-literal"
35799        );
35800    }
35801
35802    #[test]
35803    fn policy_rate_limit_cannot_admit_retry_burst_ctor_routes_retries_and_rl_verbatim() {
35804        // Routing pin sweeping non-default `(retries, rate)` tuples across
35805        // the production-playbook rate-limit-starve band — boundary
35806        // `retries==rate` (a rejecting arm on the `>=` invariant stated as
35807        // `rate >= retries + 1`), one-below-boundary pair, multi-tenant
35808        // high-retries-vs-low-rate ratio, and sub-cap high-rate ceiling —
35809        // through the paired bare-`retries` destructure and
35810        // [`RateLimit::rate`] accessor, so any wrapper-side silent
35811        // normalization, rounding, argument re-order, or accidental slot
35812        // rebrand on the two-slot pass-through surfaces at caixa-core
35813        // build time rather than at a downstream diagnostic consumer that
35814        // reads the two scalars back and gets different values than the
35815        // ones it stored.
35816        //
35817        // Deliberately routes through fixtures whose two scalars are
35818        // pairwise distinct on every non-boundary arm — a hypothetical
35819        // field-rename swap swapping the two slots at the ctor body would
35820        // land the value from the wrong axis, tripping the per-field
35821        // assertion here. Peer of the sibling
35822        // `policy_breaker_trips_before_retries_exhausted_ctor_routes_retries_and_cb_verbatim`
35823        // (f54c539) routing pin on the sibling two-slot per-`(:retries,
35824        // :circuit-breaker)` third cross-axis envelope.
35825        for (retries, rate) in [
35826            (3_u32, 3_u32),
35827            (5_u32, 4_u32),
35828            (100_u32, 50_u32),
35829            (2_u32, POLICY_RATE_LIMIT_MAX),
35830        ] {
35831            let rl = RateLimit {
35832                rate,
35833                window: Duration::from_secs(1),
35834            };
35835            let built = AplicacaoError::policy_rate_limit_cannot_admit_retry_burst(retries, &rl);
35836            let AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
35837                retries: stored_retries,
35838                rate: stored_rate,
35839            } = built
35840            else {
35841                panic!(
35842                    "policy_rate_limit_cannot_admit_retry_burst must \
35843                     construct PolicyRateLimitCannotAdmitRetryBurst for \
35844                     retries={retries}/rl={rl:?}"
35845                );
35846            };
35847            assert_eq!(
35848                stored_retries, retries,
35849                "retries slot must thread the bare-`retries` destructure \
35850                 verbatim for retries={retries}/rl={rl:?}"
35851            );
35852            assert_eq!(
35853                stored_rate, rate,
35854                "rate slot must thread RateLimit::rate() verbatim for \
35855                 retries={retries}/rl={rl:?}"
35856            );
35857        }
35858    }
35859
35860    #[test]
35861    fn first_cross_axis_violation_arm_routes_through_policy_rate_limit_cannot_admit_retry_burst_ctor()
35862     {
35863        // End-to-end pin: the sole in-crate wire-up site
35864        // ([`MeshPolicy::first_cross_axis_violation`]'s starve-under-rate-
35865        // limit arm) routes through
35866        // [`AplicacaoError::policy_rate_limit_cannot_admit_retry_burst`]
35867        // and the observed `Err` byte-equals the ctor's output on the same
35868        // rate-limit-starve fixture. A future silent de-lift of the
35869        // wire-up back to the open-coded
35870        // `AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst { retries,
35871        // rate }` struct-literal trips this test at caixa-core build time
35872        // rather than at a downstream diagnostic consumer far from the
35873        // wire-up commit. Sibling of the peer
35874        // `first_cross_axis_violation_arm_routes_through_policy_breaker_trips_before_retries_exhausted_ctor`
35875        // (f54c539) end-to-end pin on the sibling per-`(:retries,
35876        // :circuit-breaker)` third cross-axis envelope. Clears `:timeout`
35877        // and `:circuit-breaker` so the sibling window-below-timeout /
35878        // starve-under-rate-limit / trips-before-retries-exhausted arms
35879        // do not fire first on the ordering-precedent they hold over this
35880        // arm.
35881        let mut s = three_member_spec();
35882        s.politicas.timeout = None;
35883        s.politicas.circuit_breaker = None;
35884        s.politicas.retries = Some(5);
35885        s.politicas.rate_limit = Some(RateLimit {
35886            rate: 3,
35887            window: Duration::from_secs(1),
35888        });
35889        let observed = s.validate().unwrap_err();
35890        let retries = s.politicas.retries.unwrap();
35891        let rl = s.politicas.rate_limit.unwrap();
35892        let expected = AplicacaoError::policy_rate_limit_cannot_admit_retry_burst(retries, &rl);
35893        assert_eq!(
35894            observed, expected,
35895            "MeshPolicy::first_cross_axis_violation's starve-under-rate-limit arm's \
35896             Err must byte-equal \
35897             policy_rate_limit_cannot_admit_retry_burst(retries, &rl)"
35898        );
35899        assert_eq!(
35900            observed.to_string(),
35901            expected.to_string(),
35902            "Display byte-string parity"
35903        );
35904    }
35905}