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::ContratoMemberMissing {
1382                caixa: self.source().to_string(),
1383            });
1384        }
1385        if !names.contains(self.destination()) {
1386            return Err(AplicacaoError::ContratoMemberMissing {
1387                caixa: self.destination().to_string(),
1388            });
1389        }
1390        Ok(())
1391    }
1392
1393    /// Typed view of the contract's payload target. Enforces that the
1394    /// `:wit` shape and the carried `:endpoint`/`:subject`/`:slot`
1395    /// fields agree, and that each carried value is itself
1396    /// value-shape valid:
1397    ///
1398    ///   - HTTP world (`wasi:http/*`, `http:*`) ⇒ exactly `:endpoint`,
1399    ///     non-empty, leading-`/` (Cilium L7 `path` + Gateway API
1400    ///     `PathPrefix` invariant — same shape required of `:entrada
1401    ///     :paths`)
1402    ///   - `PubSub` world (`nats:*`, `kafka:*`) ⇒ exactly `:subject`,
1403    ///     non-empty (NATS / Kafka publish without a subject is a
1404    ///     no-op subscribe, never the author's intent)
1405    ///   - Store world (`wasi:keyvalue/*`, `kv:*`) ⇒ exactly `:slot`,
1406    ///     non-empty (an empty slot template addresses the bucket
1407    ///     root, defeating the per-key isolation the slot exists for)
1408    ///   - Anything else ⇒ none of the three; the contract is a pure
1409    ///     typed capability edge with no payload selector.
1410    ///
1411    /// Translates the Apollo Federation discipline ("conflicts are
1412    /// errors at compile time, not warnings at runtime";
1413    /// MESH-COMPOSITION §II.3) onto pleme-io's typed Aplicacao surface:
1414    /// a contract whose WIT shape disagrees with its target field, or
1415    /// whose target field carries a value-shape-invalid string, is a
1416    /// build error — not a silent renderer drop. The returned
1417    /// [`WitTarget`] view's `&str` payload is therefore guaranteed
1418    /// non-empty (and absolute, for `Http`); every downstream consumer
1419    /// (caixa-mesh's L7 emission, the M3 Gateway/HTTPRoute renderer,
1420    /// the M4 per-edge policy resolver) can rely on that without
1421    /// re-checking.
1422    pub fn target(&self) -> Result<WitTarget<'_>, AplicacaoError> {
1423        // Route the HTTP-shaped payload-target extraction through the
1424        // lifted [`WitContract::endpoint`] accessor rather than the raw
1425        // `self.endpoint.as_deref()` field access — the two production
1426        // consumers of the per-`:contratos :endpoint` HTTP-shaped
1427        // payload-carrier scalar (this method's Http-arm payload
1428        // extraction, the [`AplicacaoSpec::validate`] duplicate-
1429        // `:contratos` [`ContratoIdentity`] dedup-key HTTP arm) now key
1430        // off exactly one typed dispatch on the substrate primitive, so
1431        // any future rebrand on the axis (an M4 per-cluster endpoint-
1432        // alias rewrite, a per-CR fully-qualified path prefix the M4
1433        // materializer applies per-tenant, an M4 promotion from
1434        // `Option<String>` to a typed HTTP path-template enum) migrates
1435        // as a single caixa-core edit rather than a coordinated rewrite
1436        // of the two call sites — peer of the sibling M3 per-`:placement`
1437        // [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
1438        // (74ec2d3) `Option<&str>` typed-dispatch discipline extended
1439        // onto the per-`:contratos` HTTP-shaped payload-carrier axis.
1440        let endpoint = self.endpoint();
1441        let subject = self.subject();
1442        // Route the store-arm payload-carrier scalar through the
1443        // lifted [`WitContract::slot`] accessor rather than the raw
1444        // `self.slot.as_deref()` field access — the two production
1445        // consumers of the per-`:contratos :slot` key/value-store-
1446        // shaped payload-carrier scalar (this method's Store-arm
1447        // payload extraction, the [`AplicacaoSpec::validate`]
1448        // duplicate-`:contratos` [`ContratoIdentity`] dedup-key store
1449        // arm) now key off exactly one typed dispatch on the substrate
1450        // primitive. Closes the last unlifted per-`:contratos`
1451        // `Option<String>` axis, completing the payload-carrier
1452        // accessor family peer of the sibling per-`:contratos`
1453        // [`WitContract::endpoint`] (7020470) / [`WitContract::subject`]
1454        // (90de675) lifts across the HTTP / pub-sub arms.
1455        let slot = self.slot();
1456        // Route the local `(de, para, wit)` triple-projection closure
1457        // through the lifted [`WitContract::edge_triple`] typed accessor
1458        // rather than re-inlining `(self.de.clone(), self.para.clone(),
1459        // self.wit.clone())` — the eight [`AplicacaoError::Contrato*`]
1460        // triple-carrying diagnostic constructors below (wrong-target /
1461        // missing-target on all three payload arms + capability-with-
1462        // payload + invalid-wit) now key off exactly one typed dispatch
1463        // on the substrate-primitive composite projection, sibling to
1464        // the peer [`WitContract::edge_pair`]-routed
1465        // [`AplicacaoError::Empty*`]/`ContratoEndpointEmpty`/
1466        // `ContratoSubjectEmpty`/`ContratoSlotEmpty` pair-carrying
1467        // diagnostic constructors on the same per-`:contratos`
1468        // diagnostic-construction surface.
1469        let edge = || self.edge_triple();
1470
1471        // The `:wit` value drives every downstream dispatch — the
1472        // is_http/is_pubsub/is_store prefix matchers below, the
1473        // caixa-mesh L7-vs-L4 emission, the cycle-detector's pub-sub
1474        // exclusion. Until this gate landed `target()` accepted any
1475        // non-empty string and silently demoted unrecognized shapes to
1476        // a capability-only edge (`:wit "WASI:HTTP/proxy"` — uppercase
1477        // typo, `:wit "wasi-http/proxy"` — hyphen-instead-of-colon typo,
1478        // `:wit "wasi:http proxy"` — whitespace, `:wit "wasi:"` — empty
1479        // package, the paste-from-binary footgun a multi-line blob
1480        // accidentally landing in the slot, the un-percent-encoded
1481        // non-ASCII byte) — the canonical "I thought I had L7 HTTP
1482        // routing, got L4-only" footgun. Empty is still pre-checked at
1483        // the [`AplicacaoSpec::validate`] call site via the narrower
1484        // [`AplicacaoError::EmptyWit`] variant (and fires first at the
1485        // validate layer); the value-shape gate here picks up the
1486        // structurally-invalid non-empty cases the empty check misses,
1487        // and remains correct under direct `target()` calls outside
1488        // validate (the predicate's defensive empty arm returns a
1489        // parser-shaped reason rather than silently falling through to
1490        // the Capability arm). Same trajectory as c4213a4 (WitContract
1491        // endpoint/subject/slot value-shape gates lifted into
1492        // `target()`) on the peer payload axes.
1493        //
1494        // Routed through the lifted [`WitContract::world_ref`] accessor
1495        // rather than the raw `&self.wit` field access — the two
1496        // production consumers of the per-`:contratos :wit` world-ref
1497        // byte-string on the value-shape axis (this method's invalid-
1498        // wit gate, the [`AplicacaoSpec::validate`] duplicate-
1499        // `:contratos` [`ContratoIdentity`] dedup-key world-ref arm via
1500        // [`WitContract::identity`]) now key off exactly one typed
1501        // dispatch on the substrate primitive, so any future rebrand on
1502        // the axis (an M4 promotion from `String` to a typed WIT
1503        // world-ref enum once the WIT registry stabilizes in
1504        // tatara-lisp, a per-CR canonicalization pass that lowercases
1505        // the WIT world ref post-parse, a promoted `smol_str::SmolStr`
1506        // inline-buffer swap on the storage arm) migrates as a single
1507        // caixa-core edit rather than a coordinated rewrite of the two
1508        // call sites — sibling of the peer [`WitContract::endpoint`] /
1509        // [`WitContract::subject`] / [`WitContract::slot`] accessor-
1510        // routed payload-carrier extractions above on the same
1511        // [`WitContract::target`] body, completing the per-`:contratos`
1512        // scalar-accessor-routing pass at the last unlifted raw-field-
1513        // access site inside `impl WitContract`. Same "typed dispatch
1514        // composes with typed dispatch, not with raw field access"
1515        // discipline the sibling [`WitContract::edge_pair`] /
1516        // [`WitContract::edge_triple`] / [`WitContract::identity`]
1517        // composite-projection accessors and the
1518        // [`WitContract::is_self_loop`] identity-space predicate
1519        // already route through. Pinned by
1520        // [`tests::wit_contract_target_wit_shape_gate_routes_through_world_ref_accessor`].
1521        if let Err(reason) = crate::render::is_wit_world_ref(self.world_ref()) {
1522            let (de, para, wit) = edge();
1523            return Err(AplicacaoError::ContratoWitInvalid {
1524                de,
1525                para,
1526                wit,
1527                reason,
1528            });
1529        }
1530
1531        if self.is_http() {
1532            if subject.is_some() || slot.is_some() {
1533                return Err(AplicacaoError::contrato_wrong_target(
1534                    edge(),
1535                    WitTarget::HTTP_FIELD_NAME,
1536                ));
1537            }
1538            let ep = endpoint.ok_or_else(|| {
1539                AplicacaoError::contrato_missing_target(edge(), WitTarget::HTTP_FIELD_NAME)
1540            })?;
1541            if ep.is_empty() {
1542                return Err(AplicacaoError::contrato_endpoint_empty(self.edge_pair()));
1543            }
1544            if !ep.starts_with('/') {
1545                let (de, para) = self.edge_pair();
1546                return Err(AplicacaoError::ContratoEndpointNotAbsolute {
1547                    de,
1548                    para,
1549                    endpoint: ep.to_string(),
1550                });
1551            }
1552            // The `:endpoint` lands verbatim as a Cilium L7 `path:` rule
1553            // (caixa-mesh/src/lib.rs:311) and shares the K8s Gateway
1554            // API v1 HTTPPathMatch.value admission grammar with the
1555            // sibling `:entrada :paths` axis. Until this gate landed
1556            // `target()` only refused the empty string + the missing-
1557            // leading-`/` form; a structurally invalid endpoint
1558            // (`"/charge?token=X"` — query in path slot, `"/foo bar"` —
1559            // un-percent-encoded whitespace, `"/api/café"` — non-ASCII,
1560            // `"/api//bar"` — consecutive slash, `"/api/../etc"` —
1561            // path-traversal segment, the >1024-byte slug) silently
1562            // passed validate and the failure surfaced at apply time
1563            // as a Cilium policy rejection / silent traffic drop, far
1564            // from the source caixa.lisp. Same Gateway API HTTPPathMatch
1565            // grammar `:entrada :paths` already gates (55410e4), now
1566            // shared with `:contratos :endpoint` through the lifted
1567            // `crate::render::is_gateway_api_http_path` predicate.
1568            if let Err(reason) = crate::render::is_gateway_api_http_path(ep) {
1569                return Err(AplicacaoError::contrato_endpoint_invalid(
1570                    self.edge_pair(),
1571                    ep,
1572                    reason,
1573                ));
1574            }
1575            return Ok(WitTarget::Http { endpoint: ep });
1576        }
1577        if self.is_pubsub() {
1578            if endpoint.is_some() || slot.is_some() {
1579                return Err(AplicacaoError::contrato_wrong_target(
1580                    edge(),
1581                    WitTarget::PUBSUB_FIELD_NAME,
1582                ));
1583            }
1584            let s = subject.ok_or_else(|| {
1585                AplicacaoError::contrato_missing_target(edge(), WitTarget::PUBSUB_FIELD_NAME)
1586            })?;
1587            if s.is_empty() {
1588                return Err(AplicacaoError::contrato_subject_empty(self.edge_pair()));
1589            }
1590            // The `:subject` lands at runtime as the NATS subject the
1591            // producer publishes to and the consumer subscribes from.
1592            // Until this gate landed `target()` only refused the
1593            // empty string; a structurally invalid subject
1594            // (`"foo..bar"` — empty token between separators,
1595            // `"foo.>.bar"` — non-trailing `>` wildcard the NATS
1596            // server's subject parser rejects, `"foo bar"` —
1597            // un-percent-encoded whitespace, `"foo.café"` —
1598            // un-percent-encoded non-ASCII, `".foo"` / `"foo."` —
1599            // empty leading/trailing tokens, the >256-byte
1600            // paste-from-binary slug) silently passed validate and
1601            // the failure surfaced at runtime as a NATS server-side
1602            // `-ERR 'Invalid Subject'` on publish / subscribe, or as
1603            // a silent message drop, far from the source caixa.lisp.
1604            // Same Gateway API HTTPPathMatch / WIT-IDL grammar
1605            // trajectory `:contratos :endpoint` (4f0390b) and
1606            // `:contratos :wit` (6226bf4) already gate, now shared
1607            // with `:contratos :subject` through the lifted
1608            // `crate::render::is_nats_subject` predicate.
1609            if let Err(reason) = crate::render::is_nats_subject(s) {
1610                return Err(AplicacaoError::contrato_subject_invalid(
1611                    self.edge_pair(),
1612                    s,
1613                    reason,
1614                ));
1615            }
1616            return Ok(WitTarget::PubSub { subject: s });
1617        }
1618        if self.is_store() {
1619            if endpoint.is_some() || subject.is_some() {
1620                return Err(AplicacaoError::contrato_wrong_target(
1621                    edge(),
1622                    WitTarget::STORE_FIELD_NAME,
1623                ));
1624            }
1625            let sl = slot.ok_or_else(|| {
1626                AplicacaoError::contrato_missing_target(edge(), WitTarget::STORE_FIELD_NAME)
1627            })?;
1628            if sl.is_empty() {
1629                return Err(AplicacaoError::contrato_slot_empty(self.edge_pair()));
1630            }
1631            // Value-shape gate on the third (and last) typed payload
1632            // axis the `WitContract::target` dispatch carries — the
1633            // peer of [`crate::render::is_gateway_api_http_path`] for
1634            // `:endpoint` (4f0390b) and [`crate::render::is_nats_subject`]
1635            // for `:subject` (63e18a0). Until this gate landed
1636            // `target()` only refused the empty string; a structurally
1637            // invalid slot (`"check out/$order"` — un-percent-encoded
1638            // whitespace whose runtime behavior varies unpredictably
1639            // across kv backends, `"checkout/\x01order"` — control
1640            // character that Redis admits but corrupts on next read
1641            // and DynamoDB rejects outright, `"chéckout/$order"` —
1642            // un-percent-encoded non-ASCII byte each backend re-encodes
1643            // differently, `"checkout\n/$order"` — embedded newline,
1644            // the 513-byte paste-from-binary slug) silently passed
1645            // validate and surfaced at runtime as a per-backend kv
1646            // write rejection (DynamoDB / etcd) or as a silent
1647            // next-read corruption (Redis-via-RESP3), far from the
1648            // source caixa.lisp with no field naming which `:contratos`
1649            // edge carried the typo. The lifted predicate makes the
1650            // kv-backend intersection-floor a substrate-level
1651            // invariant at validate time, not a runtime "this passed
1652            // validate but the kv backend rejected on first write"
1653            // surprise — closes the typed payload-axis value-shape
1654            // trajectory across all three legs of the four
1655            // [`WitTarget`] arms (HTTP / PubSub / Store / Capability)
1656            // that caixa-mesh + the future kv emitters land in.
1657            if let Err(reason) = crate::render::is_wasi_keyvalue_slot(sl) {
1658                return Err(AplicacaoError::contrato_slot_invalid(
1659                    self.edge_pair(),
1660                    sl,
1661                    reason,
1662                ));
1663            }
1664            return Ok(WitTarget::Store { slot: sl });
1665        }
1666
1667        // Unrecognized WIT world — must not carry any payload target.
1668        if endpoint.is_some() || subject.is_some() || slot.is_some() {
1669            return Err(AplicacaoError::contrato_wrong_target(
1670                edge(),
1671                WitTarget::CAPABILITY_EXPECTED,
1672            ));
1673        }
1674        Ok(WitTarget::Capability)
1675    }
1676
1677    /// Substrate-canonical post-validation projection of the typed
1678    /// [`WitTarget`] view — the panic-on-failure shorthand every renderer
1679    /// downstream of an [`AplicacaoSpec`] that has already crossed the
1680    /// [`AplicacaoSpec::validate`] gate (typically via a caixa-mesh
1681    /// [`typed_view`]-shaped entry point that composes `validate` into
1682    /// the projection) reaches through when it needs the typed
1683    /// [`WitTarget`] and knows the containing [`AplicacaoSpec::validate`]
1684    /// has already admitted the `(:wit, :endpoint/:subject/:slot)` shape
1685    /// coherence for every `:contratos` entry. The peer accessor to the
1686    /// [`Self::target`] `Result`-returning validator on the same
1687    /// per-`:contratos` typed-projection axis — [`Self::target`] is the
1688    /// pre-validation validator that computes the projection *and* raises
1689    /// the [`AplicacaoError::Contrato*`] diagnostic cascade on any
1690    /// (`:wit`, payload) mismatch; this method is the post-validation
1691    /// projection every downstream consumer reaches through once the
1692    /// pre-validation gate has succeeded.
1693    ///
1694    /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
1695    ///
1696    /// Prior to this lift the "call `.target()` then `.expect(…)` with
1697    /// the same message" pattern sat inline at two production sites with
1698    /// no compile-time link between them: the
1699    /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)` CNP
1700    /// L7 introspection branch at `caixa-mesh/src/lib.rs:2825`
1701    /// (`c.target().expect("validated by typed_view").http_endpoint()`)
1702    /// and the [`caixa_feira::cmd::app`] `feira app graph` per-`:contratos`
1703    /// payload-column printer at `caixa-feira/src/cmd/app.rs:110`
1704    /// (`c.target().expect("validated by typed_view").graph_label()`),
1705    /// each open-coding the same `.target().expect("validated by
1706    /// typed_view")` pair with the message spelled twice. A future
1707    /// vocabulary shift on the panic-message axis (a tightening from
1708    /// `"validated by typed_view"` to `"validated by AplicacaoSpec::
1709    /// validate"` as the substrate's validator entry-point vocabulary
1710    /// sharpens, a per-consumer disambiguation, an M4 promotion of the
1711    /// panic to a `debug_assert` under a `--release` build profile) would
1712    /// have had to be threaded through both open-coded call sites in
1713    /// lockstep or one consumer would silently disagree with the peer on
1714    /// which invariant the panic message names. Same "same shape written
1715    /// verbatim ≥ 2 times becomes a typed helper" duplication-budget
1716    /// discipline the sibling [`Self::edge_pair`] /
1717    /// [`Self::edge_triple`] / [`Self::identity`] composite-projection
1718    /// lifts already establish on the paired composite-projection axis;
1719    /// this lift extends it onto the post-validation typed-view axis.
1720    ///
1721    /// Every future downstream consumer of the projected typed view
1722    /// (the future M4 per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao`
1723    /// CR materializer's per-edge admission webhook, the future
1724    /// Envoy-side per-typed-arm `local_rate_limit.descriptor_entries`
1725    /// bucket-key resolver, the future per-`:contratos`-edge mTLS overlay
1726    /// resolver, the future `feira app graph --l7` / `--pubsub` /
1727    /// `--kv` per-shape column emitters) reaches through this one typed
1728    /// dispatch on the substrate primitive rather than an open-coded
1729    /// per-consumer `.target().expect(…)` pair with the message
1730    /// re-inlined. The invariant the accessor's panic path pins — "this
1731    /// call is only reachable after [`AplicacaoSpec::validate`] has
1732    /// succeeded on the containing spec" — is the substrate's answer to
1733    /// give exactly once, at the primitive, not once per consumer.
1734    ///
1735    /// # Panics
1736    ///
1737    /// Panics with [`Self::PROJECTED_INVARIANT_MSG`] if [`Self::target`]
1738    /// would return an `Err` — i.e. if this contract's
1739    /// (`:wit`, `:endpoint`/`:subject`/`:slot`) shape has not been
1740    /// crossed by the [`AplicacaoSpec::validate`] gate cascade. Call
1741    /// this accessor only from a code path that has already reached the
1742    /// containing [`AplicacaoSpec`] through a validating entry-point
1743    /// (caixa-mesh's [`typed_view`], caixa-feira's `feira app graph`'s
1744    /// [`typed_view`] compose, the future M4 CR admission webhook's
1745    /// per-CR validate). Use [`Self::target`] instead on any pre-
1746    /// validation code path.
1747    ///
1748    /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
1749    #[must_use]
1750    pub fn target_projected(&self) -> WitTarget<'_> {
1751        self.target().expect(Self::PROJECTED_INVARIANT_MSG)
1752    }
1753
1754    /// Canonical panic message the [`Self::target_projected`]
1755    /// post-validation projection accessor threads through when the
1756    /// caller has violated the "call only after [`AplicacaoSpec::validate`]
1757    /// has succeeded" precondition. Lifted as a `pub const` on the
1758    /// [`WitContract`] surface so the byte-string lives in one place
1759    /// across the substrate — the [`Self::target_projected`] method
1760    /// body, the two prior production call sites' comments now naming
1761    /// the const, and every future consumer that must format-match the
1762    /// panic-message shape (a future test suite that asserts the panic-
1763    /// message byte-string across a fuzzed invalid-contract corpus,
1764    /// a future custom-panic hook in `caixa-operator` that surfaces the
1765    /// message with per-`:contratos` telemetry, the future admission
1766    /// webhook's per-CR validate-error report) reaches through the same
1767    /// canonical `&'static str`. A future rebrand on the panic-message
1768    /// axis (a tightening from `"validated by typed_view"` to `"validated
1769    /// by AplicacaoSpec::validate"` as the substrate's validator
1770    /// entry-point vocabulary sharpens once caixa-core grows a
1771    /// `Caixa::validated_aplicacao_view` companion to caixa-mesh's
1772    /// [`typed_view`]) lands at one caixa-core edit rather than a
1773    /// coordinated per-consumer sweep — same "one canonical declaration
1774    /// per axis, next to the accessor that reads it" discipline the peer
1775    /// [`WitTarget::CAPABILITY_LABEL`] / [`WitTarget::CAPABILITY_EXPECTED`]
1776    /// / [`WitTarget::CAPABILITY_GRAPH_LABEL`] payload-less-arm scalar-
1777    /// const family already establishes on the paired per-consumer-axis
1778    /// diagnostic-scalar surface.
1779    pub const PROJECTED_INVARIANT_MSG: &'static str = "validated by typed_view";
1780}
1781
1782/// Borrowed identity key for the typed-graph duplicate-`:contratos`
1783/// gate (see [`AplicacaoSpec::validate`]): every field that
1784/// distinguishes one contract from another, in declaration order
1785/// (`(de, para, wit, endpoint, subject, slot)`). Two [`WitContract`]s
1786/// with equal [`ContratoIdentity`]s are the same typed edge declared
1787/// twice — the graph-edge analogue of duplicate `:membros` /
1788/// `:placement :clusters` / `:entrada :paths` entries. Lifted as a
1789/// type alias so the duplicate-gate's `HashSet<…>` type doesn't trip
1790/// clippy's `type_complexity` lint (and so a future axis added to
1791/// `WitContract` is one alias edit, not a coordinated rewrite of
1792/// every set instantiation).
1793pub type ContratoIdentity<'a> = (
1794    &'a str,
1795    &'a str,
1796    &'a str,
1797    Option<&'a str>,
1798    Option<&'a str>,
1799    Option<&'a str>,
1800);
1801
1802/// Typed view of a [`WitContract`]'s payload target. Each variant
1803/// carries the field its WIT shape requires; constructing a `Http`
1804/// view without an endpoint is impossible by the type system.
1805///
1806/// Renderers (caixa-mesh L7 rules, feira app graph) match on this
1807/// instead of probing `Option<String>` fields one by one — the
1808/// "which payload field is set?" question is answered once, at
1809/// validation time.
1810#[derive(Debug, Clone, Copy, PartialEq, Eq, gen_platform::IsVariant)]
1811pub enum WitTarget<'a> {
1812    /// HTTP-shaped WIT world. Carries the configured request path.
1813    Http { endpoint: &'a str },
1814    /// Pub-sub-shaped WIT world. Carries the event-stream subject.
1815    ///
1816    /// The `IsVariant` derive would auto-name the predicate `is_pub_sub`
1817    /// (`discriminant_to_snake("PubSub") == "pub_sub"`); the explicit
1818    /// `#[is_variant(name = "pubsub")]` override keeps the emitted
1819    /// method name byte-identical to the sibling
1820    /// [`WitContract::is_pubsub`] predicate (the paired shape-side
1821    /// arm-discriminator that routes through
1822    /// [`wit_shape_is_pubsub`] on the wit-world-ref scalar rather than
1823    /// through `matches!` on the variant), so the two arm-discriminator
1824    /// axes — target-side variant-arm and shape-side ref-prefix — reach
1825    /// every downstream consumer through the same `is_pubsub()` name.
1826    #[is_variant(name = "pubsub")]
1827    PubSub { subject: &'a str },
1828    /// Key-value-shaped WIT world. Carries the slot template.
1829    Store { slot: &'a str },
1830    /// A typed capability edge with no payload selector — the WIT
1831    /// world stands on its own (rare; reserved for plain capability
1832    /// imports or M4-and-later WIT worlds we haven't shaped yet).
1833    Capability,
1834}
1835
1836impl<'a> WitTarget<'a> {
1837    /// Canonical author-facing `:contratos` payload field name for the
1838    /// HTTP-shaped arm — the `expected: &'static str` scalar the
1839    /// [`AplicacaoError::ContratoMissingTarget`] /
1840    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1841    /// through, the `:endpoint "…"` keyword the [`WitTarget::label`]
1842    /// duplicate-edge diagnostic emits, and the `endpoint=…` prefix
1843    /// the `feira app graph` verb prints. Peer of
1844    /// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
1845    /// on the payload-field-name axis; declared as a peer const next
1846    /// to the [`WitTarget::Http`] variant so a future rename on the
1847    /// author-surface `(defcaixa … :contratos ((:de … :para … :wit …
1848    /// :endpoint …)))` field lands in exactly one place, not scattered
1849    /// across the [`WitContract::target`] gate's six `expected:`
1850    /// literals, the label template, and every downstream consumer
1851    /// that prints a per-arm prefix. Same trajectory as the peer
1852    /// [`WitTarget::label`] lift (174e96a): a single source of truth
1853    /// for the arm's shape, next to the variant declaration.
1854    pub const HTTP_FIELD_NAME: &'static str = "endpoint";
1855    /// Canonical author-facing `:contratos` payload field name for the
1856    /// pub-sub-shaped arm. Peer of [`WitTarget::HTTP_FIELD_NAME`] /
1857    /// [`WitTarget::STORE_FIELD_NAME`] on the payload-field-name axis;
1858    /// see [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1859    pub const PUBSUB_FIELD_NAME: &'static str = "subject";
1860    /// Canonical author-facing `:contratos` payload field name for the
1861    /// key/value-store-shaped arm. Peer of
1862    /// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`]
1863    /// on the payload-field-name axis; see
1864    /// [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1865    pub const STORE_FIELD_NAME: &'static str = "slot";
1866
1867    /// Canonical stable human-readable label the payload-less
1868    /// [`WitTarget::Capability`] arm renders as under [`Self::label`] —
1869    /// the byte-string every consumer that formats a payload-less
1870    /// typed capability edge as text lands on (the
1871    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` diagnostic
1872    /// naming which identical edge was declared twice, the future
1873    /// `feira app graph` verb's per-arm prefix, the future M4 per-edge
1874    /// policy resolver's audit view, the operator's mesh-graph audit).
1875    /// Peer of the payload-arm [`Self::HTTP_FIELD_NAME`] /
1876    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`]
1877    /// author-facing label-scalar consts — the same
1878    /// "one canonical declaration per arm, next to the variant, so a
1879    /// future rename lands in one place" discipline extended to the
1880    /// payload-less arm. Until this lift landed the byte-string sat
1881    /// twice — once inline in [`Self::label`]'s [`WitTarget::Capability`]
1882    /// match arm, once in the pin test asserting the label's
1883    /// [`WitTarget::Capability`] output — with no compile-time link
1884    /// between the two: a rebrand on either side (an operator-facing
1885    /// vocabulary shift, a per-consumer disambiguation like
1886    /// `"(capability — no payload; typed edge only)"`) would silently
1887    /// desynchronize until a downstream consumer surfaced the drift at
1888    /// runtime.
1889    pub const CAPABILITY_LABEL: &'static str = "(capability — no payload)";
1890
1891    /// Canonical `expected:` scalar the
1892    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1893    /// through for the payload-less [`WitTarget::Capability`] arm — the
1894    /// byte-string authors read as "this WIT world's shape is not one
1895    /// of {`HTTP`, `PubSub`, `Store`}, so it must not carry
1896    /// `:endpoint` / `:subject` / `:slot`". Peer of the payload-arm
1897    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1898    /// [`Self::STORE_FIELD_NAME`] consts on the
1899    /// `ContratoWrongTarget::expected` axis — the fourth arm of the
1900    /// same "which payload field name goes in the diagnostic" dispatch
1901    /// the three payload-arm consts cover, extended to the payload-less
1902    /// arm. Until this lift landed the byte-string sat twice — once
1903    /// inline in the [`Self::target`] Capability-arm rejection at the
1904    /// production dispatch, once in the pin test asserting the
1905    /// diagnostic's `expected:` scalar carries `"none"` verbatim — with
1906    /// no compile-time link between the two: a rebrand on either side
1907    /// (an author-facing vocabulary shift to `"capability"` /
1908    /// `"(none)"` / `"no-payload"` as the WIT registry's shape
1909    /// vocabulary sharpens, a per-consumer disambiguation as M4 splits
1910    /// [`WitTarget::Capability`] into per-shape peers) would silently
1911    /// desynchronize until a downstream consumer surfaced the drift at
1912    /// runtime. Same "one canonical declaration per arm, next to the
1913    /// variant, so a future rename lands in one place" discipline the
1914    /// peer [`Self::CAPABILITY_LABEL`] lift (7ed03a3-era) already
1915    /// established for the payload-less arm's human-readable label
1916    /// axis; this lift extends it onto the peer diagnostic-scalar axis
1917    /// so both halves of the "how does the Capability arm surface at
1918    /// its two consumer axes (human-readable label, wrong-target
1919    /// diagnostic)" pipeline route through peer consts declared next
1920    /// to the variant.
1921    ///
1922    /// Pairwise-distinctness against the three payload-arm scalars
1923    /// ([`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1924    /// [`Self::STORE_FIELD_NAME`]) is pinned by the sibling
1925    /// `wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`
1926    /// test — the 4-way closure of the 3-way
1927    /// `wit_target_field_names_are_pairwise_distinct` sibling pin onto
1928    /// the `ContratoWrongTarget::expected` axis, matching the peer
1929    /// `m3_placement_estrategia_consts_are_pairwise_distinct` closed-set
1930    /// scalar-value distinctness discipline the sibling M3 typed-enum
1931    /// discriminator axis already carries.
1932    pub const CAPABILITY_EXPECTED: &'static str = "none";
1933
1934    /// Canonical `feira app graph` per-`:contratos`-edge payload-column
1935    /// byte-string the payload-less [`WitTarget::Capability`] arm renders
1936    /// as under [`Self::graph_label`] — the sibling
1937    /// [`WitTarget::CAPABILITY_LABEL`] scalar on the peer graph-verb
1938    /// payload-column axis (the graph verb spells payload-less as
1939    /// `(capability-only)`, distinct from the duplicate-`:contratos`
1940    /// diagnostic's `(capability — no payload)` on the human-readable
1941    /// [`Self::label`] axis). Peer of [`Self::CAPABILITY_LABEL`] /
1942    /// [`Self::CAPABILITY_EXPECTED`] on the payload-less-arm scalar-const
1943    /// family — extends the "one canonical declaration per arm, next to
1944    /// the variant, so a future rename lands in one place" discipline
1945    /// onto the third payload-less-arm consumer axis (`feira app graph`
1946    /// payload column, joining the [`Self::label`] duplicate-`:contratos`
1947    /// diagnostic axis and the [`Self::target`] wrong-target diagnostic
1948    /// axis).
1949    ///
1950    /// Until this lift landed the byte-string sat inline in
1951    /// [`caixa-feira`]'s `cmd::app::GraphArgs::run` per-`:contratos` payload-
1952    /// column match at `caixa-feira/src/cmd/app.rs:111` as a raw
1953    /// `"(capability-only)".to_string()` literal, with no compile-time link
1954    /// back to the [`WitTarget::Capability`] variant declaration nor to
1955    /// the sibling [`Self::CAPABILITY_LABEL`] / [`Self::CAPABILITY_EXPECTED`]
1956    /// peer consts already carrying the "one canonical declaration per
1957    /// payload-less-arm consumer axis" discipline. A rebrand on either
1958    /// side (the graph verb's operator-facing vocabulary tightening from
1959    /// `"(capability-only)"` to `"capability"` / `"(capability edge)"` as
1960    /// the WIT registry vocabulary sharpens, an M4 split of
1961    /// [`Self::Capability`] into per-shape peers) would silently
1962    /// desynchronize the graph-verb byte-string from the paired
1963    /// per-arm-adjacent const and land two spellings of the same axis in
1964    /// two spots.
1965    pub const CAPABILITY_GRAPH_LABEL: &'static str = "(capability-only)";
1966
1967    /// The `(author-facing field name, payload)` pair this typed target
1968    /// arm carries — `Some((HTTP_FIELD_NAME, endpoint))` for
1969    /// [`Self::Http`], `Some((PUBSUB_FIELD_NAME, subject))` for
1970    /// [`Self::PubSub`], `Some((STORE_FIELD_NAME, slot))` for
1971    /// [`Self::Store`], `None` for the payload-less
1972    /// [`Self::Capability`] arm.
1973    ///
1974    /// Lifted as the single 4-arm dispatch that both [`Self::label`]
1975    /// (formats `":{field} {payload:?}"` on `Some`, falls to
1976    /// [`Self::CAPABILITY_LABEL`] on `None`) and [`Self::field_name`]
1977    /// (returns the first component) route through, so a future
1978    /// [`WitTarget`] variant addition — the M4-and-later per-edge WIT
1979    /// registry may split [`Self::Http`] into `Rest` / `Grpc` peers,
1980    /// or extend [`Self::Store`] with a `Queue`-shaped peer — becomes
1981    /// exactly one new match-arm here (a compile-time exhaustiveness
1982    /// error otherwise), not a coordinated three-way rewrite of the
1983    /// prior [`Self::label`] template + [`Self::field_name`] dispatch
1984    /// + every downstream consumer that reaches for the pair.
1985    ///
1986    /// Until this lift landed the three payload arms sat in
1987    /// [`Self::label`] as three near-identical `format!(":{} {…:?}", …)`
1988    /// invocations (one per variant, each hand-quoting the paired
1989    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1990    /// [`Self::STORE_FIELD_NAME`] const) — the canonical
1991    /// "same shape, written N times" duplication THEORY.md §I.3.5
1992    /// ("Generation first, composition second, hand-authoring last;
1993    /// the duplication budget is zero") promotes to a build-time
1994    /// concern, with each per-arm site paired to its own const with no
1995    /// compile-time link between the format template and the arm's
1996    /// payload extraction.
1997    #[must_use]
1998    pub const fn payload_pair(&self) -> Option<(&'static str, &'a str)> {
1999        match *self {
2000            WitTarget::Http { endpoint } => Some((Self::HTTP_FIELD_NAME, endpoint)),
2001            WitTarget::PubSub { subject } => Some((Self::PUBSUB_FIELD_NAME, subject)),
2002            WitTarget::Store { slot } => Some((Self::STORE_FIELD_NAME, slot)),
2003            WitTarget::Capability => None,
2004        }
2005    }
2006
2007    /// The canonical author-facing `:contratos` payload field name
2008    /// this typed target arm carries (`Http` → `Some("endpoint")`,
2009    /// `PubSub` → `Some("subject")`, `Store` → `Some("slot")`), or
2010    /// `None` for the payload-less `Capability` arm.
2011    ///
2012    /// Routes through [`Self::payload_pair`] — the single 4-arm
2013    /// dispatch [`Self::label`] also reads — so a future variant
2014    /// addition is one match-arm edit at [`Self::payload_pair`], not a
2015    /// per-consumer rewrite. Same "exhaustive-match at one canonical
2016    /// dispatch, thin projections at each consumer" trajectory the
2017    /// peer [`PlacementStrategy::as_str`] / [`std::fmt::Display`]
2018    /// pair (0a2f653) landed on the sibling M3 typed-enum axis.
2019    #[must_use]
2020    pub const fn field_name(&self) -> Option<&'static str> {
2021        match self.payload_pair() {
2022            Some((f, _)) => Some(f),
2023            None => None,
2024        }
2025    }
2026
2027    /// The underlying scalar the payload-carrying arm carries — the
2028    /// per-arm request path ([`Self::Http`] `:endpoint`), event-stream
2029    /// subject ([`Self::PubSub`] `:subject`), or slot template
2030    /// ([`Self::Store`] `:slot`), borrowed from the typed slot's own
2031    /// `&'a str` storage — or `None` on the payload-less
2032    /// [`Self::Capability`] arm.
2033    ///
2034    /// Thin projection onto the single 4-arm [`Self::payload_pair`]
2035    /// dispatch (`self.payload_pair().map(|(_, p)| p)` in `const fn`
2036    /// form) — peer of [`Self::field_name`] (`.payload_pair().0`) on
2037    /// the paired sub-selector axis. Both per-half accessors read from
2038    /// one authoritative match, so a future [`WitTarget`] variant
2039    /// addition (`Rest`/`Grpc` split of [`Self::Http`], `Queue`-shaped
2040    /// peer of [`Self::Store`]) lands at exactly one caixa-core edit
2041    /// on [`Self::payload_pair`] and both per-half projections + every
2042    /// downstream consumer picks the new arm up by construction — no
2043    /// coordinated N-way rewrite across the paired accessor dispatches,
2044    /// the [`Self::label`] / [`Self::graph_label`] format templates,
2045    /// and every future WIT-registry-shaped consumer.
2046    ///
2047    /// Peer of the sibling [`caixa-flux`][caixa-flux-crate]
2048    /// `GitRefSpec::ref_value` projection on the `FluxCD` source-
2049    /// controller `spec.ref.<field>` axis — same "one paired dispatch,
2050    /// both per-half projections as thin readers, every downstream
2051    /// consumer through the same match" discipline extended onto the
2052    /// M3 `:contratos` payload-arm axis. Closes the discipline-parity
2053    /// gap between the two paired-dispatch surfaces: the peer
2054    /// [`Self::payload_pair`] + [`Self::field_name`] pair carried only
2055    /// the first-component projection until this lift; the second-
2056    /// component sibling now sits alongside so both halves reach every
2057    /// future consumer through the same substrate-primitive dispatch.
2058    ///
2059    /// [caixa-flux-crate]: https://docs.rs/caixa-flux/latest/caixa_flux/enum.GitRefSpec.html#method.ref_value
2060    #[must_use]
2061    pub const fn payload(&self) -> Option<&'a str> {
2062        match self.payload_pair() {
2063            Some((_, p)) => Some(p),
2064            None => None,
2065        }
2066    }
2067
2068    /// Substrate-canonical per-arm HTTP-endpoint scalar accessor every
2069    /// consumer that fans on the L7-HTTP-shaped payload keys off —
2070    /// returns the [`Self::Http`]-arm's author-declared request path
2071    /// verbatim as an `Option<&'a str>`, `Some(endpoint)` when the
2072    /// projected target is [`Self::Http { endpoint }`], `None` on the
2073    /// three sibling arms ([`Self::PubSub`] / [`Self::Store`] /
2074    /// [`Self::Capability`], each of which carries no HTTP endpoint by
2075    /// definition).
2076    ///
2077    /// The [`Self::Http`] arm carries the Cilium L7 `HTTPNetworkPolicy`
2078    /// `path:` rule payload every substrate-side L7-introspecting
2079    /// per-`(:de, :para)` `CiliumNetworkPolicy` emitter reads (today: the
2080    /// [`caixa_mesh::cilium_network_policies`] per-edge `toPorts[].rules
2081    /// .http[0].path` scalar the HTTP-shape-only L7 rule builder emits
2082    /// on the L7 introspection branch; every peer WIT shape stays
2083    /// L4-only because Cilium can't introspect NATS / key-value / plain
2084    /// capability edges), and every future L7-introspecting consumer
2085    /// of the projected target's HTTP endpoint (the future M4
2086    /// per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao` CR
2087    /// materializer's per-edge L7 admission-webhook overlay, the
2088    /// future Envoy-side `local_rate_limit.descriptor_entries` per-HTTP-
2089    /// path bucket-key resolver, the future per-`:contratos`-edge
2090    /// mTLS-required overlay's HTTP-shape scope filter, the future
2091    /// `feira app graph --l7` per-Aplicacao HTTP-path column) reaches
2092    /// through the same typed dispatch.
2093    ///
2094    /// Prior to this lift the sole production consumer of the projected-
2095    /// target HTTP endpoint — the [`caixa_mesh::cilium_network_policies`]
2096    /// per-edge L7 introspection branch at `caixa-mesh/src/lib.rs:2759`
2097    /// (`if let WitTarget::Http { endpoint } = c.target().expect(…) {
2098    /// http_rule.insert_string(CILIUM_KEY_PATH, endpoint.to_string()); …
2099    /// }`) — reached the payload through a raw per-arm `if let` pattern-
2100    /// match that expressed no compile-time link back to the substrate
2101    /// primitive's typed dispatch, sibling to the [`WitContract`] pre-
2102    /// projection [`WitContract::endpoint`] (7020470) `Option<&str>`
2103    /// scalar accessor on the peer per-`:contratos` raw-field axis but
2104    /// with no post-projection peer on the typed-view surface. A future
2105    /// [`WitTarget`] variant addition that splits [`Self::Http`] into
2106    /// peers (a `Rest`/`Grpc` split once the WIT registry stabilizes
2107    /// gRPC-shaped worlds per this enum's own docstring at
2108    /// aplicacao.rs:1341-1343 — with a `Rest`-arm `endpoint: &'a str`
2109    /// payload alongside a `Grpc`-arm `service_method: &'a str` payload)
2110    /// would have had to be threaded through the caixa-mesh L7 emit
2111    /// branch's raw `if let` in lockstep — either coalescing the two
2112    /// L7-HTTP-family arms under a shared `path:` emit, or splitting the
2113    /// emit path per-arm — with no substrate-primitive dispatch making
2114    /// the "which arms count as L7-HTTP-shaped for path-emission
2115    /// purposes" question the substrate's answer to give. Lifting the
2116    /// resolution to a typed method on the substrate primitive means
2117    /// every downstream L7-HTTP-facing consumer of the Aplicacao's
2118    /// projected-target HTTP endpoint reaches for exactly one typed
2119    /// dispatch — the resolver's accept-set migrates as a unit on any
2120    /// future arm-family widening, and the caixa-mesh L7 emit branch
2121    /// reads through the same substrate primitive.
2122    ///
2123    /// Peer of the sibling pre-projection [`WitContract::endpoint`]
2124    /// (7020470) `Option<&str>` scalar accessor on the raw
2125    /// `:contratos :endpoint` field-access axis — same "one typed
2126    /// dispatch on the substrate primitive, thin projections at each
2127    /// consumer" discipline extended onto the peer post-projection typed-
2128    /// view surface (the [`WitContract::endpoint`] pre-projection
2129    /// accessor returns `Some` for any author-declared `:endpoint`
2130    /// value regardless of the paired `:wit` world's HTTP-shape
2131    /// classification — the raw slot before validation crosses it —
2132    /// while this post-projection [`Self::http_endpoint`] accessor
2133    /// returns `Some` iff the target has been projected onto the
2134    /// [`Self::Http`] arm, i.e. only after the [`WitContract::target`]
2135    /// gate has admitted the `(:wit, :endpoint/:subject/:slot)` shape
2136    /// coherence; the two accessors close the pre-projection /
2137    /// post-projection pair on the HTTP-endpoint axis). Sibling of the
2138    /// unified pan-arm [`Self::payload`] (`Option<&'a str>` for any of
2139    /// the three payload-carrying arms) — extends the per-arm
2140    /// projection family onto the [`Self::Http`] specialization axis
2141    /// that the pan-arm accessor's shape blends into a single arm-
2142    /// agnostic view; paired with [`Self::pubsub_subject`] /
2143    /// [`Self::store_slot`] on the sibling per-arm axes so every
2144    /// per-payload-arm shape carries a named post-projection accessor
2145    /// on the same shape as `http_endpoint`, closing the per-arm-shape
2146    /// accept-set the substrate primitive owns.
2147    #[must_use]
2148    pub const fn http_endpoint(&self) -> Option<&'a str> {
2149        match *self {
2150            WitTarget::Http { endpoint } => Some(endpoint),
2151            WitTarget::PubSub { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
2152        }
2153    }
2154
2155    /// Substrate-canonical per-arm pub-sub-subject scalar accessor every
2156    /// consumer that fans on the pub-sub-shaped payload keys off —
2157    /// returns the [`Self::PubSub`]-arm's author-declared event-stream
2158    /// subject verbatim as an `Option<&'a str>`, `Some(subject)` when
2159    /// the projected target is [`Self::PubSub { subject }`], `None` on
2160    /// the three sibling arms ([`Self::Http`] / [`Self::Store`] /
2161    /// [`Self::Capability`], each of which carries no NATS-shaped
2162    /// subject by definition).
2163    ///
2164    /// The [`Self::PubSub`] arm carries the NATS-server-accepted subject
2165    /// the future substrate-side pub-sub-introspecting per-`(:de, :para)`
2166    /// consumer keys off (the M4 per-Aplicacao NATS `Stream` / `Consumer`
2167    /// CR materializer's `spec.subjects[]` projection, the future
2168    /// Envoy-side per-subject `local_rate_limit.descriptor_entries`
2169    /// bucket-key resolver, the future `feira app graph --pubsub`
2170    /// per-Aplicacao subject column, any future substrate-lifted
2171    /// pub-sub-shape emitter that reads a projected `WitTarget` in the
2172    /// same shape [`caixa_mesh::cilium_network_policies`] reads the
2173    /// HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today). Every
2174    /// future pub-sub-shape consumer reaches for the same typed
2175    /// dispatch this accessor exposes so the "which arm carries the
2176    /// subject scalar?" answer lives at one caixa-core edit rather
2177    /// than open-coded across per-consumer `if let WitTarget::PubSub
2178    /// { subject } = c.target()…` pattern-matches.
2179    ///
2180    /// Peer of the sibling [`Self::http_endpoint`] (5d6dc92 trajectory)
2181    /// per-arm HTTP-endpoint accessor on the peer per-arm axis and of
2182    /// the pre-projection [`WitContract::subject`] scalar accessor on
2183    /// the raw `:contratos :subject` field-access axis — same "one
2184    /// typed dispatch on the substrate primitive, thin projections at
2185    /// each consumer" discipline extended onto the per-arm pub-sub
2186    /// post-projection axis. The pre-projection accessor returns
2187    /// `Some` for any author-declared `:subject` value regardless of
2188    /// the paired `:wit` world's pub-sub-shape classification (the raw
2189    /// slot before validation crosses it); this post-projection
2190    /// accessor returns `Some` iff the target has been projected onto
2191    /// the [`Self::PubSub`] arm, i.e. only after the
2192    /// [`WitContract::target`] gate has admitted the
2193    /// `(:wit, :endpoint/:subject/:slot)` shape coherence — closing
2194    /// the pre-/post-projection pair on the pub-sub-subject axis to
2195    /// match the pair the [`WitContract::endpoint`] +
2196    /// [`Self::http_endpoint`] surfaces already close on the peer
2197    /// HTTP-endpoint axis.
2198    ///
2199    /// Sibling of the unified pan-arm [`Self::payload`]
2200    /// (`Option<&'a str>` for any of the three payload-carrying arms) —
2201    /// extends the per-arm projection family onto the [`Self::PubSub`]
2202    /// specialization axis that the pan-arm accessor's shape blends
2203    /// into a single arm-agnostic view; the pair
2204    /// (`pubsub_subject`, `store_slot`) closes the trio
2205    /// (`http_endpoint`, `pubsub_subject`, `store_slot`) so every
2206    /// payload arm now carries its own per-arm-shape post-projection
2207    /// accessor.
2208    #[must_use]
2209    pub const fn pubsub_subject(&self) -> Option<&'a str> {
2210        match *self {
2211            WitTarget::PubSub { subject } => Some(subject),
2212            WitTarget::Http { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
2213        }
2214    }
2215
2216    /// Substrate-canonical per-arm key/value-store-slot scalar accessor
2217    /// every consumer that fans on the store-shaped payload keys off —
2218    /// returns the [`Self::Store`]-arm's author-declared slot template
2219    /// verbatim as an `Option<&'a str>`, `Some(slot)` when the
2220    /// projected target is [`Self::Store { slot }`], `None` on the
2221    /// three sibling arms ([`Self::Http`] / [`Self::PubSub`] /
2222    /// [`Self::Capability`], each of which carries no
2223    /// key/value-store slot by definition).
2224    ///
2225    /// The [`Self::Store`] arm carries the WASI-key/value-accepted slot
2226    /// template (validated by [`crate::render::is_wasi_keyvalue_slot`])
2227    /// every future substrate-side store-introspecting per-`(:de,
2228    /// :para)` consumer keys off (the M4 per-Aplicacao WASI-key/value
2229    /// namespace / prefix reconciler's per-slot projection, the future
2230    /// per-store-backend routing overlay's slot-shape gate, the future
2231    /// `feira app graph --store` per-Aplicacao slot column, any future
2232    /// substrate-lifted store-shape emitter that reads a projected
2233    /// `WitTarget` in the same shape [`caixa_mesh::cilium_network_policies`]
2234    /// reads the HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today).
2235    /// Every future store-shape consumer reaches for the same typed
2236    /// dispatch this accessor exposes so the "which arm carries the
2237    /// slot scalar?" answer lives at one caixa-core edit rather than
2238    /// open-coded across per-consumer
2239    /// `if let WitTarget::Store { slot } = c.target()…`
2240    /// pattern-matches.
2241    ///
2242    /// Peer of the sibling [`Self::http_endpoint`] +
2243    /// [`Self::pubsub_subject`] per-arm accessors on the peer per-arm
2244    /// axes and of the pre-projection [`WitContract::slot`] scalar
2245    /// accessor on the raw `:contratos :slot` field-access axis — same
2246    /// "one typed dispatch on the substrate primitive, thin projections
2247    /// at each consumer" discipline extended onto the per-arm store
2248    /// post-projection axis. Closes the pre-/post-projection pair on
2249    /// the store-slot axis to match the pairs the
2250    /// [`WitContract::endpoint`] + [`Self::http_endpoint`] and
2251    /// [`WitContract::subject`] + [`Self::pubsub_subject`] surfaces
2252    /// already close on the peer HTTP-endpoint and pub-sub-subject
2253    /// axes; the substrate-side pre-/post-projection accessor family
2254    /// now spans all three payload arms as a matched trio, so any
2255    /// future arm-shape widening (a `Rest`/`Grpc` split of
2256    /// [`Self::Http`], a `Queue`-shaped peer of [`Self::Store`]) that
2257    /// lands one accessor without threading through the sibling
2258    /// pre-projection or the peer per-arm post-projection surfaces a
2259    /// compile-time exhaustiveness error at the substrate primitive,
2260    /// not a silent per-consumer split at renderer emit time.
2261    ///
2262    /// Sibling of the unified pan-arm [`Self::payload`]
2263    /// (`Option<&'a str>` for any of the three payload-carrying arms) —
2264    /// closes the per-arm projection family onto the [`Self::Store`]
2265    /// specialization axis that the pan-arm accessor's shape blends
2266    /// into a single arm-agnostic view. The trio
2267    /// (`http_endpoint`, `pubsub_subject`, `store_slot`) partitions the
2268    /// pan-arm accept-set on every payload-carrying arm: exactly one
2269    /// per-arm accessor returns `Some(payload)` and the two peers
2270    /// return `None`, and every payload-less [`Self::Capability`]
2271    /// input returns `None` on all three — the partition the sibling
2272    /// `wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`
2273    /// pin locks in load-bearing.
2274    #[must_use]
2275    pub const fn store_slot(&self) -> Option<&'a str> {
2276        match *self {
2277            WitTarget::Store { slot } => Some(slot),
2278            WitTarget::Http { .. } | WitTarget::PubSub { .. } | WitTarget::Capability => None,
2279        }
2280    }
2281
2282    /// Render this typed target as a stable human-readable label
2283    /// (`:endpoint "/charge"`, `:subject "events.x"`,
2284    /// `:slot "checkout/$order"`, or `(capability — no payload)` when
2285    /// the WIT world is a pure capability edge).
2286    ///
2287    /// Used by the [`AplicacaoSpec::validate`] duplicate-`:contratos`
2288    /// gate so the diagnostic names *which* identical edge was
2289    /// declared twice (not just which `(de, para, wit)` triple).
2290    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
2291    /// on the payload-carrying arms (`Some((field, payload)) →
2292    /// format!(":{field} {payload:?}")`) and through the lifted
2293    /// [`Self::CAPABILITY_LABEL`] const on the payload-less
2294    /// [`Self::Capability`] arm — so a future variant addition (the
2295    /// M4-and-later per-edge WIT registry may split [`Self::Http`]
2296    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
2297    /// `Queue`-shaped peer) becomes a single new match-arm on
2298    /// [`Self::payload_pair`] rather than a rewrite of this template
2299    /// (and every downstream consumer that reaches for the label
2300    /// shape: the per-edge policy resolver in M4, the `feira app
2301    /// graph` view, the operator's mesh-graph audit). Until this
2302    /// lift landed the three payload arms carried three near-identical
2303    /// per-arm `format!(":{} {…:?}", …)` invocations, and the
2304    /// [`Self::Capability`] arm carried the payload-less byte-string
2305    /// twice (once inline here, once in the pin test) — closing the
2306    /// duplication trajectory the peer [`Self::HTTP_FIELD_NAME`] /
2307    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`] (174e96a
2308    /// / 4a1e490) peer-const lifts already established for the
2309    /// payload-carrying arms.
2310    #[must_use]
2311    pub fn label(&self) -> String {
2312        match self.payload_pair() {
2313            Some((field, payload)) => format!(":{field} {payload:?}"),
2314            None => Self::CAPABILITY_LABEL.to_string(),
2315        }
2316    }
2317
2318    /// Render this typed target as the `feira app graph` per-`:contratos`
2319    /// payload-column byte-string (`endpoint=/charge`, `subject=events.x`,
2320    /// `slot=checkout/$order`, or [`Self::CAPABILITY_GRAPH_LABEL`] on the
2321    /// payload-less arm).
2322    ///
2323    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
2324    /// on the payload-carrying arms (`Some((field, payload)) →
2325    /// format!("{field}={payload}")`) and through the lifted
2326    /// [`Self::CAPABILITY_GRAPH_LABEL`] const on the payload-less
2327    /// [`Self::Capability`] arm — so a future variant addition
2328    /// (the M4-and-later per-edge WIT registry may split [`Self::Http`]
2329    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
2330    /// `Queue`-shaped peer) becomes one match-arm edit at
2331    /// [`Self::payload_pair`], propagating through this graph-verb
2332    /// projection at zero call-site cost, sibling to the peer
2333    /// [`Self::label`] duplicate-`:contratos` diagnostic emission on the
2334    /// same 4-arm dispatch.
2335    ///
2336    /// Until this lift landed the [`caixa-feira`]
2337    /// `cmd::app::GraphArgs::run` per-`:contratos` payload column
2338    /// (`caixa-feira/src/cmd/app.rs:101-112`) hand-rolled the same 4-arm
2339    /// dispatch inline, re-projecting `HTTP_FIELD_NAME` /
2340    /// `PUBSUB_FIELD_NAME` / `STORE_FIELD_NAME` under a per-arm
2341    /// `format!("{}={endpoint}", ...)` template and hard-coding
2342    /// `"(capability-only)"` as a fifth payload-less scalar with no link
2343    /// back to the paired [`WitTarget::Capability`] variant declaration.
2344    /// A future variant addition would have had to be threaded through
2345    /// both [`Self::label`] (via [`Self::payload_pair`]) *and* the graph
2346    /// verb's inline match in lockstep or the two projections would
2347    /// silently disagree on the arm-set the graph verb prints — the
2348    /// duplicate-`:contratos` diagnostic reading one shape while the
2349    /// graph verb's payload column silently dropped the new arm to
2350    /// `(capability-only)`. Lifting the graph-verb projection onto the
2351    /// same substrate-primitive [`Self::payload_pair`] dispatch closes
2352    /// the axis: both projections migrate as a unit.
2353    ///
2354    /// The `field=payload` (no colon prefix, `=` separator, no `Debug`
2355    /// quoting) shape is graph-verb-canonical — distinct from the
2356    /// sibling [`Self::label`] `":{field} {payload:?}"` shape the
2357    /// duplicate-`:contratos` diagnostic seeds (see
2358    /// [`Self::CAPABILITY_LABEL`] vs. [`Self::CAPABILITY_GRAPH_LABEL`]
2359    /// on the payload-less axis for the paired distinction).
2360    #[must_use]
2361    pub fn graph_label(&self) -> String {
2362        match self.payload_pair() {
2363            Some((field, payload)) => format!("{field}={payload}"),
2364            None => Self::CAPABILITY_GRAPH_LABEL.to_string(),
2365        }
2366    }
2367}
2368
2369/// [`std::fmt::Display`] routed through [`WitTarget::label`], so the
2370/// pretty-printed byte-string every consumer that formats a typed
2371/// payload target as user-facing text lands on (the
2372/// [`AplicacaoError::ContratoDuplicate`] diagnostic's `target:` carry
2373/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds via
2374/// [`WitTarget::label`] at aplicacao.rs:5491, the future `feira app
2375/// graph` per-`:contratos`-edge payload column that reaches the graph
2376/// verb through `format!("{target}")`, the future M4 per-edge policy
2377/// resolver's per-edge audit-log line, the operator's mesh-graph
2378/// per-edge inspection view) reaches for the same lifted
2379/// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`] /
2380/// [`WitTarget::STORE_FIELD_NAME`] / [`WitTarget::CAPABILITY_LABEL`]
2381/// const set the [`WitTarget::payload_pair`] 4-arm dispatch already
2382/// routes through — extending the three-path-convergence
2383/// (`Debug` for structural inspection, `Display` for user-facing text,
2384/// per-arm typed accessor for the canonical byte-string) discipline the
2385/// sibling M3 [`PlacementStrategy`] and M2 [`crate::supervisor::RestartStrategy`]
2386/// / [`crate::supervisor::RestartPolicy`] OTP-shape typed enums carry
2387/// onto the fourth (and only remaining) typed-shape-discriminator axis
2388/// on the caixa surface.
2389///
2390/// Pre-lift the two paths were structurally independent — every consumer
2391/// reaching for a payload byte-string past the [`WitTarget::label`]
2392/// helper had to pick between three paths ([`WitTarget::label`],
2393/// `format!("{v:?}")` on the `Debug` derive, hand-rolled per-arm
2394/// formatting through the [`WitTarget::HTTP_FIELD_NAME`] /
2395/// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`] /
2396/// [`WitTarget::CAPABILITY_LABEL`] const set), and a future consumer
2397/// that reached for `format!("{target}")` — the canonical shape every
2398/// user-facing pretty-print site on the sibling typed-enum axes already
2399/// uses — would silently land on the `Debug` derive's structural output
2400/// (`Http { endpoint: "/charge" }` — Rust struct-literal syntax) rather
2401/// than the `label()` helper's stable byte-string (`:endpoint
2402/// "/charge"` — the author-facing `:contratos` keyword form) the
2403/// substrate-side duplicate-`:contratos` gate at aplicacao.rs:5491
2404/// already threads through. The two spellings would diverge silently in
2405/// every downstream diagnostic / graph / audit line reached through
2406/// `format!` rather than through the `label()` helper. Routing
2407/// [`std::fmt::Display`] through [`WitTarget::label`] closes the third
2408/// path: every `format!("{v}")` call reaches the same
2409/// [`WitTarget::payload_pair`]-shaped byte-string the `label()` helper
2410/// and the duplicate-`:contratos` gate already route through, so a
2411/// future variant addition (the M4-and-later per-edge WIT registry may
2412/// split [`WitTarget::Http`] into `Rest` / `Grpc` peers, or extend
2413/// [`WitTarget::Store`] with a `Queue`-shaped peer) reaches every
2414/// consumer at exactly one place — the [`WitTarget::payload_pair`]
2415/// match — rather than fanning out through hand-rolled per-arm
2416/// [`std::fmt::Display`] arms.
2417///
2418/// The dispatcher-catalog identity remains unaffected — [`WitTarget`]
2419/// is the typed view returned by [`WitContract::target`], not a
2420/// closed-set discriminator enum with a gen-platform Discriminant
2421/// registration, so the `Debug` derive's structural output (which every
2422/// `{v:?}` consumer still reaches) stays distinct from the `Display`
2423/// helper's stable pretty-printed byte-string. `Debug` reveals variant
2424/// shape for structural inspection; `Display` (via `label`) reveals the
2425/// stable author-facing payload projection.
2426///
2427/// Pin tests
2428/// [`tests::wit_target_display_routes_through_label_helper`] and
2429/// [`tests::wit_target_display_matches_duplicate_contratos_diagnostic_carrier`]
2430/// assert the two paths agree byte-for-byte on every variant, so a
2431/// future variant addition or `label()` reimplementation that hand-rolls
2432/// the arms instead of delegating to [`WitTarget::payload_pair`] is a
2433/// build error visible at caixa-core test time, not a silent
2434/// per-consumer dispatch miss at diagnostic / audit / graph time.
2435impl std::fmt::Display for WitTarget<'_> {
2436    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2437        f.write_str(&self.label())
2438    }
2439}
2440
2441// ── one Aplicacao member ─────────────────────────────────────────────
2442
2443/// A Servico participating in the Aplicacao. Same shape as
2444/// `crate::supervisor::ChildSpec` but without a restart policy —
2445/// supervision is per-Servico (each member has its own
2446/// `:supervisor`), the Aplicacao orchestrates *placement*.
2447#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2448#[serde(rename_all = "camelCase")]
2449pub struct Membro {
2450    /// Member caixa's `:nome`. Resolves through the same dep
2451    /// resolution path as `crate::dep::Dep`.
2452    pub caixa: String,
2453
2454    /// Semver constraint.
2455    pub versao: String,
2456}
2457
2458impl Membro {
2459    /// Substrate-canonical per-`:membros` member-caixa `:nome` scalar
2460    /// accessor every consumer that reads the member's Servico identity
2461    /// keys off — returns the author-declared `:membros :caixa`
2462    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
2463    /// own [`String`] storage.
2464    ///
2465    /// The `:membros :caixa` slot carries the caixa `:nome` of a Servico
2466    /// participating in the Aplicacao — validated by
2467    /// [`AplicacaoSpec::validate`] to be a non-empty DNS-1123 label
2468    /// (via [`validate_membro_caixa`]), unique across the Aplicacao's
2469    /// `:membros` list, distinct from the Aplicacao's own `:nome` (via
2470    /// [`validate_no_self_membership`]) — and every downstream consumer
2471    /// that fans on the member's identity keys off this scalar (the
2472    /// [`AplicacaoSpec::validate`] `:contratos`/`:entrada` member-set
2473    /// lookup, the per-`:membros` duplicate gate's dedup key, the
2474    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency map's node
2475    /// identity, the self-membership gate, the
2476    /// [`caixa_mesh::fleet_programs`] per-member programs.yaml entry
2477    /// `name:` axis, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
2478    /// CR materializer's per-member resolver).
2479    ///
2480    /// Prior to this lift the `.caixa` byte-string was read inline at
2481    /// five caixa-core sites (the [`AplicacaoSpec::validate`] member-name
2482    /// set collector at
2483    /// `self.membros.iter().map(|m| m.caixa.as_str())`, the
2484    /// [`validate_membros`] validation-side member-caixa gate at
2485    /// `validate_membro_caixa(&m.caixa)`, the [`validate_membros`]
2486    /// per-member duplicate-gate dedup key at
2487    /// `insert_first_seen(&mut seen, m.caixa.as_str(), …)`, the
2488    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency-map seed at
2489    /// `adj.entry(m.caixa.as_str()).or_default()`, and the
2490    /// [`validate_no_self_membership`] self-loop gate at
2491    /// `m.caixa == parent_nome`) — five open-coded field-accesses that
2492    /// expressed no compile-time link back to the typed slot. Every
2493    /// caixa-mesh `metadata.name` derived from a `:membros :caixa`
2494    /// value flows through the [`caixa_mesh::fleet_programs`] per-entry
2495    /// `name:` axis, so a future extension of the `:membros :caixa`
2496    /// axis to a richer author surface — a per-cluster alias table the
2497    /// operator pins through a future `:placement`-scoped slot, a
2498    /// namespace-qualified rewrite the M4 CR materializer applies
2499    /// per-CR, a per-member overlay from the future `:membros
2500    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
2501    /// acknowledges — would have had to be threaded through every
2502    /// open-coded copy in lockstep or one consumer would silently
2503    /// disagree with the peers on which caixa a given member resolves
2504    /// to. A member-set lookup that treated the name as `"cart"` while
2505    /// the peer adjacency map treated it as `"tenant-a/cart"` would
2506    /// silently split the `:contratos` membership-lookup diagnostic from
2507    /// the cycle-detector's node identity — a two-consumer split at the
2508    /// validator far from the source `caixa.lisp` with no field naming
2509    /// the identity-drift root cause. Lifting the resolution rule to a
2510    /// typed method on the substrate primitive means every downstream
2511    /// consumer of the Aplicacao's per-`:membros` identity surface
2512    /// reaches for exactly one typed dispatch — the resolver's
2513    /// accept-set migrates as a unit on any future axis addition.
2514    ///
2515    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2516    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2517    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2518    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2519    /// destination-Servico scalar accessors — same "one typed dispatch
2520    /// on the substrate primitive, thin projections at each consumer"
2521    /// discipline extended onto the per-`:membros` member-caixa `:nome`
2522    /// byte-string axis. Named `nome()` to match the tatara-lisp
2523    /// author-surface term the field's docstring already reaches for
2524    /// ("Member caixa's `:nome`") and the peer [`crate::Caixa::nome`] /
2525    /// [`crate::dep::Dep::nome`] field-name discipline the substrate
2526    /// already carries — the accessor's name maps directly onto the
2527    /// canonical caixa-identity vocabulary rather than shadowing the
2528    /// field's storage-side `caixa` label.
2529    #[must_use]
2530    pub const fn nome(&self) -> &str {
2531        self.caixa.as_str()
2532    }
2533
2534    /// Substrate-canonical per-`:membros` member-caixa `:versao` semver-
2535    /// requirement scalar accessor every consumer that reads the
2536    /// member's version pin keys off — returns the author-declared
2537    /// `:membros :versao` byte-string verbatim as a `&str`, borrowed
2538    /// from the typed slot's own [`String`] storage.
2539    ///
2540    /// The `:membros :versao` slot carries the Cargo-shaped semver
2541    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that
2542    /// pins which release of the member-caixa the Aplicacao composes
2543    /// against — the same requirement grammar the peer `:deps :versao`
2544    /// / `:children :versao` axes carry, resolved through the shared
2545    /// [`crate::render::require_valid_versao_requirement`] cascade and
2546    /// the shared [`crate::version::parse_requirement`] parser. Every
2547    /// downstream consumer that fans on the member's version pin keys
2548    /// off this scalar (the [`validate_membros`] per-member requirement
2549    /// gate at `require_valid_versao_requirement(m.versao_requirement(),
2550    /// …)`, the [`feira app graph`] per-member `println!("    - {} {}",
2551    /// m.nome(), m.versao_requirement())` line, every future per-cluster
2552    /// version-lock overlay the operator pins through a future
2553    /// `:placement`-scoped slot, the future
2554    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-member
2555    /// version resolver, the future `feira app deploy` pipeline's
2556    /// per-member lacre BLAKE3-closure lookup).
2557    ///
2558    /// Prior to this lift the `.versao` byte-string was accessed inline
2559    /// at two `&str`-shaped sites — the [`validate_membros`]
2560    /// requirement-gate call `require_valid_versao_requirement(&m.versao,
2561    /// …)` and the `feira app graph` per-member printer's `println!(
2562    /// "    - {} {}", m.caixa, m.versao)` (caixa-feira/src/cmd/app.rs:78
2563    /// prior to this lift) — two open-coded field-accesses that expressed
2564    /// no compile-time link back to the typed slot. A future extension of
2565    /// the `:membros :versao` axis to a richer author surface (a
2566    /// per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
2567    /// flow, a lacre-projected concrete-version rewrite the operator
2568    /// materializes at CR-admission time, a future `:membros :versao-lock`
2569    /// per-cluster override slot) would have had to be threaded through
2570    /// every open-coded copy in lockstep or one consumer would silently
2571    /// disagree with the peers on which release constraint a given
2572    /// member resolves to. Lifting the resolution rule to a typed method
2573    /// on the substrate primitive means every downstream requirement-
2574    /// facing consumer reaches for exactly one typed dispatch — the
2575    /// resolver's accept-set migrates as a unit on any future axis
2576    /// addition.
2577    ///
2578    /// Sibling of the peer per-`:membros` [`Membro::nome`] (4a32abf)
2579    /// member-caixa `:nome` scalar accessor — the pair
2580    /// `(nome(), versao_requirement())` jointly projects the
2581    /// `(caixa, versao)` field pair every renderer that fans on
2582    /// per-member identity + version pin keys off, closing the last
2583    /// unlifted per-`:membros` scalar axis so every downstream
2584    /// per-`:membros` reader now routes through a typed dispatch on the
2585    /// substrate primitive. Named `versao_requirement()` rather than
2586    /// `versao()` because the field's storage-side `.versao` label is
2587    /// already the author-surface term (`:versao`); the accessor's name
2588    /// carries the semantic role — the semver *requirement* string the
2589    /// shared [`crate::version::parse_requirement`] entry-point consumes
2590    /// — so a raw field access and a typed dispatch read differently at
2591    /// every consumer site.
2592    ///
2593    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2594    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2595    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2596    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2597    /// destination-Servico scalar accessors — same "one typed dispatch
2598    /// on the substrate primitive, thin projections at each consumer"
2599    /// discipline extended onto the per-`:membros` member-`:versao`
2600    /// semver-requirement byte-string axis.
2601    #[must_use]
2602    pub const fn versao_requirement(&self) -> &str {
2603        self.versao.as_str()
2604    }
2605}
2606
2607// ── mesh-level policies ──────────────────────────────────────────────
2608
2609/// Mesh policies that apply to every `:contratos` edge unless
2610/// overridden per-edge in M4. V0 is a single global policy block.
2611#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
2612#[serde(rename_all = "camelCase")]
2613pub struct MeshPolicy {
2614    /// Per-call timeout. Authored as a duration string (`"30s"`).
2615    #[serde(
2616        default,
2617        skip_serializing_if = "Option::is_none",
2618        with = "supervisor::duration_codec"
2619    )]
2620    pub timeout: Option<Duration>,
2621
2622    /// Number of retries on transient failure. None = no retries.
2623    #[serde(default, skip_serializing_if = "Option::is_none")]
2624    pub retries: Option<u32>,
2625
2626    /// Circuit breaker config. Trips after N failures within W
2627    /// duration; closes after a cooldown.
2628    #[serde(default, skip_serializing_if = "Option::is_none")]
2629    pub circuit_breaker: Option<CircuitBreaker>,
2630
2631    /// Whether mTLS is required for every contrato. Default: true
2632    /// (sandboxing-by-default; explicit opt-out only).
2633    #[serde(default, skip_serializing_if = "Option::is_none")]
2634    pub mtls_required: Option<bool>,
2635
2636    /// Token-bucket rate limit. Authored as `"100/s"` or
2637    /// `"5000/m"`; stored as `(rate, window)`.
2638    #[serde(
2639        default,
2640        skip_serializing_if = "Option::is_none",
2641        with = "rate_limit_codec"
2642    )]
2643    pub rate_limit: Option<RateLimit>,
2644}
2645
2646impl MeshPolicy {
2647    /// True when no `:politicas` axis carries a value — every field is
2648    /// `None`. The same emptiness contract every other M2/M3 typed
2649    /// surface carries ([`crate::LimitsSpec::is_empty`],
2650    /// [`crate::BehaviorSpec::is_empty`]): renderers that overlay the
2651    /// typed slot onto a cluster artifact key off this predicate to
2652    /// decide "emit the slot" vs "skip the slot entirely", so an
2653    /// authored-but-unset `:politicas (())` round-trips to a rendered
2654    /// artifact that's structurally identical to one that omits the
2655    /// slot. Lifted as a typed predicate (rather than per-renderer
2656    /// inline `politicas.timeout.is_none() && politicas.retries.is_none()
2657    /// && …` chains) so a future axis added to `MeshPolicy` (per-edge
2658    /// :politicas overlay in M4, per-Aplicacao traffic-shaping in M5)
2659    /// is one struct-field edit + one `&& self.<axis>.is_none()` here,
2660    /// not a coordinated rewrite of every consumer that's reaching
2661    /// for the emptiness semantic.
2662    #[must_use]
2663    pub const fn is_empty(&self) -> bool {
2664        self.timeout().is_none()
2665            && self.retries().is_none()
2666            && self.circuit_breaker().is_none()
2667            && self.mtls_required().is_none()
2668            && self.rate_limit().is_none()
2669    }
2670
2671    /// Substrate-canonical cross-axis coherence predicate on the
2672    /// `:politicas` slot: does the `:circuit-breaker :window` rolling
2673    /// failure-observation interval span at least one full
2674    /// `:timeout`-bounded call?
2675    ///
2676    /// The first *cross-axis* invariant on the `:politicas` surface —
2677    /// every prior gate ([`AplicacaoSpec::validate_politicas`]'s four
2678    /// zero-floor + canonical-form + cap brackets) validates one axis
2679    /// in isolation, so a `MeshPolicy` whose axes are each individually
2680    /// well-formed could still name a structurally inert pair. The
2681    /// pair `{ timeout: 30s, circuit_breaker: { window: 10s, .. } }`
2682    /// passes every per-axis bracket (30s ≤ [`POLICY_TIMEOUT_MAX`],
2683    /// 10s ≤ [`POLICY_BREAKER_WINDOW_MAX`], both integer-millisecond,
2684    /// both above the zero floor) and is nonetheless a breaker that
2685    /// cannot trip on the failure mode it exists to catch: a call
2686    /// dispatched at t=0 is declared failed at t=30s, by which point
2687    /// the 10s window open at dispatch has rolled twice over, so no
2688    /// window can ever hold even one timeout-derived failure however
2689    /// high the call volume. Envoy's `outlier_detection.interval`
2690    /// carries the identical relation against the per-route request
2691    /// timeout; Hystrix ships the canonical ratio in its defaults
2692    /// (10s `metrics.rollingStats.timeInMilliseconds` against a 1s
2693    /// `execution.isolation.thread.timeoutInMilliseconds`).
2694    ///
2695    /// Vacuously `true` when either axis is absent — a `:politicas`
2696    /// that names only one of the pair declares no relation for the
2697    /// substrate to hold it to (`:timeout` alone is a per-call deadline
2698    /// with no breaker; `:circuit-breaker` alone is a breaker whose
2699    /// failures arrive from the transport's own error signal rather
2700    /// than from a substrate-imposed deadline, so no dispatch-to-report
2701    /// lag is knowable at author time). This is the same
2702    /// "unset means the cluster default applies, not zero" partition
2703    /// [`MeshPolicy::is_empty`] and every per-axis accessor's `None`
2704    /// arm already carry.
2705    ///
2706    /// Lifted as a typed predicate on the substrate primitive rather
2707    /// than open-coded at the validate gate so every downstream
2708    /// consumer of the pair reaches the invariant through one dispatch:
2709    /// the [`AplicacaoSpec::validate_politicas`] gate below, the future
2710    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2711    /// (MESH-COMPOSITION §III.2 #3) that must emit
2712    /// `outlier_detection.interval` and the per-route `timeout` as one
2713    /// coherent Envoy block, the future M4
2714    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
2715    /// webhook, and the future per-`:contratos`-edge `:politicas`
2716    /// override that same roadmap acknowledges — which resolves an
2717    /// *effective* pair per edge (edge-level `:timeout` against the
2718    /// Aplicacao-level `:window`, or vice versa) and so must re-check
2719    /// the relation on a pair neither axis's declaration site can see
2720    /// whole. Naming the invariant once means that resolver folds this
2721    /// predicate over its resolved pair instead of re-deriving the
2722    /// comparison, exactly as the sibling cross-slot
2723    /// [`PlacementStrategy::is_shard_keyed`] predicate names the
2724    /// `:placement`/`:shard-key` relation for its own consumers.
2725    #[must_use]
2726    pub const fn breaker_window_observes_timeout(&self) -> bool {
2727        match (self.timeout(), self.circuit_breaker()) {
2728            (Some(timeout), Some(cb)) => cb.window().as_nanos() >= timeout.as_nanos(),
2729            _ => true,
2730        }
2731    }
2732
2733    /// Substrate-canonical cross-axis coherence predicate on the
2734    /// `:politicas` slot: can the token-bucket rate declared by
2735    /// `:rate-limit` dispatch enough calls inside `:circuit-breaker
2736    /// :window` to reach `:max-failures`?
2737    ///
2738    /// The second cross-axis invariant on the `:politicas` surface —
2739    /// sibling to [`MeshPolicy::breaker_window_observes_timeout`] on
2740    /// the `(:timeout, :circuit-breaker :window)` pair, extended onto
2741    /// the `(:rate-limit, :circuit-breaker)` pair. Each axis in the
2742    /// pair is validated in isolation by the per-axis brackets in
2743    /// [`AplicacaoSpec::validate_politicas`] (rate zero-floor + cap,
2744    /// max-failures zero-floor + cap, both windows zero-floor +
2745    /// integer-millisecond + cap, rate-limit window canonical-form),
2746    /// so a `MeshPolicy` whose axes are each individually well-formed
2747    /// can still name a structurally inert pair. The pair
2748    /// `{ rate-limit: "1/h", circuit-breaker: (:max-failures 5 :window
2749    /// "10s") }` passes every per-axis bracket and is nonetheless a
2750    /// breaker that cannot trip on the failure mode it exists to
2751    /// catch: the token bucket admits `rate × (cb.window / rl.window)`
2752    /// = `1 × (10s / 3600s)` ≈ 0 calls per rolling breaker window, so
2753    /// no window can accumulate five failures however catastrophically
2754    /// the upstream is failing. Envoy's
2755    /// `outlier_detection.consecutive_5xx` paired against
2756    /// `local_rate_limit.token_bucket.max_tokens` /
2757    /// `fill_interval` carries the identical relation; every
2758    /// production playbook that pairs the two axes (Envoy, Istio, AWS
2759    /// App Mesh, Kong) recommends sizing the rate at or above the
2760    /// breaker's minimum-request-volume threshold for exactly this
2761    /// reason.
2762    ///
2763    /// The typed test is the integer inequality
2764    /// `rate × cb.window.as_nanos() >= max_failures × rl.window.as_nanos()`
2765    /// (rearranged from `rate × cb.window / rl.window >= max_failures`
2766    /// so no floating-point division mediates the comparison and so
2767    /// the sub-second `rl.window` arms — `"n/s"` = 1s — are treated
2768    /// exactly). Both multiplicands are `saturating_mul`'d into
2769    /// [`u128`] so a struct-literal `MeshPolicy` whose per-axis fields
2770    /// have not yet passed [`AplicacaoSpec::validate_politicas`]
2771    /// (e.g. `rate: u32::MAX, cb_window: Duration::MAX`) does not
2772    /// panic the predicate; a saturated pair collapses to the
2773    /// "vacuously coherent" branch the peer per-axis brackets reject
2774    /// via their own zero-floor / cap arms first.
2775    ///
2776    /// Vacuously `true` when either axis is absent — a `:politicas`
2777    /// that names only one of the pair declares no relation for the
2778    /// substrate to hold it to (`:rate-limit` alone is a per-edge
2779    /// token-bucket declaration with no failure counter to starve;
2780    /// `:circuit-breaker` alone is a rolling-window failure counter
2781    /// whose call rate is unconstrained by the substrate, so no
2782    /// bucket-derived upper bound on calls-per-window is knowable at
2783    /// author time). Same "unset means the cluster default applies,
2784    /// not zero" partition [`MeshPolicy::is_empty`] and the sibling
2785    /// [`MeshPolicy::breaker_window_observes_timeout`] predicate
2786    /// carry.
2787    ///
2788    /// Lifted as a typed predicate on the substrate primitive rather
2789    /// than open-coded at the validate gate so every downstream
2790    /// consumer of the pair reaches the invariant through one
2791    /// dispatch: the [`AplicacaoSpec::validate_politicas`] gate
2792    /// below, the future `CiliumClusterwideEnvoyConfig`
2793    /// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) that
2794    /// must emit `local_rate_limit.token_bucket.{max_tokens,
2795    /// fill_interval}` alongside `outlier_detection.consecutive_5xx`
2796    /// / `outlier_detection.interval` as one coherent Envoy block,
2797    /// the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
2798    /// materializer's admission webhook, and the future
2799    /// per-`:contratos`-edge `:politicas` override the same roadmap
2800    /// acknowledges — which resolves an *effective* pair per edge
2801    /// (edge-level `:rate-limit` against the Aplicacao-level
2802    /// `:circuit-breaker`, or vice versa) and so must re-check the
2803    /// relation on a pair neither axis's declaration site can see
2804    /// whole. Naming the invariant once means that resolver folds
2805    /// this predicate over its resolved pair instead of re-deriving
2806    /// the comparison, exactly as the sibling cross-axis
2807    /// [`MeshPolicy::breaker_window_observes_timeout`] predicate
2808    /// names the `(:timeout, :window)` relation for its own consumers.
2809    #[must_use]
2810    pub const fn breaker_can_trip_under_rate_limit(&self) -> bool {
2811        match (self.rate_limit(), self.circuit_breaker()) {
2812            (Some(rl), Some(cb)) => {
2813                let calls_per_cb_window =
2814                    (rl.rate() as u128).saturating_mul(cb.window().as_nanos());
2815                let trip_threshold_per_cb_window =
2816                    (cb.max_failures() as u128).saturating_mul(rl.window().as_nanos());
2817                calls_per_cb_window >= trip_threshold_per_cb_window
2818            }
2819            _ => true,
2820        }
2821    }
2822
2823    /// Substrate-canonical cross-axis coherence predicate on the
2824    /// `:politicas` slot: can one client's declared `:retries` all
2825    /// complete before `:circuit-breaker :max-failures` trips the
2826    /// breaker mid-retry?
2827    ///
2828    /// The third cross-axis invariant on the `:politicas` surface —
2829    /// sibling to [`MeshPolicy::breaker_window_observes_timeout`] on
2830    /// the `(:timeout, :circuit-breaker :window)` pair and
2831    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] on the
2832    /// `(:rate-limit, :circuit-breaker)` pair, extended onto the
2833    /// `(:retries, :circuit-breaker :max-failures)` pair. Each axis in
2834    /// the pair is validated in isolation by the per-axis brackets in
2835    /// [`AplicacaoSpec::validate_politicas`] (retries zero-floor + cap,
2836    /// max-failures zero-floor + cap), so a `MeshPolicy` whose axes
2837    /// are each individually well-formed can still name a
2838    /// structurally-inert retry policy. The pair
2839    /// `{ :retries 3, :circuit-breaker (:max-failures 3 :window "1s") }`
2840    /// passes every per-axis bracket and is nonetheless a retry
2841    /// policy the substrate cannot honor: one client's initial attempt
2842    /// plus three retries is four attempts, but the breaker trips on
2843    /// the third failure — the fourth attempt (the last declared
2844    /// retry) is blocked by the open breaker, so the substrate
2845    /// declared four attempts and structurally allows three.
2846    ///
2847    /// The typed test is the integer inequality
2848    /// `cb.max_failures() > retries` — the retries count is the
2849    /// *number of retry attempts beyond the initial* (Envoy's
2850    /// `retry_policy.num_retries` semantics), so a client makes at
2851    /// most `retries + 1` attempts per client call, each of which may
2852    /// fail. For the breaker to *admit* the retry policy through
2853    /// completion, its trip threshold must not be reached by one
2854    /// client's failures alone: `retries + 1 <= max_failures`,
2855    /// equivalently `retries < max_failures`, equivalently
2856    /// `max_failures > retries`. The boundary case
2857    /// `max_failures == retries + 1` accepts (the R+1th failure — the
2858    /// last retry — trips the breaker exactly as it completes; retries
2859    /// are fully executed). The strict-below case
2860    /// `max_failures <= retries` rejects (the breaker trips before
2861    /// retries exhaust, silently truncating the declared retry policy
2862    /// mid-run — the same declared-but-structurally-inert footgun the
2863    /// sibling per-axis cap arms close on the single-axis surfaces).
2864    ///
2865    /// Vacuously `true` when either axis is absent — a `:politicas`
2866    /// that names only one of the pair declares no relation for the
2867    /// substrate to hold it to (`:retries` alone is a client-retry
2868    /// policy with no failure counter to trip; `:circuit-breaker`
2869    /// alone is a failure counter whose per-client attempt count is
2870    /// unconstrained by the substrate, so no per-client saturation
2871    /// bound on failures-per-client-call is knowable at author time).
2872    /// Same "unset means the cluster default applies, not zero"
2873    /// partition [`MeshPolicy::is_empty`] and the sibling
2874    /// [`MeshPolicy::breaker_window_observes_timeout`] /
2875    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
2876    /// carry.
2877    ///
2878    /// Lifted as a typed predicate on the substrate primitive rather
2879    /// than open-coded at the validate gate so every downstream
2880    /// consumer of the pair reaches the invariant through one
2881    /// dispatch: the [`AplicacaoSpec::validate_politicas`] gate
2882    /// below, the future `CiliumClusterwideEnvoyConfig`
2883    /// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) that
2884    /// must emit `retry_policy.num_retries` alongside
2885    /// `outlier_detection.consecutive_5xx` as one coherent Envoy
2886    /// block, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
2887    /// materializer's admission webhook, and the future
2888    /// per-`:contratos`-edge `:politicas` override the same roadmap
2889    /// acknowledges — which resolves an *effective* pair per edge
2890    /// (edge-level `:retries` against the Aplicacao-level
2891    /// `:circuit-breaker`, or vice versa) and so must re-check the
2892    /// relation on a pair neither axis's declaration site can see
2893    /// whole. Naming the invariant once means that resolver folds
2894    /// this predicate over its resolved pair instead of re-deriving
2895    /// the comparison, exactly as the sibling cross-axis
2896    /// [`MeshPolicy::breaker_window_observes_timeout`] and
2897    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
2898    /// name the `(:timeout, :window)` and `(:rate-limit,
2899    /// :circuit-breaker)` relations for their own consumers.
2900    #[must_use]
2901    pub const fn retries_fit_under_breaker_trip_threshold(&self) -> bool {
2902        match (self.retries(), self.circuit_breaker()) {
2903            (Some(retries), Some(cb)) => cb.max_failures() > retries,
2904            _ => true,
2905        }
2906    }
2907
2908    /// Substrate-canonical cross-axis coherence predicate on the
2909    /// `:politicas` slot: does the `:rate-limit` token-bucket capacity
2910    /// admit one client's full `:retries + 1` attempt burst inside a
2911    /// single refill window?
2912    ///
2913    /// The fourth cross-axis invariant on the `:politicas` surface,
2914    /// completing the triangle of pairs the three sibling gates carve
2915    /// out — sibling to [`MeshPolicy::breaker_window_observes_timeout`]
2916    /// on the `(:timeout, :circuit-breaker :window)` pair,
2917    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] on the
2918    /// `(:rate-limit, :circuit-breaker)` pair, and
2919    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`] on the
2920    /// `(:retries, :circuit-breaker :max-failures)` pair, extended onto
2921    /// the `(:retries, :rate-limit)` pair — the last cross-axis relation
2922    /// among the three scalar `:politicas` axes (`:retries`,
2923    /// `:rate-limit`, `:circuit-breaker`) whose axis-triple defines the
2924    /// coherence surface every production overlay (Envoy, Istio,
2925    /// resilience4j, AWS App Mesh) resolves as one block. Each axis in
2926    /// the pair is validated in isolation by the per-axis brackets in
2927    /// [`AplicacaoSpec::validate_politicas`] (retries zero-floor + cap,
2928    /// rate zero-floor + cap, window canonical-form), so a `MeshPolicy`
2929    /// whose axes are each individually well-formed can still name a
2930    /// structurally-truncated retry policy the rate limiter refuses to
2931    /// admit. The pair `{ :retries 5, :rate-limit "3/s" }` passes every
2932    /// per-axis bracket and is nonetheless a retry policy the substrate
2933    /// cannot honor: one client's initial attempt plus five retries is
2934    /// six attempts, but the token bucket admits at most three tokens
2935    /// per one-second refill window, so the fourth attempt onward is
2936    /// blocked by the rate limiter itself — the substrate declared six
2937    /// attempts and structurally allows three. Envoy's
2938    /// `local_rate_limit.token_bucket.max_tokens` paired against
2939    /// `retry_policy.num_retries` carries the identical relation; every
2940    /// production playbook that pairs the two axes recommends sizing
2941    /// the bucket capacity above any single client's retry budget so
2942    /// the retry policy is not silently truncated by the same rate
2943    /// limiter it feeds through.
2944    ///
2945    /// The typed test is the integer inequality
2946    /// `rl.rate() >= retries + 1` — the retries count is the *number of
2947    /// retry attempts beyond the initial* (Envoy's
2948    /// `retry_policy.num_retries` semantics), so a client makes at most
2949    /// `retries + 1` attempts per client call, each of which consumes
2950    /// one token from the local rate-limit bucket. For the bucket to
2951    /// *admit* the retry burst without dropping tokens, its capacity
2952    /// must not be reached by one client's attempts alone:
2953    /// `retries + 1 <= rate`, equivalently `rate >= retries + 1`. The
2954    /// boundary case `rate == retries + 1` accepts (the bucket admits
2955    /// exactly one client's full retry sequence per refill window —
2956    /// retries fully executed). The strict-below case `rate <= retries`
2957    /// rejects (the bucket exhausts before retries complete, silently
2958    /// truncating the declared retry policy mid-run — the same
2959    /// declared-but-structurally-inert footgun the sibling per-axis cap
2960    /// arms close on the single-axis surfaces). The equivalent
2961    /// coherent-direction form `rl.rate() > retries` sidesteps the
2962    /// `retries + 1` addition entirely (both `rate` and `retries` are
2963    /// `u32`; the `>` comparison is total on the type with no overflow
2964    /// against past-the-guard struct-literal `retries` values a caller
2965    /// might pass before `validate` runs), matching the peer
2966    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`] direct-
2967    /// `>`-comparison discipline on the sibling
2968    /// `(:retries, :max-failures)` pair.
2969    ///
2970    /// Vacuously `true` when either axis is absent — a `:politicas`
2971    /// that names only one of the pair declares no relation for the
2972    /// substrate to hold it to (`:retries` alone is a client-retry
2973    /// policy with no rate limiter to saturate; `:rate-limit` alone is
2974    /// a token-bucket declaration whose per-client attempt count is
2975    /// unconstrained by the substrate, so no per-client saturation
2976    /// bound on tokens-per-client-call is knowable at author time).
2977    /// Same "unset means the cluster default applies, not zero"
2978    /// partition [`MeshPolicy::is_empty`] and the three sibling
2979    /// cross-axis predicates
2980    /// ([`MeshPolicy::breaker_window_observes_timeout`],
2981    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`],
2982    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]) carry.
2983    ///
2984    /// Lifted as a typed predicate on the substrate primitive rather
2985    /// than open-coded at the validate gate so every downstream
2986    /// consumer of the pair reaches the invariant through one dispatch:
2987    /// the [`AplicacaoSpec::validate_politicas`] gate below, the future
2988    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2989    /// (MESH-COMPOSITION §III.2 #3) that must emit
2990    /// `local_rate_limit.token_bucket.max_tokens` alongside
2991    /// `retry_policy.num_retries` as one coherent Envoy block, the
2992    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
2993    /// admission webhook, and the future per-`:contratos`-edge
2994    /// `:politicas` override the same roadmap acknowledges — which
2995    /// resolves an *effective* pair per edge (edge-level `:retries`
2996    /// against the Aplicacao-level `:rate-limit`, or vice versa) and
2997    /// so must re-check the relation on a pair neither axis's
2998    /// declaration site can see whole. Naming the invariant once means
2999    /// that resolver folds this predicate over its resolved pair
3000    /// instead of re-deriving the comparison, exactly as the three
3001    /// sibling cross-axis predicates name the
3002    /// `(:timeout, :window)` / `(:rate-limit, :circuit-breaker)` /
3003    /// `(:retries, :max-failures)` relations for their own consumers,
3004    /// closing the fourth and last cross-axis relation on the scalar
3005    /// `:politicas` axis-triple.
3006    #[must_use]
3007    pub const fn rate_limit_admits_retry_burst(&self) -> bool {
3008        match (self.retries(), self.rate_limit()) {
3009            (Some(retries), Some(rl)) => rl.rate() > retries,
3010            _ => true,
3011        }
3012    }
3013
3014    /// Substrate-canonical fold over the four cross-axis coherence
3015    /// predicates on the `:politicas` slot — returns the *first*
3016    /// cross-axis violation (as its [`AplicacaoError`] variant) in the
3017    /// canonical "more-foundational-cross-axis first" ordering
3018    /// [`MeshPolicy::breaker_window_observes_timeout`] on
3019    /// `(:timeout, :circuit-breaker :window)` →
3020    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] on
3021    /// `(:rate-limit, :circuit-breaker)` →
3022    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`] on
3023    /// `(:retries, :circuit-breaker :max-failures)` →
3024    /// [`MeshPolicy::rate_limit_admits_retry_burst`] on `(:retries,
3025    /// :rate-limit)`. Returns `None` when every cross-axis relation
3026    /// holds (the vacuous shape [`MeshPolicy::is_empty`] and the fully-
3027    /// coherent shape both land here).
3028    ///
3029    /// The ordering discipline this method encodes was open-coded four
3030    /// times at [`AplicacaoSpec::validate_politicas`] — each cross-axis
3031    /// gate was an `if !<predicate>() { let <a> = self.<axis>().expect(
3032    /// "cross-axis gate fires only when :<axis> is present"); let <b>
3033    /// = self.<axis>().expect(…); return Err(<variant>) }` block whose
3034    /// axis-fetch step depended on the predicate having just returned
3035    /// `false` (structurally guaranteed both paired axes are `Some`,
3036    /// but the compiler cannot see through the predicate body, so
3037    /// every arm re-called the accessor with `.expect(…)` to reach
3038    /// the axis it just tested). Two unsound consequences: (1) the
3039    /// validate gate carried eight `.expect(…)` panic call sites the
3040    /// predicate contract already forbids on every well-typed input
3041    /// but the type system does not enforce; (2) the
3042    /// "which-cross-axis-fires-first-when-two-apply" contract lived
3043    /// twice — once in each predicate's own doc comments and once at
3044    /// the validate call site's four-arm cascade. Lifting the four-arm
3045    /// cascade onto this substrate primitive collapses both
3046    /// duplications: the predicate contract and the axis-fetch step
3047    /// live in the same body (no `.expect(…)` — the pattern match at
3048    /// each arm rebinds the paired axes so their `Some` presence is a
3049    /// compile-time property of the local scope), and the ordering
3050    /// discipline lives once at the top of the primitive rather than
3051    /// scattered across four sibling doc-comment blocks that must
3052    /// stay in lockstep.
3053    ///
3054    /// Every downstream cross-axis consumer (the [`AplicacaoSpec::
3055    /// validate_politicas`] gate below, the future M4 `mesh.pleme.io/
3056    /// v1alpha1/Aplicacao` CR materializer's admission webhook, the
3057    /// per-`:contratos`-edge `:politicas` override MESH-COMPOSITION
3058    /// §III.2 #3 acknowledges — the last of which resolves an
3059    /// *effective* per-edge pair and must emit *the same* diagnostic
3060    /// on the same paired-axis input as `feira build`) reaches through
3061    /// one call rather than re-inlining the four pattern-matches +
3062    /// accessor-fetches + variant-constructions + ordering-cascade.
3063    ///
3064    /// Returns owned copies of every axis carried into the diagnostic:
3065    /// [`Duration`] and [`u32`] are `Copy`, so no `String` allocation
3066    /// occurs on the happy path when no violation fires.
3067    #[must_use]
3068    pub fn first_cross_axis_violation(&self) -> Option<AplicacaoError> {
3069        // Ordering discipline this fold encodes matches the four
3070        // per-arm predicate doc comments' pairwise-ordering contract:
3071        // window-below-timeout wins over every arm that names `:rate-
3072        // limit` or `:retries` (its diagnostic is more self-locating —
3073        // the pair is a per-call-deadline invariant every synchronous
3074        // edge carries whether or not `:rate-limit`/`:retries` is
3075        // declared); the starve arm wins over the two retry arms (its
3076        // diagnostic reasons across the token-bucket-vs-breaker
3077        // relation, an axis the retry arms do not touch); the
3078        // retries-saturate arm wins over the retries-burst arm (its
3079        // diagnostic reasons across the per-client-vs-breaker
3080        // relation, which carries whether or not `:rate-limit` is
3081        // declared). Each arm rebinds the paired axes through the
3082        // pattern match, so the `.expect(…)` panics the four-block
3083        // cascade at `validate_politicas` carried collapse to no-op
3084        // pattern rebindings the compiler statically proves exhaust.
3085        if let (Some(t), Some(cb)) = (self.timeout(), self.circuit_breaker())
3086            && !self.breaker_window_observes_timeout()
3087        {
3088            return Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
3089                window: cb.window(),
3090                timeout: t,
3091            });
3092        }
3093        if let (Some(rl), Some(cb)) = (self.rate_limit(), self.circuit_breaker())
3094            && !self.breaker_can_trip_under_rate_limit()
3095        {
3096            return Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
3097                rate: rl.rate(),
3098                rl_window: rl.window(),
3099                max_failures: cb.max_failures(),
3100                cb_window: cb.window(),
3101            });
3102        }
3103        if let (Some(retries), Some(cb)) = (self.retries(), self.circuit_breaker())
3104            && !self.retries_fit_under_breaker_trip_threshold()
3105        {
3106            return Some(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
3107                retries,
3108                max_failures: cb.max_failures(),
3109            });
3110        }
3111        if let (Some(retries), Some(rl)) = (self.retries(), self.rate_limit())
3112            && !self.rate_limit_admits_retry_burst()
3113        {
3114            return Some(AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
3115                retries,
3116                rate: rl.rate(),
3117            });
3118        }
3119        None
3120    }
3121
3122    /// Substrate-canonical compound entry gate over the whole
3123    /// `:politicas` typed slot — folds every per-axis bracket
3124    /// (`:timeout` / `:retries` / `:circuit-breaker :max-failures` /
3125    /// `:circuit-breaker :window` / `:rate-limit` rate / `:rate-limit`
3126    /// window-canonical-form) *and* the compound cross-axis fold
3127    /// [`MeshPolicy::first_cross_axis_violation`] into one call every
3128    /// consumer of a validated [`MeshPolicy`] reaches through.
3129    ///
3130    /// Returns the first violation as its [`AplicacaoError`] variant,
3131    /// or `Ok(())` when every per-axis value lies in its accept-set and
3132    /// every cross-axis relation holds. Per-axis brackets run strictly
3133    /// before the cross-axis fold — the sibling
3134    /// [`AplicacaoSpec::validate_politicas`] gate carried the same
3135    /// ordering discipline for the same reason: a per-axis
3136    /// structurally-invalid value (a `Duration::ZERO` `:window`, an
3137    /// above-cap `:rate-limit` rate) surfaces its own self-locating
3138    /// diagnostic first, ahead of any cross-axis arm that would send
3139    /// the author to reconcile two values one of which is not a
3140    /// meaningful window at all. Within the per-axis phase, arms fire
3141    /// in the same slot-order the peer per-axis brackets carry
3142    /// (`:timeout` → `:retries` → `:circuit-breaker` → `:rate-limit`,
3143    /// each internally ordered zero-floor before canonical-form before
3144    /// cap by [`crate::render::require_positive_bounded_u32`] /
3145    /// [`crate::render::require_positive_canonical_bounded_duration`]);
3146    /// within the cross-axis phase, arms fire in the canonical
3147    /// more-foundational-cross-axis-first ordering
3148    /// [`MeshPolicy::first_cross_axis_violation`] encodes.
3149    ///
3150    /// Lifted as a typed method on the substrate primitive so every
3151    /// downstream consumer of a validated [`MeshPolicy`] reaches the
3152    /// invariant through one dispatch: the
3153    /// [`AplicacaoSpec::validate_politicas`] gate below (whose whole
3154    /// body collapses to `self.politicas().validate()`), the future
3155    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
3156    /// admission webhook, the future per-`:contratos`-edge `:politicas`
3157    /// override MESH-COMPOSITION §III.2 #3 acknowledges — the last of
3158    /// which resolves an *effective* per-edge [`MeshPolicy`] and must
3159    /// emit *the same* diagnostic on the same input as `feira build`.
3160    /// Naming the compound gate once on the substrate primitive means
3161    /// every downstream consumer inherits both the per-axis brackets
3162    /// *and* the cross-axis fold through one call, rather than
3163    /// re-inlining the four-per-axis + one-cross-axis cascade in
3164    /// lockstep with `validate_politicas`.
3165    ///
3166    /// Peer of the per-kind compound entry gates lifted at
3167    /// [`crate::render::require_aplicacao_view`] (7242d45 / 3aefefb),
3168    /// [`crate::render::require_supervisor_view`] (8d8a5c3), and
3169    /// [`crate::render::require_v0_servico_shape`] on the per-Caixa
3170    /// layout axis, and the sibling compound cross-axis fold
3171    /// [`MeshPolicy::first_cross_axis_violation`] on the same
3172    /// `:politicas` axis — extended here onto the per-slot per-axis +
3173    /// cross-axis compound entry gate that folds both surfaces.
3174    pub fn validate(&self) -> Result<(), AplicacaoError> {
3175        if let Some(t) = self.timeout() {
3176            crate::render::require_positive_canonical_bounded_duration(
3177                t,
3178                POLICY_TIMEOUT_MAX,
3179                || AplicacaoError::PolicyTimeoutZero,
3180                |timeout| AplicacaoError::PolicyTimeoutNotCanonical { timeout },
3181                |timeout| AplicacaoError::PolicyTimeoutExceedsCap { timeout },
3182            )?;
3183        }
3184        if let Some(r) = self.retries() {
3185            crate::render::require_positive_bounded_u32(
3186                r,
3187                POLICY_RETRIES_MAX,
3188                || AplicacaoError::PolicyRetriesZero,
3189                |retries| AplicacaoError::PolicyRetriesExceedsCap { retries },
3190            )?;
3191        }
3192        if let Some(cb) = self.circuit_breaker() {
3193            crate::render::require_positive_bounded_u32(
3194                cb.max_failures(),
3195                POLICY_BREAKER_MAX_FAILURES_MAX,
3196                || AplicacaoError::PolicyBreakerZeroFailures,
3197                |max_failures| AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
3198            )?;
3199            crate::render::require_positive_canonical_bounded_duration(
3200                cb.window(),
3201                POLICY_BREAKER_WINDOW_MAX,
3202                || AplicacaoError::PolicyBreakerZeroWindow,
3203                |window| AplicacaoError::PolicyBreakerWindowNotCanonical { window },
3204                |window| AplicacaoError::PolicyBreakerWindowExceedsCap { window },
3205            )?;
3206        }
3207        if let Some(rl) = self.rate_limit() {
3208            crate::render::require_positive_bounded_u32(
3209                rl.rate(),
3210                POLICY_RATE_LIMIT_MAX,
3211                || AplicacaoError::PolicyRateLimitZero,
3212                |rate| AplicacaoError::PolicyRateLimitExceedsCap { rate },
3213            )?;
3214            if rl.canonical_unit().is_none() {
3215                return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical {
3216                    window: rl.window(),
3217                });
3218            }
3219        }
3220        if let Some(err) = self.first_cross_axis_violation() {
3221            return Err(err);
3222        }
3223        Ok(())
3224    }
3225
3226    /// Substrate-canonical per-`:politicas` `:timeout` Gateway-API-mesh
3227    /// per-call-deadline scalar accessor every consumer of the
3228    /// Aplicacao's Gateway API v1.x per-rule request-timeout keys off —
3229    /// returns the author-declared `:politicas :timeout` typed
3230    /// [`Duration`] verbatim as an `Option<Duration>`, copied out of the
3231    /// typed slot's own `Option<Duration>` storage (`Option<Duration>`
3232    /// is `Copy`, so the accessor returns by value; no borrow of
3233    /// `&self` past the call). `None` when the slot is absent (the
3234    /// "cluster default applies — typically the gateway class's
3235    /// implementation-side per-request wall-clock cap" arm caixa-mesh's
3236    /// `timeout_overlay` builder documents at caixa-mesh/src/lib.rs:2911
3237    /// — [`MeshPolicy::is_empty`]'s `timeout.is_none()` arm reads this
3238    /// predicate too, so an authored-but-unset `:politicas (:timeout ())`
3239    /// round-trips to a rendered `HTTPRoute` structurally identical to
3240    /// one that omits the slot).
3241    ///
3242    /// The `:politicas :timeout` slot carries the "no infinite blocking"
3243    /// per-call deadline contract (MESH-COMPOSITION §V CSE invariant) —
3244    /// the typed slot's `Option<Duration>` accept-set (zero-floor
3245    /// rejected through [`AplicacaoError::PolicyTimeoutZero`], canonical-
3246    /// form rejected through [`AplicacaoError::PolicyTimeoutNotCanonical`],
3247    /// upper-bounded by [`POLICY_TIMEOUT_MAX`]) maps onto the Gateway API
3248    /// v1.x `HTTPRoute.spec.rules[].timeouts.request` per-rule request-
3249    /// deadline scalar the caixa-mesh `timeout_overlay` builder writes.
3250    /// Every downstream consumer that reads the per-call cap keys off
3251    /// this scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
3252    /// renderers key off to decide "emit :politicas overlay" vs "skip
3253    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
3254    /// `timeouts.request` builder at caixa-mesh/src/lib.rs:2979 that
3255    /// fans the deadline into every rule via
3256    /// [`crate::render::single_field_overlay`], the future M4 per-
3257    /// Aplicacao Gateway API reconciler materialization pass, the
3258    /// future per-`:contratos`-edge timeout-override overlay the
3259    /// MESH-COMPOSITION §III.2 roadmap acknowledges).
3260    ///
3261    /// Prior to this lift the `.timeout` field was accessed inline at
3262    /// two sites — [`MeshPolicy::is_empty`]'s `self.timeout.is_none()`
3263    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.timeout,
3264    /// …)` call — two open-coded field-accesses that expressed no
3265    /// compile-time link back to the typed slot. A future extension of
3266    /// the `:politicas :timeout` axis to a richer author surface — a
3267    /// per-`:contratos`-edge timeout override the operator pins through
3268    /// a future `:contratos :timeout` slot the MESH-COMPOSITION §III.2
3269    /// roadmap acknowledges, a per-cluster timeout-default overlay the
3270    /// M4 CR materializer resolves per-CR, a split of the single
3271    /// per-call `Duration` into a richer `{request, backendRequest}`
3272    /// pair once the Gateway API's per-rule `timeouts` block grows the
3273    /// upstream-facing backendRequest arm alongside the client-facing
3274    /// request arm — would have had to be threaded through both open-
3275    /// coded copies in lockstep or the emptiness predicate and the
3276    /// caixa-mesh emit path would silently disagree on which per-call
3277    /// deadline a given [`MeshPolicy`] resolves to (a `:politicas` block
3278    /// whose only axis is a `Some :timeout` would satisfy `is_empty()
3279    /// == false` while the renderer's overlay-emit path silently read
3280    /// a drifted other value, or vice versa: an author's `:timeout
3281    /// "30s"` would omit the `HTTPRoute` `timeouts.request` block while
3282    /// the emptiness predicate still classified the policy as non-
3283    /// empty, and every `kubectl -n tatara-system get httproute -o yaml
3284    /// | grep -A2 timeouts` audit would land on a route whose author's
3285    /// typed slot value silently vanished at the renderer layer).
3286    /// Lifting the resolution to a typed method on the substrate
3287    /// primitive means every downstream consumer of the Aplicacao's
3288    /// per-`:politicas` deadline surface reaches for exactly one typed
3289    /// dispatch — the resolver's accept-set migrates as a unit on any
3290    /// future axis addition.
3291    ///
3292    /// Third `Option<Copy-T>`-return accessor on the M3 mesh-slot
3293    /// family (sibling of the peer per-`:politicas`
3294    /// [`MeshPolicy::retries`] bdfb399 `Option<u32>` accessor and the
3295    /// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1
3296    /// `Option<bool>` accessor — same "one typed dispatch on the
3297    /// substrate primitive, thin projections at each consumer"
3298    /// discipline extended onto the peer per-`:politicas` typed-
3299    /// [`Duration`] optional-scalar axis; closes the "optional per-slot
3300    /// numeric-Copy-T scalar" projection pattern the sibling
3301    /// `Option<u32>` / `Option<bool>` lifts opened, since every
3302    /// remaining `MeshPolicy` axis (`circuit_breaker: Option<CircuitBreaker>`,
3303    /// `rate_limit: Option<RateLimit>`) carries a struct payload rather
3304    /// than a scalar). Named `timeout()` to match the storage field's
3305    /// name; the accessor's identity maps onto the canonical MESH-
3306    /// COMPOSITION §III.2 vocabulary the slot's docstring already carries.
3307    #[must_use]
3308    pub const fn timeout(&self) -> Option<Duration> {
3309        self.timeout
3310    }
3311
3312    /// Substrate-canonical per-`:politicas` `:retries` transient-failure-
3313    /// retry-budget scalar accessor every consumer of the Aplicacao's
3314    /// Gateway API v1.x per-rule retry-cap keys off — returns the
3315    /// author-declared `:politicas :retries` typed `u32` verbatim as an
3316    /// `Option<u32>`, copied out of the typed slot's own `Option<u32>`
3317    /// storage (`Option<u32>` is `Copy`, so the accessor returns by
3318    /// value; no borrow of `&self` past the call). `None` when the slot
3319    /// is absent (the "cluster default applies — typically 'no retries
3320    /// beyond a single dispatch attempt'" arm the caixa-mesh
3321    /// `retry_overlay` builder documents at caixa-mesh/src/lib.rs:2985
3322    /// — [`MeshPolicy::is_empty`]'s `retries.is_none()` arm reads
3323    /// this predicate too, so an authored-but-unset `:politicas
3324    /// (:retries ())` round-trips to a rendered `HTTPRoute` structurally
3325    /// identical to one that omits the slot).
3326    ///
3327    /// The `:politicas :retries` slot carries the "transient failure
3328    /// retry cap" contract (MESH-COMPOSITION §III.2 #2) — the typed
3329    /// slot's `Option<u32>` accept-set (lower-bounded by 1 through
3330    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
3331    /// [`POLICY_RETRIES_MAX`]) maps onto the Gateway API v1.x
3332    /// `HTTPRoute.spec.rules[].retry.attempts` per-rule retry-attempt-
3333    /// count scalar the caixa-mesh `retry_overlay` builder writes.
3334    /// Every downstream consumer that reads the retry cap keys off this
3335    /// scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
3336    /// renderers key off to decide "emit :politicas overlay" vs "skip
3337    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
3338    /// `retry.attempts` builder at caixa-mesh/src/lib.rs:3007 that fans
3339    /// the value into every rule via [`crate::render::single_field_overlay`],
3340    /// the future M4 per-Aplicacao Gateway API reconciler
3341    /// materialization pass, the future per-`:contratos`-edge retry-
3342    /// override overlay the MESH-COMPOSITION §III.2 #2 roadmap
3343    /// acknowledges).
3344    ///
3345    /// Prior to this lift the `.retries` field was accessed inline at
3346    /// two sites — [`MeshPolicy::is_empty`]'s `self.retries.is_none()`
3347    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.retries,
3348    /// …)` call — two open-coded field-accesses that expressed no
3349    /// compile-time link back to the typed slot. A future extension of
3350    /// the `:politicas :retries` axis to a richer author surface — a
3351    /// per-`:contratos`-edge retry override the operator pins through a
3352    /// future `:contratos :retries` slot, a per-cluster retry-default
3353    /// overlay the M4 CR materializer resolves per-CR, a promotion of
3354    /// the plain `u32` attempt-count to a richer `{attempts, codes,
3355    /// backoff}` sub-block once the Gateway API grows the peer
3356    /// `retry.codes` / `retry.backoff` axes — would have had to be
3357    /// threaded through both open-coded copies in lockstep or the
3358    /// emptiness predicate and the caixa-mesh emit path would silently
3359    /// disagree on which retry budget a given [`MeshPolicy`] resolves to
3360    /// (a `:politicas` block whose only axis is a `Some :retries` would
3361    /// satisfy `is_empty() == false` while the renderer's overlay-emit
3362    /// path silently read a drifted other value, or vice versa: an
3363    /// author's `:retries 3` would omit the `HTTPRoute` `retry.attempts`
3364    /// block while the emptiness predicate still classified the policy
3365    /// as non-empty). Lifting the resolution to a typed method on the
3366    /// substrate primitive means every downstream consumer of the
3367    /// Aplicacao's per-`:politicas` retry surface reaches for exactly
3368    /// one typed dispatch — the resolver's accept-set migrates as a
3369    /// unit on any future axis addition.
3370    ///
3371    /// Second `Option<Copy-T>`-return accessor on the M3 mesh-slot
3372    /// family (sibling of the peer per-`:politicas`
3373    /// [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` accessor —
3374    /// same "one typed dispatch on the substrate primitive, thin
3375    /// projections at each consumer" discipline extended onto the
3376    /// peer per-`:politicas` typed-`u32` optional-scalar axis; opens
3377    /// the "optional per-slot numeric-Copy-T scalar" projection pattern
3378    /// the sibling per-`:politicas` `:timeout` (Option<Duration>) /
3379    /// per-`CircuitBreaker` `:max-failures` / `:window` future lifts
3380    /// fold on). Named `retries()` to match the storage field's name;
3381    /// the accessor's identity maps onto the canonical MESH-COMPOSITION
3382    /// §III.2 vocabulary the slot's docstring already carries.
3383    #[must_use]
3384    pub const fn retries(&self) -> Option<u32> {
3385        self.retries
3386    }
3387
3388    /// Substrate-canonical per-`:politicas` `:mtls-required` mTLS-
3389    /// enforcement-toggle scalar accessor every consumer of the
3390    /// Aplicacao's Cilium-mesh L4 mutual-authentication policy keys off
3391    /// — returns the author-declared `:politicas :mtls-required` typed
3392    /// bool verbatim as an `Option<bool>`, copied out of the typed
3393    /// slot's own `Option<bool>` storage (`Option<bool>` is `Copy`, so
3394    /// the accessor returns by value; no borrow of `&self` past the
3395    /// call). `None` when the slot is absent (the "cluster default
3396    /// applies — typically 'disabled' cluster-wide" arm the caixa-mesh
3397    /// `mtls_overlay` builder documents at caixa-mesh/src/lib.rs:2540
3398    /// — [`MeshPolicy::is_empty`]'s `mtls_required.is_none()` arm reads
3399    /// this predicate too, so an authored-but-unset `:politicas
3400    /// (:mtls-required ())` round-trips to a rendered
3401    /// `CiliumNetworkPolicy` structurally identical to one that omits
3402    /// the slot).
3403    ///
3404    /// The `:politicas :mtls-required` slot carries the "explicit opt-
3405    /// out only, sandboxing-by-default" mTLS-enforcement toggle
3406    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's three-way
3407    /// `{None, Some(true), Some(false)}` accept-set maps onto the
3408    /// Cilium `authentication.mode` bijection through
3409    /// [`crate::cilium_auth_mode`]: `Some(true) → "required"` (mTLS
3410    /// handshake enforced), `Some(false) → "disabled"` (handshake
3411    /// skipped — the debug-edge opt-out), `None` → omit the block
3412    /// (cluster default applies). Every downstream consumer that
3413    /// reads the toggle keys off this scalar (the
3414    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
3415    /// off to decide "emit :politicas overlay" vs "skip entirely", the
3416    /// caixa-mesh per-`(:de, :para)` CNP `mtls_overlay` builder at
3417    /// caixa-mesh/src/lib.rs:2549 that fans the toggle into every
3418    /// ingress rule via [`crate::render::single_field_overlay`], the
3419    /// future M4 per-Aplicacao Cilium `authentication.mode` reconciler
3420    /// materialization pass, the future per-`:contratos`-edge mTLS
3421    /// override MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3422    ///
3423    /// Prior to this lift the `.mtls_required` field was accessed
3424    /// inline at two sites — [`MeshPolicy::is_empty`]'s
3425    /// `self.mtls_required.is_none()` arm and caixa-mesh's
3426    /// `single_field_overlay(spec.politicas.mtls_required, …)` call —
3427    /// two open-coded field-accesses that expressed no compile-time
3428    /// link back to the typed slot. A future extension of the
3429    /// `:politicas :mtls-required` axis to a richer author surface —
3430    /// a per-`:contratos`-edge mTLS override the operator pins through
3431    /// a future `:contratos :mtls` slot the MESH-COMPOSITION §III.2
3432    /// #3 roadmap acknowledges, a per-cluster mTLS-default overlay the
3433    /// M4 CR materializer resolves per-CR, a three-valued
3434    /// `{None, Some(true), Some(false), Some(Optional)}` promotion
3435    /// once Cilium's `authentication.mode` grows an `"optional"` arm —
3436    /// would have had to be threaded through both open-coded copies in
3437    /// lockstep or the emptiness predicate and the caixa-mesh emit
3438    /// path would silently disagree on which toggle a given
3439    /// [`MeshPolicy`] resolves to (a `:politicas` block whose only
3440    /// axis is a `Some`
3441    /// `:mtls-required` would satisfy `is_empty() == false` while the
3442    /// renderer's overlay-emit path silently read a drifted other
3443    /// value, or vice versa). Lifting the resolution to a typed method
3444    /// on the substrate primitive means every downstream consumer of
3445    /// the Aplicacao's per-`:politicas` mTLS-toggle surface reaches
3446    /// for exactly one typed dispatch — the resolver's accept-set
3447    /// migrates as a unit on any future axis addition.
3448    ///
3449    /// First `Option<Copy-T>`-return accessor on the M3 mesh-slot
3450    /// family (peer of the sibling per-`:placement`
3451    /// [`Placement::shard_key`] 7cd2a28 `Option<&str>` accessor —
3452    /// same "one typed dispatch on the substrate primitive, thin
3453    /// projections at each consumer" discipline extended onto the
3454    /// peer per-`:politicas` typed-bool optional-scalar axis; opens
3455    /// the "optional per-slot Copy-T scalar" projection pattern the
3456    /// sibling per-`:politicas` `:retries` (Option<u32>) /
3457    /// `:timeout` (Option<Duration>) future lifts fold on). Named
3458    /// `mtls_required()` to match the storage field's name; the
3459    /// accessor's identity maps onto the canonical MESH-COMPOSITION
3460    /// §III.2 vocabulary the slot's docstring already carries.
3461    #[must_use]
3462    pub const fn mtls_required(&self) -> Option<bool> {
3463        self.mtls_required
3464    }
3465
3466    /// Substrate-canonical per-`:politicas` `:rate-limit` Envoy-
3467    /// `local_rate_limit`-mesh token-bucket-declaration scalar
3468    /// accessor every consumer of the Aplicacao's per-`:politicas`
3469    /// per-`(rate, window)` rate-limit surface keys off — returns the
3470    /// author-declared `:politicas :rate-limit` typed [`RateLimit`]
3471    /// verbatim as an `Option<RateLimit>`, copied out of the typed
3472    /// slot's own `Option<RateLimit>` storage ([`RateLimit`] is
3473    /// `Copy`, so the accessor returns by value; no borrow of `&self`
3474    /// past the call). `None` when the slot is absent (the "cluster
3475    /// default applies — typically 'no per-Aplicacao rate declaration,
3476    /// gateway-class per-listener default applies'" arm the future
3477    /// caixa-mesh `local_rate_limit_overlay` emitter MESH-COMPOSITION
3478    /// §III.2 #3 names — [`MeshPolicy::is_empty`]'s
3479    /// `rate_limit().is_none()` arm reads this predicate too, so an
3480    /// authored-but-unset `:politicas (:rate-limit ())` round-trips
3481    /// to a rendered `CiliumClusterwideEnvoyConfig` structurally
3482    /// identical to one that omits the slot).
3483    ///
3484    /// The `:politicas :rate-limit` slot carries the "per-Aplicacao
3485    /// token-bucket rate declaration" contract (MESH-COMPOSITION
3486    /// §III.2 #3) — the typed slot's `Option<RateLimit>` accept-set
3487    /// (rate lower-bounded by 1 through
3488    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
3489    /// [`POLICY_RATE_LIMIT_MAX`], window canonically bijected to the
3490    /// three-unit `{"s", "m", "h"}` [`rate_limit_codec`] table through
3491    /// [`is_canonical_rate_limit_window`]) maps onto the Envoy
3492    /// `local_rate_limit.token_bucket.{max_tokens, fill_interval}`
3493    /// bijection the future `CiliumClusterwideEnvoyConfig` per-
3494    /// `:politicas` overlay emits. Every downstream consumer that
3495    /// reads the rate declaration keys off this scalar (the
3496    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
3497    /// off to decide "emit :politicas overlay" vs "skip entirely", the
3498    /// [`AplicacaoSpec::validate_politicas`] per-value-shape gate that
3499    /// brackets `rl.rate` against [`POLICY_RATE_LIMIT_MAX`] and pins
3500    /// `rl.window` against [`is_canonical_rate_limit_window`], the
3501    /// future M4 per-Aplicacao Envoy reconciler materialization pass,
3502    /// the future per-`:contratos`-edge rate-limit override the
3503    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3504    ///
3505    /// Prior to this lift the `.rate_limit` field was accessed inline
3506    /// at two sites — [`MeshPolicy::is_empty`]'s
3507    /// `self.rate_limit.is_none()` arm and the `validate_politicas`
3508    /// gate's `if let Some(rl) = &p.rate_limit` bind — two open-coded
3509    /// field-accesses that expressed no compile-time link back to the
3510    /// typed slot. A future extension of the `:politicas :rate-limit`
3511    /// axis to a richer author surface — a per-`:contratos`-edge
3512    /// rate-limit override the operator pins through a future
3513    /// `:contratos :rate-limit` slot the MESH-COMPOSITION §III.2 #3
3514    /// roadmap acknowledges, a per-cluster rate-limit-default overlay
3515    /// the M4 CR materializer resolves per-CR, a promotion of the
3516    /// plain `(rate, window)` scalar pair to a richer
3517    /// `{rate, window, burst, key}` sub-block once Envoy's
3518    /// `local_rate_limit` grows the peer `burst_size` /
3519    /// `descriptor_key` axes — would have had to be threaded through
3520    /// both open-coded copies in lockstep or the emptiness predicate
3521    /// and the validate gate would silently disagree on which rate
3522    /// declaration a given [`MeshPolicy`] resolves to (a `:politicas`
3523    /// block whose only axis is a `Some :rate-limit` would satisfy
3524    /// `is_empty() == false` while the validate path silently read a
3525    /// drifted other value, or vice versa: an author's
3526    /// `:rate-limit "100/s"` would omit the value-shape gate while the
3527    /// emptiness predicate still classified the policy as non-empty).
3528    /// Lifting the resolution to a typed method on the substrate
3529    /// primitive means every downstream consumer of the Aplicacao's
3530    /// per-`:politicas` rate-limit surface reaches for exactly one
3531    /// typed dispatch — the resolver's accept-set migrates as a unit
3532    /// on any future axis addition.
3533    ///
3534    /// First `Option<Copy-composite-T>`-return accessor on the M3
3535    /// mesh-slot family — closes the last un-lifted per-`:politicas`
3536    /// scalar-value axis. Peer of the sibling per-`:politicas`
3537    /// [`MeshPolicy::timeout`] (7073d0f) / [`MeshPolicy::retries`]
3538    /// (bdfb399) / [`MeshPolicy::mtls_required`] (c0110f1)
3539    /// `Option<Copy-T>` accessors on the primitive-Copy axes — same
3540    /// "one typed dispatch on the substrate primitive, thin
3541    /// projections at each consumer" discipline extended onto the
3542    /// peer per-`:politicas` composite-Copy shape (`RateLimit` is
3543    /// `#[derive(Copy)]`; peer of [`CircuitBreaker`] which lives
3544    /// behind [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
3545    /// sub-accessors rather than a top-level accessor because
3546    /// consumers reach for the axes not the aggregate). Named
3547    /// `rate_limit()` to match the storage field's name; the
3548    /// accessor's identity maps onto the canonical MESH-COMPOSITION
3549    /// §III.2 vocabulary the slot's docstring already carries.
3550    #[must_use]
3551    pub const fn rate_limit(&self) -> Option<RateLimit> {
3552        self.rate_limit
3553    }
3554
3555    /// Substrate-canonical per-`:politicas` `:circuit-breaker`
3556    /// Envoy-`outlier_detection`-mesh consecutive-failure-ejection-
3557    /// declaration scalar accessor every consumer of the Aplicacao's
3558    /// per-`:politicas` breaker declaration keys off — returns the
3559    /// author-declared `:politicas :circuit-breaker` typed
3560    /// [`CircuitBreaker`] verbatim as an `Option<CircuitBreaker>`,
3561    /// copied out of the typed slot's own `Option<CircuitBreaker>`
3562    /// storage ([`CircuitBreaker`] is `Copy`, so the accessor returns
3563    /// by value; no borrow of `&self` past the call). `None` when the
3564    /// slot is absent (the "cluster default applies — typically 'no
3565    /// per-Aplicacao breaker declaration, gateway-class per-listener
3566    /// default applies'" arm the future caixa-mesh
3567    /// `outlier_detection_overlay` emitter MESH-COMPOSITION §III.2 #3
3568    /// names — [`MeshPolicy::is_empty`]'s `circuit_breaker().is_none()`
3569    /// arm reads this predicate too, so an authored-but-unset
3570    /// `:politicas (:circuit-breaker ())` round-trips to a rendered
3571    /// `CiliumClusterwideEnvoyConfig` structurally identical to one
3572    /// that omits the slot).
3573    ///
3574    /// The `:politicas :circuit-breaker` slot carries the
3575    /// "per-Aplicacao consecutive-transient-failure trip declaration"
3576    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
3577    /// `Option<CircuitBreaker>` accept-set (per-`:max-failures`
3578    /// zero-floor rejected through
3579    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
3580    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]; per-`:window` zero-floor
3581    /// rejected through [`AplicacaoError::PolicyBreakerZeroWindow`],
3582    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`],
3583    /// canonical-form pinned through
3584    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`]) maps onto
3585    /// the Envoy `outlier_detection.{consecutive_5xx, interval}`
3586    /// bijection the future `CiliumClusterwideEnvoyConfig`
3587    /// per-`:politicas` overlay emits. Every downstream consumer that
3588    /// reads the breaker declaration keys off this scalar (the
3589    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
3590    /// off to decide "emit :politicas overlay" vs "skip entirely", the
3591    /// [`AplicacaoSpec::validate_politicas`] per-sub-struct-axis gate
3592    /// that brackets `cb.max_failures()` against
3593    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`] and `cb.window()` against
3594    /// [`POLICY_BREAKER_WINDOW_MAX`] via
3595    /// [`crate::render::require_positive_canonical_bounded_duration`],
3596    /// the future M4 per-Aplicacao Envoy reconciler materialization
3597    /// pass, the future per-`:contratos`-edge breaker override the
3598    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3599    ///
3600    /// Prior to this lift the `.circuit_breaker` field was accessed
3601    /// inline at two sites — [`MeshPolicy::is_empty`]'s
3602    /// `self.circuit_breaker.is_none()` arm and the
3603    /// `validate_politicas` gate's `if let Some(cb) = &p.circuit_breaker`
3604    /// bind — two open-coded field-accesses that expressed no
3605    /// compile-time link back to the typed slot. A future extension of
3606    /// the `:politicas :circuit-breaker` axis to a richer author
3607    /// surface — a per-`:contratos`-edge breaker override the operator
3608    /// pins through a future `:contratos :circuit-breaker` slot the
3609    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-cluster
3610    /// breaker-default overlay the M4 CR materializer resolves per-CR,
3611    /// a promotion of the plain `(max_failures, window)` scalar pair to
3612    /// a richer `{max_failures, window, base_ejection_time, max_ejection_percent}`
3613    /// sub-block once Envoy's `outlier_detection` grows the peer
3614    /// ejection-percentage / ejection-time axes — would have had to be
3615    /// threaded through both open-coded copies in lockstep or the
3616    /// emptiness predicate and the validate gate would silently
3617    /// disagree on which breaker declaration a given [`MeshPolicy`]
3618    /// resolves to (a `:politicas` block whose only axis is a
3619    /// `Some :circuit-breaker` would satisfy `is_empty() == false` while
3620    /// the validate path silently read a drifted other value, or vice
3621    /// versa: an author's `(:circuit-breaker (:max-failures 5 :window
3622    /// "60s"))` would omit the value-shape gate while the emptiness
3623    /// predicate still classified the policy as non-empty). Lifting
3624    /// the resolution to a typed method on the substrate primitive
3625    /// means every downstream consumer of the Aplicacao's
3626    /// per-`:politicas` breaker surface reaches for exactly one typed
3627    /// dispatch — the resolver's accept-set migrates as a unit on any
3628    /// future axis addition.
3629    ///
3630    /// Second `Option<Copy-composite-T>`-return accessor on the M3
3631    /// mesh-slot family (sibling of the peer per-`:politicas`
3632    /// [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>` accessor
3633    /// on the same composite-Copy shape, and of the sibling per-
3634    /// `:politicas` [`MeshPolicy::timeout`] 7073d0f
3635    /// `Option<Duration>` / [`MeshPolicy::retries`] bdfb399
3636    /// `Option<u32>` / [`MeshPolicy::mtls_required`] c0110f1
3637    /// `Option<bool>` accessors on the sibling primitive-Copy axes —
3638    /// same "one typed dispatch on the substrate primitive, thin
3639    /// projections at each consumer" discipline extended onto the last
3640    /// unlifted per-`:politicas` scalar-value axis (the composite-Copy
3641    /// `Option<CircuitBreaker>` arm). Named `circuit_breaker()` to
3642    /// match the storage field's name; the accessor's identity maps
3643    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3644    /// docstring already carries. Closes the last unlifted
3645    /// [`MeshPolicy`] accessor axis so every downstream per-`:politicas`
3646    /// reader now routes through a typed dispatch on the substrate
3647    /// primitive.
3648    #[must_use]
3649    pub const fn circuit_breaker(&self) -> Option<CircuitBreaker> {
3650        self.circuit_breaker
3651    }
3652}
3653
3654#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
3655#[serde(rename_all = "camelCase")]
3656pub struct CircuitBreaker {
3657    pub max_failures: u32,
3658    #[serde(with = "supervisor::duration_codec_required")]
3659    pub window: Duration,
3660}
3661
3662impl CircuitBreaker {
3663    /// Substrate-canonical per-`:politicas :circuit-breaker`
3664    /// `:max-failures` Envoy-outlier-detection trip-threshold scalar
3665    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3666    /// breaker trip-count keys off — returns the author-declared
3667    /// `:politicas :circuit-breaker :max-failures` typed `u32` verbatim,
3668    /// copied out of the typed slot's own `u32` storage (`u32` is `Copy`,
3669    /// so the accessor returns by value; no borrow of `&self` past the
3670    /// call). Non-optional (the surrounding `Option<CircuitBreaker>` is
3671    /// the "slot present?" projection at the parent [`MeshPolicy::circuit_breaker`]
3672    /// axis; a `CircuitBreaker` past pattern-match is definitionally
3673    /// present, and its `:max-failures` field carries the trip count as a
3674    /// required-axis scalar).
3675    ///
3676    /// The `:politicas :circuit-breaker :max-failures` axis carries the
3677    /// "consecutive-transient-failure trip threshold" contract
3678    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's `u32` accept-set
3679    /// (zero-floor rejected through
3680    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
3681    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]) maps onto the Envoy
3682    /// `outlier_detection.consecutive_5xx` per-cluster ejection-threshold
3683    /// scalar (equivalently the future `CiliumClusterwideEnvoyConfig`
3684    /// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 acknowledges).
3685    /// Every downstream consumer that reads the trip threshold keys off
3686    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3687    /// cap bracket at caixa-core/src/aplicacao.rs:4022 that gates on the
3688    /// canonical `require_positive_bounded_u32` helper, the future M4
3689    /// per-Aplicacao Envoy config reconciler materialization pass, the
3690    /// future per-`:contratos`-edge breaker-override overlay the
3691    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3692    ///
3693    /// Prior to this lift the `.max_failures` field was accessed inline
3694    /// at one production site — [`AplicacaoSpec::validate_politicas`]'s
3695    /// `require_positive_bounded_u32(cb.max_failures, …)` call — one
3696    /// open-coded field-access that expressed no compile-time link back
3697    /// to the typed sub-struct axis. A future extension of the
3698    /// `:max-failures` axis to a richer author surface — a
3699    /// per-`:contratos`-edge breaker override the operator pins through a
3700    /// future `:contratos :max-failures` slot the MESH-COMPOSITION §III.2
3701    /// #3 roadmap acknowledges, a per-cluster max-failures-default
3702    /// overlay the M4 CR materializer resolves per-CR, a promotion of the
3703    /// plain `u32` trip count to a richer
3704    /// `{consecutive_5xx, consecutive_gateway_failure, consecutive_local_origin_failure}`
3705    /// tuple once Envoy's `outlier_detection` block's peer axes come into
3706    /// scope, a per-Envoy-cluster minimum-request-volume gate before the
3707    /// count arms — would have had to be threaded through every open-
3708    /// coded copy in lockstep or the validate gate and the future M4
3709    /// emit path would silently disagree on which trip threshold a given
3710    /// [`CircuitBreaker`] resolves to (an author's `:max-failures 5`
3711    /// would satisfy validate while the emit path silently read a drifted
3712    /// other value, or vice versa: a validated typed slot would land at
3713    /// the emit boundary as a no-op breaker whose trip threshold is
3714    /// structurally never reached). Lifting the resolution to a typed
3715    /// method on the substrate primitive means every downstream consumer
3716    /// of the Aplicacao's per-`:politicas :circuit-breaker`
3717    /// trip-threshold surface reaches for exactly one typed dispatch —
3718    /// the resolver's accept-set migrates as a unit on any future axis
3719    /// addition.
3720    ///
3721    /// First sub-struct scalar accessor on the M3 mesh-slot family
3722    /// (opens the "per-`CircuitBreaker` / per-`RateLimit` required-axis
3723    /// scalar" projection pattern the sibling `CircuitBreaker::window` /
3724    /// `RateLimit::rate` / `RateLimit::window` future lifts fold on —
3725    /// closes the last unlifted per-`:politicas` scalar-value axis after
3726    /// the c0110f1 / bdfb399 / 7073d0f trajectory closed every scalar-
3727    /// shaped axis on the parent [`MeshPolicy`] optional-slot surface).
3728    /// Same "one typed dispatch on the substrate primitive, thin
3729    /// projections at each consumer" discipline the peer
3730    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
3731    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
3732    /// [`Membro::versao_requirement`] (a40b0e3),
3733    /// [`Entrada::destination`] (6db982c) accessors carry on their
3734    /// respective per-mesh-slot-atom scalar-value axes, extended onto the
3735    /// per-sub-struct required-`u32` axis. Named `max_failures()` to
3736    /// match the storage field's name; the accessor's identity maps onto
3737    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3738    /// docstring already carries.
3739    #[must_use]
3740    pub const fn max_failures(&self) -> u32 {
3741        self.max_failures
3742    }
3743
3744    /// Substrate-canonical per-`:politicas :circuit-breaker` `:window`
3745    /// Envoy-outlier-detection rolling-observation-interval scalar
3746    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3747    /// breaker rolling-window duration keys off — returns the
3748    /// author-declared `:politicas :circuit-breaker :window` typed
3749    /// `Duration` verbatim, copied out of the typed slot's own
3750    /// `Duration` storage (`Duration` is `Copy`, so the accessor returns
3751    /// by value; no borrow of `&self` past the call). Non-optional (the
3752    /// surrounding `Option<CircuitBreaker>` is the "slot present?"
3753    /// projection at the parent [`MeshPolicy::circuit_breaker`] axis; a
3754    /// `CircuitBreaker` past pattern-match is definitionally present,
3755    /// and its `:window` field carries the rolling-observation interval
3756    /// as a required-axis scalar).
3757    ///
3758    /// The `:politicas :circuit-breaker :window` axis carries the
3759    /// "consecutive-transient-failure rolling-observation interval"
3760    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
3761    /// `Duration` accept-set (zero-floor rejected through
3762    /// [`AplicacaoError::PolicyBreakerZeroWindow`], sub-millisecond
3763    /// residue rejected through
3764    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`],
3765    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`]) maps onto the
3766    /// Envoy `outlier_detection.interval` per-cluster
3767    /// ejection-observation-interval scalar (equivalently the future
3768    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3769    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3770    /// consumer that reads the rolling-observation interval keys off
3771    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3772    /// integer-millisecond canonical-form + cap bracket at
3773    /// caixa-core/src/aplicacao.rs:4121 that gates on the canonical
3774    /// [`crate::render::require_positive_canonical_bounded_duration`]
3775    /// helper, the future M4 per-Aplicacao Envoy config reconciler
3776    /// materialization pass, the future per-`:contratos`-edge
3777    /// breaker-override overlay the MESH-COMPOSITION §III.2 #3 roadmap
3778    /// acknowledges).
3779    ///
3780    /// Prior to this lift the `.window` field was accessed inline at
3781    /// one production site — [`AplicacaoSpec::validate_politicas`]'s
3782    /// `require_positive_canonical_bounded_duration(cb.window, …)`
3783    /// call — one open-coded field-access that expressed no compile-
3784    /// time link back to the typed sub-struct axis. A future extension
3785    /// of the `:window` axis to a richer author surface — a
3786    /// per-`:contratos`-edge window override the operator pins through
3787    /// a future `:contratos :window` slot the MESH-COMPOSITION §III.2
3788    /// #3 roadmap acknowledges, a per-cluster window-default overlay
3789    /// the M4 CR materializer resolves per-CR, a promotion of the plain
3790    /// `Duration` observation interval to a richer
3791    /// `{interval, base_ejection_time, max_ejection_percent}` tuple
3792    /// once Envoy's `outlier_detection` block's peer axes come into
3793    /// scope, a per-Envoy-cluster minimum-request-volume gate before
3794    /// the window arms — would have had to be threaded through every
3795    /// open-coded copy in lockstep or the validate gate and the future
3796    /// M4 emit path would silently disagree on which observation
3797    /// interval a given [`CircuitBreaker`] resolves to (an author's
3798    /// `:window "60s"` would satisfy validate while the emit path
3799    /// silently read a drifted other value, or vice versa: a validated
3800    /// typed slot would land at the emit boundary as a breaker whose
3801    /// observation window is structurally so wide that no realistic
3802    /// failure-rate shape can trip it). Lifting the resolution to a
3803    /// typed method on the substrate primitive means every downstream
3804    /// consumer of the Aplicacao's per-`:politicas :circuit-breaker`
3805    /// observation-window surface reaches for exactly one typed
3806    /// dispatch — the resolver's accept-set migrates as a unit on any
3807    /// future axis addition.
3808    ///
3809    /// Second sub-struct scalar accessor on the M3 mesh-slot family —
3810    /// sibling in shape to the just-landed [`CircuitBreaker::max_failures`]
3811    /// (3a74062) required-`u32` accessor on the peer per-`CircuitBreaker`
3812    /// required-axis, extended onto the per-sub-struct required-`Duration`
3813    /// axis; closes the last unlifted per-`CircuitBreaker` scalar-value
3814    /// axis. Same "one typed dispatch on the substrate primitive, thin
3815    /// projections at each consumer" discipline the peer
3816    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
3817    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
3818    /// [`Membro::versao_requirement`] (a40b0e3),
3819    /// [`Entrada::destination`] (6db982c) accessors carry on their
3820    /// respective per-mesh-slot-atom scalar-value axes, extended onto
3821    /// the per-sub-struct required-`Duration` axis. Named `window()` to
3822    /// match the storage field's name; the accessor's identity maps onto
3823    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3824    /// docstring already carries.
3825    #[must_use]
3826    pub const fn window(&self) -> Duration {
3827        self.window
3828    }
3829}
3830
3831#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3832pub struct RateLimit {
3833    /// Requests per window.
3834    pub rate: u32,
3835    /// Window duration.
3836    pub window: Duration,
3837}
3838
3839impl RateLimit {
3840    /// Substrate-canonical per-`:politicas :rate-limit` `:rate`
3841    /// Envoy-local-rate-limit-mesh token-bucket capacity scalar accessor
3842    /// every consumer of the Aplicacao's per-`:contratos`-edge
3843    /// rate-limit-bucket capacity keys off — returns the author-declared
3844    /// `:politicas :rate-limit` typed `u32` verbatim, copied out of the
3845    /// typed slot's own `u32` storage (`u32` is `Copy`, so the accessor
3846    /// returns by value; no borrow of `&self` past the call). Non-optional
3847    /// (the surrounding `Option<RateLimit>` is the "slot present?"
3848    /// projection at the parent [`MeshPolicy::rate_limit`] axis; a
3849    /// `RateLimit` past pattern-match is definitionally present, and its
3850    /// `:rate` field carries the token-bucket capacity as a required-axis
3851    /// scalar).
3852    ///
3853    /// The `:politicas :rate-limit` `:rate` axis carries the
3854    /// "token-bucket capacity" contract (MESH-COMPOSITION §III.2 #3) —
3855    /// the typed slot's `u32` accept-set (zero-floor rejected through
3856    /// [`AplicacaoError::PolicyRateLimitZero`], upper-bounded by
3857    /// [`POLICY_RATE_LIMIT_MAX`]) maps onto the Envoy
3858    /// `local_rate_limit.token_bucket.max_tokens` per-cluster
3859    /// token-bucket-capacity scalar (equivalently the future
3860    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3861    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3862    /// consumer that reads the token-bucket capacity keys off this
3863    /// scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3864    /// cap bracket that gates on the canonical
3865    /// [`crate::render::require_positive_bounded_u32`] helper, the
3866    /// [`rate_limit_codec::render`] `Duration → unit` projection that
3867    /// emits the `<n>/<s|m|h>` author surface, the future M4
3868    /// per-Aplicacao Envoy config reconciler materialization pass, the
3869    /// future per-`:contratos`-edge rate-limit-override overlay the
3870    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3871    ///
3872    /// Prior to this lift the `.rate` field was accessed inline at three
3873    /// production sites — [`AplicacaoSpec::validate_politicas`]'s
3874    /// `require_positive_bounded_u32(rl.rate, …)` call, and the two
3875    /// [`rate_limit_codec::render`] format-arm arms (canonical-window
3876    /// `format!("{}/{unit}", rl.rate)` and non-canonical-window
3877    /// `format!("{}/{}s", rl.rate, …)` fallback). Three open-coded
3878    /// field-accesses that expressed no compile-time link back to the
3879    /// typed sub-struct axis. A future extension of the `:rate` axis
3880    /// to a richer author surface — a per-`:contratos`-edge rate
3881    /// override the operator pins through a future `:contratos :rate`
3882    /// slot the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a
3883    /// per-cluster rate-default overlay the M4 CR materializer resolves
3884    /// per-CR, a promotion of the plain `u32` token capacity to a
3885    /// richer `{max_tokens, tokens_per_fill}` tuple once Envoy's
3886    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
3887    /// axis comes into scope, a per-Envoy-cluster descriptor-key gate
3888    /// before the token arms — would have had to be threaded through
3889    /// every open-coded copy in lockstep or the validate gate, the
3890    /// codec's render path, and the future M4 emit path would silently
3891    /// disagree on which token capacity a given [`RateLimit`] resolves
3892    /// to (an author's `:rate-limit "100/s"` would satisfy validate
3893    /// while the render / emit paths silently read a drifted other
3894    /// value, or vice versa: a validated typed slot would land at the
3895    /// emit boundary as a no-op limiter whose token capacity is
3896    /// structurally so high that no realistic per-edge traffic shape
3897    /// can drain it). Lifting the resolution to a typed method on the
3898    /// substrate primitive means every downstream consumer of the
3899    /// Aplicacao's per-`:politicas :rate-limit` token-capacity surface
3900    /// reaches for exactly one typed dispatch — the resolver's
3901    /// accept-set migrates as a unit on any future axis addition.
3902    ///
3903    /// First sub-struct scalar accessor on the `RateLimit` axis — sibling
3904    /// in shape to the peer per-`CircuitBreaker`
3905    /// [`CircuitBreaker::max_failures`] (3a74062) required-`u32` accessor
3906    /// on the peer per-sub-struct required-axis, extended onto the
3907    /// per-`RateLimit` required-`u32` axis; opens the "per-`RateLimit`
3908    /// required-axis scalar" projection pattern the sibling
3909    /// [`RateLimit::window`] future lift folds on. Same "one typed
3910    /// dispatch on the substrate primitive, thin projections at each
3911    /// consumer" discipline the peer [`WitContract::source`] /
3912    /// [`WitContract::destination`] (7f0fd43), [`WitContract::world_ref`]
3913    /// (0804823), [`Membro::nome`] (4a32abf),
3914    /// [`Membro::versao_requirement`] (a40b0e3),
3915    /// [`Entrada::destination`] (6db982c),
3916    /// [`CircuitBreaker::max_failures`] (3a74062),
3917    /// [`CircuitBreaker::window`] (373957f) accessors carry on their
3918    /// respective per-mesh-slot-atom scalar-value axes. Named `rate()`
3919    /// to match the storage field's name; the accessor's identity maps
3920    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3921    /// docstring already carries.
3922    #[must_use]
3923    pub const fn rate(&self) -> u32 {
3924        self.rate
3925    }
3926
3927    /// Substrate-canonical per-`:politicas :rate-limit` `:window`
3928    /// Envoy-local-rate-limit-mesh token-bucket refill-period scalar
3929    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3930    /// rate-limit-bucket refill period keys off — returns the
3931    /// author-declared `:politicas :rate-limit` typed `Duration`
3932    /// verbatim, copied out of the typed slot's own `Duration` storage
3933    /// (`Duration` is `Copy`, so the accessor returns by value; no
3934    /// borrow of `&self` past the call). Non-optional (the surrounding
3935    /// `Option<RateLimit>` is the "slot present?" projection at the
3936    /// parent [`MeshPolicy::rate_limit`] axis; a `RateLimit` past
3937    /// pattern-match is definitionally present, and its `:window`
3938    /// field carries the token-bucket refill period as a required-axis
3939    /// scalar).
3940    ///
3941    /// The `:politicas :rate-limit` `:window` axis carries the
3942    /// "token-bucket refill period" contract (MESH-COMPOSITION §III.2 #3)
3943    /// — the typed slot's `Duration` accept-set (constrained to the
3944    /// three canonical windows `{1s, 60s, 3600s}` the
3945    /// [`RATE_LIMIT_UNIT_TABLE`] lifts, rejected off-set through
3946    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]) maps
3947    /// onto the Envoy `local_rate_limit.token_bucket.fill_interval`
3948    /// per-cluster token-bucket-refill-period scalar (equivalently the
3949    /// future `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3950    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3951    /// consumer that reads the token-bucket refill period keys off
3952    /// this scalar (the [`AplicacaoSpec::validate_politicas`]
3953    /// canonical-window gate that keys off
3954    /// [`is_canonical_rate_limit_window`], the
3955    /// [`rate_limit_codec::render`] `Duration → unit` projection that
3956    /// emits the `<n>/<s|m|h>` author surface — canonical arm via
3957    /// [`rate_limit_window_unit`] and non-canonical fallback via
3958    /// `.as_secs()`, the future M4 per-Aplicacao Envoy config
3959    /// reconciler materialization pass, the future per-`:contratos`-
3960    /// edge rate-limit-override overlay the MESH-COMPOSITION §III.2 #3
3961    /// roadmap acknowledges).
3962    ///
3963    /// Prior to this lift the `.window` field was accessed inline at
3964    /// three production sites — [`AplicacaoSpec::validate_politicas`]'s
3965    /// `is_canonical_rate_limit_window(rl.window)` shape-gate call
3966    /// plus the sibling [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]
3967    /// error-payload construction on refusal, and the two
3968    /// [`rate_limit_codec::render`] arms
3969    /// (canonical-window `rate_limit_window_unit(rl.window)` dispatch
3970    /// and non-canonical-window `rl.window.as_secs()` fallback). Three
3971    /// open-coded field-accesses that expressed no compile-time link
3972    /// back to the typed sub-struct axis. A future extension of the
3973    /// `:window` axis to a richer author surface — a per-`:contratos`-
3974    /// edge window override the operator pins through a future
3975    /// `:contratos :window` slot the MESH-COMPOSITION §III.2 #3 roadmap
3976    /// acknowledges, a per-cluster window-default overlay the M4 CR
3977    /// materializer resolves per-CR, a promotion of the plain
3978    /// `Duration` refill period to a richer
3979    /// `{fill_interval, tokens_per_fill}` tuple once Envoy's
3980    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
3981    /// axis comes into scope, an addition of a `"d"` day suffix once
3982    /// Envoy's `rate_limit_action` grows daily-bucket support — would
3983    /// have had to be threaded through every open-coded copy in
3984    /// lockstep or the validate gate, the codec's render path, and
3985    /// the future M4 emit path would silently disagree on which
3986    /// refill period a given [`RateLimit`] resolves to (an author's
3987    /// `:rate-limit "100/s"` would satisfy validate while the render
3988    /// / emit paths silently read a drifted other value, or vice
3989    /// versa: a validated typed slot would land at the emit boundary
3990    /// as a limiter whose refill period is structurally so long that
3991    /// no realistic per-edge traffic shape stays inside the token
3992    /// budget). Lifting the resolution to a typed method on the
3993    /// substrate primitive means every downstream consumer of the
3994    /// Aplicacao's per-`:politicas :rate-limit` refill-period surface
3995    /// reaches for exactly one typed dispatch — the resolver's
3996    /// accept-set migrates as a unit on any future axis addition.
3997    ///
3998    /// Second sub-struct scalar accessor on the `RateLimit` axis —
3999    /// sibling in shape to the just-landed [`RateLimit::rate`]
4000    /// (7f81a60) required-`u32` accessor on the peer per-`RateLimit`
4001    /// required-axis, extended onto the per-sub-struct
4002    /// required-`Duration` axis; closes the last unlifted
4003    /// per-`RateLimit` scalar-value axis (the M3 mesh-slot family's
4004    /// per-sub-struct accessor coverage is now complete across both
4005    /// `CircuitBreaker` and `RateLimit`). Same "one typed dispatch on
4006    /// the substrate primitive, thin projections at each consumer"
4007    /// discipline the peer [`CircuitBreaker::max_failures`] (3a74062),
4008    /// [`CircuitBreaker::window`] (373957f), [`RateLimit::rate`]
4009    /// (7f81a60), [`WitContract::source`] / [`WitContract::destination`]
4010    /// (7f0fd43), [`WitContract::world_ref`] (0804823),
4011    /// [`Membro::nome`] (4a32abf),
4012    /// [`Membro::versao_requirement`] (a40b0e3),
4013    /// [`Entrada::destination`] (6db982c) accessors carry on their
4014    /// respective per-mesh-slot-atom scalar-value axes. Named
4015    /// `window()` to match the storage field's name; the accessor's
4016    /// identity maps onto the canonical MESH-COMPOSITION §III.2
4017    /// vocabulary the slot's docstring already carries.
4018    #[must_use]
4019    pub const fn window(&self) -> Duration {
4020        self.window
4021    }
4022
4023    /// Recognize this rate-limit's `:window` as a canonical
4024    /// [`RateLimitUnit`] arm — `Some(RateLimitUnit)` when the window
4025    /// exactly matches one of the three closed-set arm-Durations
4026    /// (`1s` / `60s` / `3600s`), `None` when the window carries a
4027    /// non-canonical magnitude the codec's round-trip would break on
4028    /// (sub-second residue, or a second-magnitude outside the set
4029    /// [`RateLimitUnit::ALL`] enumerates).
4030    ///
4031    /// Every validated [`RateLimit`] past [`AplicacaoSpec::validate_politicas`]
4032    /// returns `Some` here — the validate gate's
4033    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`] arm
4034    /// rejects every window this accessor returns `None` on. Downstream
4035    /// consumers past validate (the codec's [`rate_limit_codec::render`]
4036    /// path, the future M4 per-Aplicacao Envoy config reconciler's
4037    /// materialization pass, the future per-`:contratos`-edge rate-limit-
4038    /// override overlay the MESH-COMPOSITION §III.2 #3 roadmap
4039    /// acknowledges) that read the typed unit off a validated slot can
4040    /// pattern-match on the returned `Some` without re-checking
4041    /// canonicality at the consumer layer — the typed enum surface is
4042    /// the load-bearing carrier of the canonicality invariant.
4043    ///
4044    /// Preferred over the free [`is_canonical_rate_limit_window`]
4045    /// module-private helper at any call site that has the typed
4046    /// [`RateLimit`] in hand (the codec's `render` arm at
4047    /// [`rate_limit_codec::render`], the validate gate's canonical-form
4048    /// arm in [`AplicacaoSpec::validate_politicas`], any future
4049    /// per-`:contratos` edge-override overlay resolver): those consumers
4050    /// reach for the typed enum without going through the
4051    /// `.window()` scalar-projection layer, and get the enum value
4052    /// directly (which the codec's render arm can then format via
4053    /// [`RateLimitUnit::as_suffix`] / [`std::fmt::Display`]). Same
4054    /// "typed sub-struct scalar accessor, one dispatch on the substrate
4055    /// primitive" discipline the sibling [`RateLimit::rate`] and
4056    /// [`RateLimit::window`] accessors carry on the peer per-sub-struct
4057    /// scalar-value axes, extended onto the per-`RateLimit` typed-unit
4058    /// projection axis (the third scalar accessor on the [`RateLimit`]
4059    /// axis, first typed-enum-return projection).
4060    ///
4061    /// `pub const fn` — the typed-`RateLimit`-projection dispatch onto
4062    /// the canonical [`RateLimitUnit`] arm now carries the same
4063    /// `const`-eval-surface posture the sibling `pub const fn`
4064    /// [`Self::rate`] / [`Self::window`] scalar-projection accessors on
4065    /// this typed sub-struct already carry, composing through the
4066    /// peer-lifted `pub const fn` [`RateLimitUnit::from_window`]
4067    /// reverse-resolver in `const` context. Any downstream substrate-
4068    /// side `const`-context consumer of the typed unit (a module-scope
4069    /// `const _:() = assert!(matches!(rl.canonical_unit(), Some(RateLimitUnit::Second)))`
4070    /// invariant pin on a typed fixture, a future M4 admission-webhook
4071    /// `const fn` per-`:politicas :rate-limit :window` canonical-arm
4072    /// resolver over a typed [`RateLimit`], any future `const fn`
4073    /// per-`:contratos`-edge rate-limit-override overlay resolver over
4074    /// the substrate primitive) now reaches the same typed dispatch on
4075    /// the substrate primitive at const-eval time as at runtime.
4076    ///
4077    /// Pinned load-bearing at the substrate-primitive level by
4078    /// [`tests::rate_limit_canonical_unit_accessor_is_const_fn`] (const-
4079    /// eval-surface pin via `const fn` wrapper).
4080    #[must_use]
4081    pub const fn canonical_unit(&self) -> Option<RateLimitUnit> {
4082        RateLimitUnit::from_window(self.window)
4083    }
4084}
4085
4086/// Typed closed-set enum for the three canonical `:politicas :rate-limit`
4087/// `:window` units — `Second` / `Minute` / `Hour` — the `rate_limit_codec`
4088/// round-trips losslessly (`"<n>/s"` / `"<n>/m"` / `"<n>/h"`).
4089///
4090/// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer of
4091/// the `:politicas :rate-limit` unit surface reads from
4092/// ([`rate_limit_codec::parse`]'s `unit → Duration` dispatch,
4093/// [`rate_limit_codec::render`]'s `Duration → unit` projection, the
4094/// [`is_canonical_rate_limit_window`] predicate the
4095/// [`AplicacaoSpec::validate_politicas`] gate keys off, the future M4
4096/// per-Aplicacao Envoy config reconciler's `local_rate_limit.token_bucket.fill_interval`
4097/// projection) now lives inside this typed enum's `match self` arms — a
4098/// future rate-limit-unit addition (a `"d"` day suffix once Envoy's
4099/// `rate_limit_action` grows daily-bucket support) is one new variant
4100/// plus the exhaustiveness arms on the four methods, so every consumer
4101/// picks it up by compile-time construction rather than a runtime
4102/// table-scan miss.
4103///
4104/// The prior `RATE_LIMIT_UNIT_TABLE: &[(&str, u64)]` slice-of-tuples was
4105/// scanned via `find_map` at every projection call — an untyped runtime
4106/// walk that carried no compile-time link between the parse arm's
4107/// accepted suffixes, the render arm's emitted suffixes, and the
4108/// validate gate's accepted windows. A future rate-limit-unit addition
4109/// that landed one row without threading through the other consumers
4110/// (or a copy-paste flip that collapsed two rows onto one suffix) would
4111/// silently split the accepted-set across the three consumers — the
4112/// parse arm accepts `"d"` and rejects `"s"`, the render arm emits `"h"`
4113/// for a 24h window that parse can't round-trip, the validate gate
4114/// misses one canonical window. Lifting the pairs onto a typed
4115/// closed-set enum with exhaustive `match` arms makes any such
4116/// half-landed extension a caixa-core build error (the compiler enforces
4117/// arm coverage on every method), not a silent per-consumer drift
4118/// surfacing at apply time. Same "closed-set typed-enum discriminator"
4119/// discipline the sibling [`PlacementStrategy`] (cc8f749),
4120/// [`crate::supervisor::RestartStrategy`],
4121/// [`crate::supervisor::RestartPolicy`],
4122/// [`crate::upgrade::UpgradeInstruction`], and [`crate::CaixaKind`]
4123/// closed-set typed enums carry on their respective closed-set axes —
4124/// extended onto the seventh closed-set typed-enum discriminator axis
4125/// on the caixa typed surface (the `:politicas :rate-limit :window`
4126/// canonical-unit axis).
4127#[derive(
4128    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
4129)]
4130pub enum RateLimitUnit {
4131    /// 1-second window — canonical author-surface suffix `"s"`
4132    /// (`"<n>/s"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
4133    /// with a 1s magnitude.
4134    Second,
4135    /// 1-minute window — canonical author-surface suffix `"m"`
4136    /// (`"<n>/m"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
4137    /// with a 60s magnitude.
4138    Minute,
4139    /// 1-hour window — canonical author-surface suffix `"h"`
4140    /// (`"<n>/h"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
4141    /// with a 3600s magnitude.
4142    Hour,
4143}
4144
4145impl RateLimitUnit {
4146    /// Exhaustive iteration surface for every consumer that reads the
4147    /// full canonical-unit set (the byte-parity witness against the
4148    /// prior `RATE_LIMIT_UNIT_TABLE` shape, the future M4 admission
4149    /// webhook's accepted-suffix listing in its rejection body, any
4150    /// future round-trip fuzz harness). A future variant addition to
4151    /// [`RateLimitUnit`] extends this slice as a single edit and every
4152    /// consumer picks up the new entry by construction — the compiler-
4153    /// checked exhaustiveness on the sibling method `match` arms is the
4154    /// build-time guarantee that no arm forgets to grow.
4155    pub const ALL: &'static [Self] = &[Self::Second, Self::Minute, Self::Hour];
4156
4157    /// Canonical author-surface suffix — the `"s"` / `"m"` / `"h"` byte-
4158    /// string every `<n>/<unit>` rate-limit shape carries after its
4159    /// `/` separator. The single source of truth the codec's parse and
4160    /// render arms both dispatch on: the parse arm matches an incoming
4161    /// suffix against every [`RateLimitUnit::ALL`] entry's `as_suffix`
4162    /// output; the render arm emits the entry's `as_suffix` verbatim
4163    /// after the rate magnitude.
4164    #[must_use]
4165    pub const fn as_suffix(self) -> &'static str {
4166        match self {
4167            Self::Second => "s",
4168            Self::Minute => "m",
4169            Self::Hour => "h",
4170        }
4171    }
4172
4173    /// Canonical `Duration` for this unit — the token-bucket refill
4174    /// period the [`RateLimit::window`] axis carries when the surrounding
4175    /// slot's `:rate-limit` author surface named this unit.
4176    #[must_use]
4177    pub const fn window(self) -> Duration {
4178        Duration::from_secs(match self {
4179            Self::Second => 1,
4180            Self::Minute => 60,
4181            Self::Hour => 3_600,
4182        })
4183    }
4184
4185    /// Parse the `<n>/<unit>`-shaped suffix into the typed enum, or
4186    /// `None` when `suffix` is outside the closed-set arm-string set
4187    /// [`Self::as_suffix`] emits. The single `str → Self` projection
4188    /// [`rate_limit_codec::parse`] consumes.
4189    #[must_use]
4190    pub fn from_suffix(suffix: &str) -> Option<Self> {
4191        Self::ALL.iter().copied().find(|u| u.as_suffix() == suffix)
4192    }
4193
4194    /// Recognize a canonical rate-limit `Duration` as one of the three
4195    /// arms, or `None` when `window` carries sub-second residue or a
4196    /// second-magnitude outside the closed-set arm-window set
4197    /// [`Self::window`] emits. The single `Duration → Self` projection
4198    /// [`rate_limit_codec::render`] + [`is_canonical_rate_limit_window`]
4199    /// both consume.
4200    ///
4201    /// `pub const fn` — the reverse `Duration → Self` projection now
4202    /// carries the same `const`-eval-surface posture the sibling
4203    /// `pub const fn` [`Self::as_suffix`] / [`Self::window`] scalar-
4204    /// projection accessors on this closed-set typed enum already
4205    /// carry, and the paired `pub const fn` [`RateLimit::canonical_unit`]
4206    /// typed-`RateLimit`-projection sibling composes through in `const`
4207    /// context. Routes byte-for-byte through the peer `pub const fn`
4208    /// [`Self::window`] canonical-`Duration` projection so any future
4209    /// arm-magnitude edit on the sibling accessor reaches this reverse
4210    /// resolver by construction — the `s == Self::<Arm>.window().as_secs()`
4211    /// per-arm probes each dispatch through one `pub const fn` on the
4212    /// substrate primitive rather than a hand-authored per-arm second-
4213    /// magnitude literal that would silently drift on any future
4214    /// [`Self::window`] arm-magnitude edit.
4215    ///
4216    /// Prior to the `const` lift the body dispatched through
4217    /// `Self::ALL.iter().copied().find(|u| u.window() == window)` — an
4218    /// iterator-driven linear scan whose iterator methods
4219    /// (`.iter()` / `.copied()` / `.find()`) and `Duration`-side
4220    /// `PartialEq` dispatch each carry non-`const` bounds on stable
4221    /// Rust 1.94, so any downstream substrate-side `const`-context
4222    /// consumer of the reverse resolver (a module-scope
4223    /// `const _:() = assert!(RateLimitUnit::from_window(<canonical>).is_some())`
4224    /// invariant pin on a typed fixture, a future M4
4225    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
4226    /// webhook `const fn` per-`:politicas` canonical-window floor over a
4227    /// typed [`RateLimit`] scalar, any future `const fn`
4228    /// per-`:contratos`-edge rate-limit-override overlay resolver over
4229    /// the substrate primitive that wants to fan on the canonical unit
4230    /// at compile time) surfaced as a downstream E0015 far from the
4231    /// resolver's own declaration. The `pub const fn` posture closes
4232    /// the drift structurally at caixa-core build time.
4233    ///
4234    /// Pinned load-bearing at the substrate-primitive level by
4235    /// [`tests::rate_limit_unit_from_window_accessor_is_const_fn`] (const-
4236    /// eval-surface pin via `const fn` wrapper) and
4237    /// [`tests::rate_limit_unit_from_window_composes_through_window_accessor`]
4238    /// (composition-witness pin against the peer `Self::window` scalar
4239    /// dispatch).
4240    #[must_use]
4241    pub const fn from_window(window: Duration) -> Option<Self> {
4242        if window.subsec_nanos() != 0 {
4243            return None;
4244        }
4245        // Route through the peer `pub const fn` [`Self::window`]
4246        // canonical-`Duration` projection so any future arm-magnitude
4247        // edit on the sibling accessor reaches this reverse resolver by
4248        // construction — the per-arm `secs` comparison keys off
4249        // `Duration::as_secs` (`pub const fn`), not a hand-authored
4250        // per-arm second-magnitude literal that would silently drift.
4251        let secs = window.as_secs();
4252        if secs == Self::Second.window().as_secs() {
4253            Some(Self::Second)
4254        } else if secs == Self::Minute.window().as_secs() {
4255            Some(Self::Minute)
4256        } else if secs == Self::Hour.window().as_secs() {
4257            Some(Self::Hour)
4258        } else {
4259            None
4260        }
4261    }
4262
4263    /// Canonical rate-limit `Duration` for a unit suffix, or `None` when
4264    /// `suffix` is outside the closed-set arm-string set [`Self::as_suffix`]
4265    /// emits. Composes [`Self::from_suffix`] with [`Self::window`] — the
4266    /// single `&str → Duration` projection [`rate_limit_codec::parse`]
4267    /// consumes.
4268    ///
4269    /// The peer `Duration → &'static str` axis folded onto the substrate
4270    /// primitive [`RateLimit::canonical_unit`] typed accessor once both
4271    /// production consumers ([`rate_limit_codec::render`] and
4272    /// [`AplicacaoSpec::validate_politicas`]'s canonical-window gate)
4273    /// migrated (61421a6): the free helper's `Duration → &str` projection
4274    /// is now the two-step composition
4275    /// `rl.canonical_unit().map(RateLimitUnit::as_suffix)` every consumer
4276    /// reads through the typed accessor. This lift closes the peer
4277    /// `&str → Duration` axis by folding the vestigial module-private
4278    /// `rate_limit_window_from_unit` delegate onto this associated method
4279    /// — the codec's parse arm and every future wire-side consumer of the
4280    /// `&str → Duration` projection (a future admission-webhook that
4281    /// reads a `:rate-limit` shape off a CR spec's `raw string` value
4282    /// before it's promoted to a validated typed slot, a future
4283    /// `feira lint` shape-probe that reads the author-surface bytes
4284    /// verbatim) now reach for exactly one typed dispatch on the
4285    /// substrate primitive.
4286    ///
4287    /// Same "closed-set typed-enum discriminator with canonical
4288    /// projections per axis" discipline the sibling [`Self::as_suffix`]
4289    /// / [`Self::window`] / [`Self::from_suffix`] / [`Self::from_window`]
4290    /// methods carry — this associated method closes the fifth (and last
4291    /// unlifted) projection axis on the arm-table, so the closed-set enum
4292    /// now owns every `str ↔ Duration ↔ Self` typed dispatch every
4293    /// consumer of the `:politicas :rate-limit :window` axis reaches
4294    /// through. A future rate-limit-unit addition (a `"d"` day suffix
4295    /// once Envoy's `rate_limit_action` grows daily-bucket support, a
4296    /// `"ms"` sub-second window once high-throughput per-edge policies
4297    /// come into scope per MESH-COMPOSITION §III.2 #3) is one new
4298    /// variant plus one arm per method — the compiler enforces
4299    /// exhaustiveness on every consumer's `match self` arms and picks
4300    /// the new unit up by construction across all five projections.
4301    #[must_use]
4302    pub fn window_from_suffix(suffix: &str) -> Option<Duration> {
4303        Self::from_suffix(suffix).map(Self::window)
4304    }
4305}
4306
4307/// Route [`std::fmt::Display`] through [`RateLimitUnit::as_suffix`], so
4308/// every consumer that formats a canonical rate-limit unit as user-
4309/// facing text (future M4 admission-webhook rejection bodies naming
4310/// the accepted-suffix set, future `feira app graph` per-`:politicas`
4311/// unit column) lands on the same `"s"` / `"m"` / `"h"` byte-string the
4312/// codec's parse arm accepts and the render arm emits. Same
4313/// as_str-through-Display convergence discipline the sibling
4314/// [`PlacementStrategy`], [`crate::CaixaKind`],
4315/// [`crate::supervisor::RestartStrategy`], and
4316/// [`crate::supervisor::RestartPolicy`] closed-set typed enums carry.
4317impl std::fmt::Display for RateLimitUnit {
4318    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4319        f.write_str(self.as_suffix())
4320    }
4321}
4322
4323/// Upper-bound ceiling on the `:politicas :timeout` axis — every
4324/// validated [`MeshPolicy::timeout`] past
4325/// [`AplicacaoSpec::validate_politicas`] lies in `1ms..=POLICY_TIMEOUT_MAX`
4326/// (inclusive on both ends, integer-millisecond magnitudes by the
4327/// canonical-form gate immediately preceding).
4328///
4329/// The typed field is `Option<Duration>` (the zero-floor arm
4330/// [`AplicacaoError::PolicyTimeoutZero`] already rejects
4331/// `Duration::ZERO`, and the canonical-form arm
4332/// [`AplicacaoError::PolicyTimeoutNotCanonical`] already rejects
4333/// sub-millisecond residue), so a programmatic struct literal
4334/// (`MeshPolicy { timeout: Some(Duration::from_secs(86_400)), .. }` —
4335/// 24h) and the equivalent author-surface form
4336/// (`(:politicas (:timeout "24h"))` — the codec emits `"h"` for any
4337/// integer-hour magnitude) both round-trip cleanly through serde — a
4338/// structurally unbounded `Duration` ceiling. A `:timeout` value far
4339/// above the documented production-playbook band (Envoy default `15s`,
4340/// Istio per-route typical `≤ 30s`, AWS App Mesh `httpRouteTimeout`
4341/// schema typical `≤ 60s`, Linkerd `request_timeout` typical `10s`,
4342/// Kubernetes ingress-nginx `proxy_read_timeout` default `60s` capped
4343/// at `~3600s`) silently degenerates the mesh-policy contract: the
4344/// per-call deadline is structurally so long that no realistic
4345/// synchronous-`:contratos` traversal can reach it, so the typed slot
4346/// becomes a no-op carried on every emitted Envoy / Cilium L7 timeout
4347/// overlay — the MESH-COMPOSITION §V CSE invariant "no infinite
4348/// blocking" degenerates to a nominal-only contract on the
4349/// synchronous-call path. Pairs with the [`POLICY_RETRIES_MAX`] cap on
4350/// the sibling `:politicas :retries` axis and the
4351/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap on the sibling
4352/// `:politicas :circuit-breaker :max-failures` axis — all three close
4353/// the "structurally unbounded ceiling on a typed `:politicas` axis"
4354/// footgun the prior zero-floor-and-canonical-form-only checks left
4355/// open.
4356///
4357/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
4358/// shared duration codec emits (`"<n>h"` for any integer-hour
4359/// magnitude) — every value in the canonical authoring form's
4360/// `<integer><unit>` grammar at or below this cap renders to a clean
4361/// canonical string. The cap sits an order of magnitude above every
4362/// documented production-playbook recommendation band (Envoy default
4363/// `15s`, Istio production `≤ 30s`, Linkerd production `≤ 10s`, AWS
4364/// App Mesh production `≤ 60s`) and at the Kubernetes ingress-nginx
4365/// configured maximum (`proxy_read_timeout` typical max `3600s`),
4366/// below the clearly-pathological "effectively no timeout" floor
4367/// (`24h`, `7d`, `Duration::MAX`): a value the author can plausibly
4368/// want for a long-running synchronous workflow, but a hard wall above
4369/// which the mesh-level deadline is structurally a non-deadline.
4370/// Lifted as a typed `pub const` so the bound has exactly one source
4371/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4372/// materializer's admission webhook and the caixa-mesh-side
4373/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
4374/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
4375/// other typed upper bound in this crate carries
4376/// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
4377/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4378/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4379/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4380pub const POLICY_TIMEOUT_MAX: Duration = Duration::from_secs(3600);
4381
4382/// Upper-bound ceiling on the `:politicas :retries` axis — every
4383/// validated [`MeshPolicy::retries`] past
4384/// [`AplicacaoSpec::validate_politicas`] lies in `1..=POLICY_RETRIES_MAX`.
4385///
4386/// The typed slot is `Option<u32>` (`None` = no retries on transient
4387/// failure; `Some(0)` already rejected by the
4388/// [`AplicacaoError::PolicyRetriesZero`] zero-floor arm), so a
4389/// programmatic struct literal (`MeshPolicy { retries: Some(100_000),
4390/// .. }`) and the equivalent author-surface form
4391/// (`(:politicas (:retries 100000))`) both round-trip cleanly through
4392/// serde / the codec — a structurally unbounded `u32` ceiling. The
4393/// runtime substrate that consumes the value (Envoy's
4394/// `retry_policy.num_retries`, the `CiliumClusterwideEnvoyConfig`
4395/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 names, AWS
4396/// App Mesh's `gRPCRouteRetryPolicy.maxRetries` whose schema-side
4397/// admission cap is 10) translates a four-billion-retry policy into a
4398/// thundering-herd amplification vector on transient failure — the
4399/// caller's one request fans out to `retries` server-side calls per
4400/// edge per traversal, multiplying load by `(retries+1)^depth` across
4401/// the synchronous-`:contratos` subgraph. The MESH-COMPOSITION §V CSE
4402/// invariant "no infinite blocking" pairs with a no-runaway-amplification
4403/// invariant on the retry axis; both belong at the typed-slot layer.
4404///
4405/// The `10` ceiling matches AWS App Mesh's explicit hard cap (the only
4406/// upstream mesh-policy schema that documents one) and sits above the
4407/// Envoy / Istio practical-recommendation band (`num_retries ≤ 5` in
4408/// every documented production playbook): a value the author can
4409/// plausibly want, but a hard wall above which the policy is
4410/// structurally a footgun. Lifted as a typed `pub const` so the bound
4411/// has exactly one source of truth — a future axis reaching for the
4412/// same value (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4413/// materializer's admission webhook, the caixa-mesh-side
4414/// `CiliumClusterwideEnvoyConfig` overlay's per-edge cap) reads from
4415/// one place. Same shape every other typed upper bound in this crate
4416/// carries ([`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4417/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4418/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
4419/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4420pub const POLICY_RETRIES_MAX: u32 = 10;
4421
4422/// Upper-bound ceiling on the `:politicas :circuit-breaker :max-failures`
4423/// axis — every validated [`CircuitBreaker::max_failures`] past
4424/// [`AplicacaoSpec::validate_politicas`] lies in
4425/// `1..=POLICY_BREAKER_MAX_FAILURES_MAX`.
4426///
4427/// The typed field is `u32` (the zero-floor arm
4428/// [`AplicacaoError::PolicyBreakerZeroFailures`] already rejects
4429/// `0` — a breaker that trips on the first call), so a programmatic
4430/// struct literal (`CircuitBreaker { max_failures: u32::MAX, .. }`)
4431/// and the equivalent author-surface form
4432/// (`(:circuit-breaker (:max-failures 4294967295))`) both round-trip
4433/// cleanly through serde — a structurally unbounded `u32` ceiling. A
4434/// `max_failures` value far above the documented production-playbook
4435/// band (Hystrix `circuitBreaker.requestVolumeThreshold` default 20,
4436/// Istio `outlierDetection.consecutive5xxErrors` default 5, Envoy
4437/// `outlier_detection.consecutive_5xx` default 5, Polly / Resilience4j
4438/// typical 5–50) silently disables the breaker's protection role:
4439/// the threshold is structurally so high that no realistic
4440/// failures-per-`:window` traffic shape can reach it, so the breaker
4441/// never trips and the typed slot becomes a no-op carried on every
4442/// emitted Envoy / Cilium L7 overlay. Pairs with the
4443/// [`POLICY_RETRIES_MAX`] cap on the sibling `:politicas :retries`
4444/// axis — both close the "structurally unbounded `u32` ceiling on a
4445/// typed policy axis" footgun the prior zero-floor-only checks left
4446/// open.
4447///
4448/// The `1000` ceiling sits an order of magnitude above every
4449/// documented upstream production-playbook recommendation band (the
4450/// highest is Hystrix's 20-default `requestVolumeThreshold`, the
4451/// Istio / Envoy / Polly / Resilience4j ones all sit ≤ 50) and below
4452/// the clearly-pathological "effectively no protection"
4453/// floor (`10_000`, `100_000`, `u32::MAX`): a value the author can
4454/// plausibly want at hyperscale, but a hard wall above which the
4455/// policy is structurally a no-op. Lifted as a typed `pub const` so
4456/// the bound has exactly one source of truth — the future M4
4457/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
4458/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
4459/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
4460/// one place. Same shape every other typed upper bound in this crate
4461/// carries ([`POLICY_RETRIES_MAX`],
4462/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4463/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4464/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4465pub const POLICY_BREAKER_MAX_FAILURES_MAX: u32 = 1000;
4466
4467/// Upper-bound ceiling on the `:politicas :circuit-breaker :window` axis —
4468/// every validated [`CircuitBreaker::window`] past
4469/// [`AplicacaoSpec::validate_politicas`] lies in
4470/// `1ms..=POLICY_BREAKER_WINDOW_MAX` (inclusive on both ends,
4471/// integer-millisecond magnitudes by the canonical-form gate
4472/// immediately preceding).
4473///
4474/// The typed field is `Duration` (the zero-floor arm
4475/// [`AplicacaoError::PolicyBreakerZeroWindow`] already rejects
4476/// `Duration::ZERO`, and the canonical-form arm
4477/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`] already rejects
4478/// sub-millisecond residue), so a programmatic struct literal
4479/// (`CircuitBreaker { window: Duration::from_secs(86_400), .. }` — 24h)
4480/// and the equivalent author-surface form
4481/// (`(:circuit-breaker (:window "24h"))` — the codec emits `"h"` for any
4482/// integer-hour magnitude) both round-trip cleanly through serde — a
4483/// structurally unbounded `Duration` ceiling. A `:window` value far
4484/// above the documented production-playbook band (Hystrix
4485/// `metrics.rollingStats.timeInMilliseconds` default `10s`,
4486/// resilience4j `slidingWindowSize` time-based typical `10s..=60s`,
4487/// Istio `outlierDetection.interval` default `10s`, Envoy
4488/// `outlier_detection.interval` default `10s`, AWS App Mesh
4489/// circuit-breaker time-window typical `30s..=300s`) degenerates the
4490/// breaker's role: a rolling-window failure counter whose window is
4491/// hours long is operationally a lifetime counter, the breaker's
4492/// "recent failures" memory is structurally so long that transient
4493/// failures are never forgotten, and the typed slot becomes a no-op
4494/// trigger that trips once and stays tripped for the lifetime of the
4495/// component carried on every emitted Envoy / Cilium L7 overlay.
4496///
4497/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
4498/// shared duration codec emits (`"<n>h"` for any integer-hour
4499/// magnitude) — every value in the canonical authoring form's
4500/// `<integer><unit>` grammar at or below this cap renders to a clean
4501/// canonical string — and matches the sibling [`POLICY_TIMEOUT_MAX`]
4502/// cap on the first typed-`Duration` `:politicas` axis: the two
4503/// duration-typed `:politicas` axes now share a single uniform top
4504/// edge so the next typed-slot wiring (the future caixa-mesh
4505/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay, the M4
4506/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-policy
4507/// admission webhook) reaches for either field knowing the value is
4508/// in `1ms..=1h` without re-validating at the renderer layer. The cap
4509/// sits two orders of magnitude above every documented upstream
4510/// production-playbook recommendation band (Hystrix / resilience4j /
4511/// Istio / Envoy all default to 10s; AWS App Mesh maxes out at ~5m)
4512/// and below the clearly-pathological "rolling window degenerates to
4513/// lifetime counter" floor (`24h`, `7d`, `Duration::MAX`): a value the
4514/// author can plausibly want for a very-low-traffic long-tail
4515/// failure-detection window, but a hard wall above which the breaker's
4516/// rolling-window contract is structurally a lifetime-counter contract.
4517/// Lifted as a typed `pub const` so the bound has exactly one source
4518/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4519/// materializer's admission webhook and the caixa-mesh-side
4520/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
4521/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
4522/// other typed upper bound in this crate carries
4523/// ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
4524/// [`POLICY_BREAKER_MAX_FAILURES_MAX`],
4525/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4526/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4527/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4528pub const POLICY_BREAKER_WINDOW_MAX: Duration = Duration::from_secs(3600);
4529
4530/// Upper-bound ceiling on the `:politicas :rate-limit` rate axis —
4531/// every validated [`RateLimit::rate`] past
4532/// [`AplicacaoSpec::validate_politicas`] lies in
4533/// `1..=POLICY_RATE_LIMIT_MAX`.
4534///
4535/// The typed field is `u32` (the zero-floor arm
4536/// [`AplicacaoError::PolicyRateLimitZero`] already rejects `0` — a
4537/// zero-rate limit denies every request, the canonical "I forgot
4538/// that 0 means deny-everything" footgun), so a programmatic struct
4539/// literal (`RateLimit { rate: u32::MAX, window: Duration::from_secs(1) }`)
4540/// and the equivalent author-surface form (`(:rate-limit "4294967295/s")`
4541/// — the `rate_limit_codec` parses any `u32`-shaped magnitude) both
4542/// round-trip cleanly through serde — a structurally unbounded `u32`
4543/// ceiling. The runtime substrate consuming the value (Envoy's
4544/// `local_rate_limit.token_bucket.max_tokens`, the future
4545/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
4546/// MESH-COMPOSITION §III.2 #3 names) translates a four-billion-token
4547/// rate-limit into a no-op rate-limiter: the bucket capacity is
4548/// structurally so high no realistic per-edge traffic shape can
4549/// drain it, the limiter never trips, and the typed slot becomes a
4550/// "rate-limit declared, no enforcement" footgun — the canonical
4551/// declared-but-inert shape every other `:politicas` cap arm
4552/// closes ([`POLICY_RETRIES_MAX`] thundering-herd amplification,
4553/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] no-op-breaker, etc.).
4554///
4555/// The `1_000_000` (1M) ceiling sits two-to-three orders of magnitude
4556/// above every documented upstream production-playbook recommendation
4557/// band (Envoy `local_rate_limit` typical `10..=10_000` RPS, Istio
4558/// `RateLimitFilter` typical `10..=10_000` RPS, Cloudflare WAF
4559/// rate-rule Free / Pro `10_000` req/min, AWS API Gateway account
4560/// default `10_000` RPS, Kong typical `100..=10_000`, NGINX
4561/// `limit_req_zone` typical `1..=1_000` RPS) and below the
4562/// clearly-pathological "paste-from-binary blob" floor (`100_000_000`,
4563/// `u32::MAX`): a value the author can plausibly want at hyperscale
4564/// (Cloudflare Enterprise rate-plans run to ~6M/min ≈ 1M/h on the
4565/// /h-window arm), but a hard wall above which the policy is
4566/// structurally a no-op carried verbatim on every emitted Envoy /
4567/// Cilium L7 overlay. The cap brackets all three canonical windows
4568/// the [`rate_limit_codec`] accepts: at `1M/s` (absurd hyperscale
4569/// ceiling, ~1M RPS per edge), at `1M/m` (~16.7k RPS, the
4570/// hyperscale-tier WAF band), at `1M/h` (~277 RPS, the common
4571/// per-endpoint API band). Lifted as a typed `pub const` so the bound
4572/// has exactly one source of truth — the future M4
4573/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
4574/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
4575/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
4576/// one place. Same shape every other typed upper bound in this crate
4577/// carries ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
4578/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
4579/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4580/// [`crate::LIMITS_WALL_CLOCK_MAX`],
4581/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4582/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4583pub const POLICY_RATE_LIMIT_MAX: u32 = 1_000_000;
4584
4585// `:entrada :host` total-length and per-label cap axes route through
4586// the lifted [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] (253) and
4587// [`crate::render::DNS_1123_LABEL_MAX_LEN`] (63) canonical bounds. The
4588// pair of aplicacao-private aliases the previous `validate_entrada_host`
4589// arms consumed (`ENTRADA_HOST_MAX_LEN = 253`, `ENTRADA_HOST_LABEL_MAX_LEN
4590// = 63`) were structurally the same K8s Gateway API v1 Hostname
4591// admission-schema bounds — the total-length cap on the OpenAPI
4592// `Hostname` type and the per-`.`-separated-label DNS-1123 cap on the
4593// same regex — that the peer axes at the caixa-core::render level pin,
4594// so hoisting both readers onto the shared lifted constants closes the
4595// third-occurrence duplication threshold structurally: the M4
4596// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-host / per-
4597// label validator, the future per-`Certificate` SAN emitter, and every
4598// other per-Gateway-API-Hostname landing site reach the same one place
4599// as the `:entrada :host` gate does — no per-axis alias drift surface
4600// between them, by construction.
4601
4602/// Max byte length for an Akka-cluster-sharding `:placement :shard-key`
4603/// extractor expression — the upper bound `validate_placement_shard_key`
4604/// enforces on every well-shaped shard-key past validate. The realistic
4605/// shard-key forms in the wild (`tenantId`, `customerId`, `$tenantId`,
4606/// `metadata.tenantId`, `${tenant}`, `$.user.id`) all sit well under 64
4607/// bytes; the 63-byte cap mirrors the DNS-1123 label cap on the peer
4608/// `:placement :affinity` / `:placement :clusters` identifier-shaped
4609/// axes and surfaces the canonical "paste-from-doc multi-line blob landed
4610/// in `:shard-key`" footgun at validate time rather than at the future
4611/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass.
4612const PLACEMENT_SHARD_KEY_MAX_LEN: usize = 63;
4613
4614/// Reject `:membros :caixa` values the K8s apiserver would refuse at
4615/// admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
4616/// that maps the shared parser-shaped reason into the
4617/// [`AplicacaoError::MembroCaixaInvalid`] variant, so the diagnostic
4618/// is self-locating (the offending `caixa:` is named verbatim) and
4619/// the author can grep their caixa.lisp for `:caixa "<name>"` and
4620/// fix it in one edit. Same diagnostic shape as
4621/// [`AplicacaoError::EntradaHostInvalid`] (c7d05ec) and
4622/// [`AplicacaoError::MembroVersaoInvalid`] (9888b13).
4623fn validate_membro_caixa(caixa: &str) -> Result<(), AplicacaoError> {
4624    // Empty is already gated by `MembroCaixaEmpty` at the call site;
4625    // re-checking here keeps the predicate usable from any future
4626    // call site (the M4 CR materializer) without an empty-check
4627    // footgun. The shared
4628    // [`crate::render::require_valid_dns_1123_label`] helper brackets
4629    // the empty-first + shape cascade every peer name axis
4630    // (`:placement :clusters`, `:placement :affinity`, `:contratos
4631    // :de`/`:para`, `:entrada :para`, `:children :caixa`, `:nome`,
4632    // `:upgrade-from :module`) routes through, so drift between the
4633    // eight axes' accepted DNS-1123-label sets is structurally
4634    // impossible.
4635    crate::render::require_valid_dns_1123_label(
4636        caixa,
4637        || AplicacaoError::MembroCaixaEmpty,
4638        |reason| AplicacaoError::membro_caixa_invalid(caixa, reason),
4639    )
4640}
4641
4642/// Reject `:placement :clusters` entries the K8s apiserver would refuse
4643/// at admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
4644/// that maps the shared parser-shaped reason into the
4645/// [`AplicacaoError::PlacementClusterInvalid`] variant.
4646///
4647/// Cluster names land in DNS-1123-label territory across every consumer:
4648/// the K8s context name keying `kubeconfig`, the `clusters[]` filter
4649/// the `lareira-fleet-programs` aggregator applies to scope programs to
4650/// their owning cluster (caixa-mesh's `placement.clusters` overlay,
4651/// 4d91c0b), the namespace prefix the future cross-cluster fan-out
4652/// emits per entry, and the `cluster.x-k8s.io/v1beta1/Cluster.metadata.name`
4653/// cluster identity the M4 CR materializer round-trips. Each apiserver-
4654/// side schema enforces the DNS-1123 label rule on admission; a
4655/// structurally invalid cluster name (`"Rio"`, `"my_cluster"`,
4656/// `"team.rio"`, `"-rio"`, `"rio-"`, the >63-byte UUID-shaped
4657/// mistaken-identity slug) silently passes the prior empty-/duplicate-
4658/// only gate and the failure surfaces as a no-match at filter time —
4659/// the workload doesn't land in the named cluster, with no diagnostic
4660/// naming the offending `:clusters` entry. Lifting the gate to caixa-
4661/// build time mirrors the `:membros :caixa` value-shape trajectory
4662/// (3f9d7a0) on the peer name axis.
4663///
4664/// The diagnostic carries the offending `cluster:` verbatim plus a
4665/// parser-shaped `reason:` naming the specific violation, so the
4666/// author can grep their caixa.lisp for `:clusters` and fix it in
4667/// one edit. Same diagnostic shape as
4668/// [`AplicacaoError::MembroCaixaInvalid`] (3f9d7a0).
4669fn validate_placement_cluster(cluster: &str) -> Result<(), AplicacaoError> {
4670    // Empty is already gated by `PlacementClusterEmpty` at the call
4671    // site; re-checking here keeps the predicate usable from any
4672    // future call site (the M4 CR materializer's per-cluster validator)
4673    // without an empty-check footgun. Routes through the shared
4674    // [`crate::render::require_valid_dns_1123_label`] gate the peer
4675    // name axes each land on.
4676    crate::render::require_valid_dns_1123_label(
4677        cluster,
4678        || AplicacaoError::PlacementClusterEmpty,
4679        |reason| AplicacaoError::placement_cluster_invalid(cluster, reason),
4680    )
4681}
4682
4683/// Reject `:placement :affinity` hints whose shape can never legitimately
4684/// land in any downstream selector or label-keyed routing axis. Thin
4685/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
4686/// shared parser-shaped reason into the
4687/// [`AplicacaoError::PlacementAffinityInvalid`] variant, so the
4688/// diagnostic is self-locating (the offending `:affinity` is named
4689/// verbatim) and the author can grep their caixa.lisp for
4690/// `:affinity "<hint>"` and fix it in one edit.
4691///
4692/// The `:affinity` slot carries a placement-engine hint — canonical
4693/// examples in the M3 surface are `"data-locality"`, `"low-latency"`,
4694/// `"anti-affinity"` — that flows verbatim into the M3 Adaptive
4695/// compression overlay and the future M4 placement-engine's per-hint
4696/// routing axis. Each downstream consumer (caixa-mesh's
4697/// `placement.affinity` overlay at caixa-mesh/src/lib.rs:126, the
4698/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4699/// `spec.placement.affinity` admission rule, the future M4 per-hint
4700/// node-affinity / pod-affinity rule generator keying off the same
4701/// value as a K8s `app.pleme.io/affinity-hint=<value>` label
4702/// selector) requires the value to be a DNS-1123 label — K8s label
4703/// values are bounded by `[a-z0-9A-Z_.-]{,63}` with a stricter
4704/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?` floor in every identity-keyed
4705/// admission rule the apiserver enforces.
4706///
4707/// Until this gate landed an `:affinity "DataLocality"` (the canonical
4708/// TitleCase-from-an-ADR typo), `:affinity "data_locality"` (the
4709/// Python-module-name leak), `:affinity "data.locality"` (the
4710/// namespace-dot-on-a-label confusion), `:affinity "-data-locality"` /
4711/// `:affinity "data-locality-"` (boundary-hyphen violation),
4712/// `:affinity "data locality"` (paste-from-doc whitespace),
4713/// `:affinity "data-localité"` (un-Punycode-encoded IDN), or the
4714/// 64-byte over-cap slug silently passed the empty-only check and the
4715/// failure surfaced as a no-match at the M3 Adaptive compression
4716/// overlay's filter time (`placement.affinity` carried a malformed
4717/// value, no node matched, the workload landed on the default
4718/// heuristic) — the canonical "declared-but-inert" footgun mirroring
4719/// the empty-:affinity / empty-shard-key / zero-:politicas /
4720/// empty-:contratos-target gates already close on every other
4721/// declare-but-no-opinion axis. Lifting the rejection to a build-time
4722/// gate closes the fifth typed slot on the Aplicacao surface to land
4723/// on the canonical DNS-1123 label floor (after the four Servico-name
4724/// reference axes: `:membros :caixa` 3f9d7a0, `:placement :clusters`
4725/// 6c8c00b, `:contratos :de`/`:para` 8d5af6b, `:entrada :para`
4726/// b0e8748).
4727///
4728/// Same diagnostic shape as [`AplicacaoError::PlacementClusterInvalid`]
4729/// (6c8c00b) on the sibling `:placement :clusters` axis — both axes'
4730/// validated values are guaranteed-accepted by the apiserver without
4731/// re-validation at any downstream renderer or admission layer.
4732fn validate_placement_affinity(affinity: &str) -> Result<(), AplicacaoError> {
4733    // Empty is gated separately at the call site for a self-locating
4734    // diagnostic; re-checking here keeps the predicate usable from any
4735    // future call site (the M4 CR materializer's per-affinity
4736    // validator) without an empty-check footgun. Routes through the
4737    // shared [`crate::render::require_valid_dns_1123_label`] gate the
4738    // peer name axes each land on.
4739    crate::render::require_valid_dns_1123_label(
4740        affinity,
4741        || AplicacaoError::PlacementAffinityEmpty,
4742        |reason| AplicacaoError::placement_affinity_invalid(affinity, reason),
4743    )
4744}
4745
4746/// Reject `:placement :shard-key` extractor expressions whose shape can
4747/// never legitimately drive the future M4 Akka-style cluster-sharding
4748/// reconciler's hash-extractor pass. Maps the per-byte / length checks
4749/// into the [`AplicacaoError::ShardKeyInvalid`] variant, so the
4750/// diagnostic is self-locating (the offending `:shard-key` value is
4751/// named verbatim alongside the parser-shaped reason) and the author can
4752/// grep their caixa.lisp for `:shard-key "<expr>"` and fix it in one
4753/// edit.
4754///
4755/// The `:shard-key` slot is the Akka-cluster-sharding `ExtractEntityId`
4756/// axis (MESH-COMPOSITION §II.4) — a single-token entity-id extractor
4757/// expression naming the message property to hash on. The realistic
4758/// shapes in the wild (`tenantId` / `customerId` / `userId` — bare
4759/// property name; `$tenantId` — Akka entity-id placeholder;
4760/// `metadata.tenantId` / `$.user.id` — JSONPath-style nested reference;
4761/// `${tenant}` — interpolation-style template) all sit in the printable
4762/// ASCII subset; the realistic *non-shapes* (a paste-from-doc
4763/// multi-line blob landing in `:shard-key`, an embedded space from a
4764/// paste-from-aligned-doc, a trailing newline from a paste-from-shell
4765/// heredoc, a non-ASCII byte from a paste-from-Unicode-doc, the
4766/// `:shard-key "tenant Id"` typo) silently passed the prior empty-only
4767/// check and the failure surfaces at the future M4 reconciler's hash
4768/// pass as a runtime extractor-evaluation error far from the source
4769/// `caixa.lisp`, with no field naming which member's `:shard-key`
4770/// carried the offending value.
4771///
4772/// The contract — the printable ASCII single-token intersection-floor
4773/// every Akka-style entity-id extractor implementation admits:
4774///
4775///   - 1..=[`PLACEMENT_SHARD_KEY_MAX_LEN`] (63) bytes — same cap as the
4776///     peer DNS-1123-label-shaped `:placement :affinity` /
4777///     `:placement :clusters` identifier axes; realistic shard-keys sit
4778///     well under 32 bytes, the cap surfaces paste-from-doc multi-line
4779///     blob footguns at validate time;
4780///   - every byte in the printable ASCII range `0x21..=0x7E` —
4781///     rejects whitespace (space, tab, CR, LF — `"$tenant Id"` /
4782///     `"$tenantId\n"` from paste-from-aligned-doc /
4783///     paste-from-shell-heredoc), control characters (`\x00..\x1F`,
4784///     `\x7F` — the canonical "embedded null from a copy-paste-binary
4785///     footgun"), and non-ASCII bytes (`"$tenàntId"` —
4786///     un-Punycode-encoded IDN that round-trips inconsistently across
4787///     NFC/NFD normalization).
4788///
4789/// The accepted set is broader than the DNS-1123 label floor the peer
4790/// `:placement :clusters` / `:placement :affinity` axes use because the
4791/// `:shard-key` value is not a K8s `metadata.name` / label-selector
4792/// landing site; it's an extractor expression the future Akka-style
4793/// reconciler reads as a property reference. The realistic forms
4794/// (`$tenantId`, `metadata.tenantId`, `${tenant}`, `$.user.id`) carry
4795/// `$` / `.` / `{` / `}` characters that the DNS-1123 grammar forbids
4796/// but every Akka-style entity-id extractor parses. The
4797/// printable-ASCII-token floor accepts every shape any such extractor
4798/// would accept while rejecting the cross-implementation footguns
4799/// (whitespace breaks token boundaries; non-ASCII round-trips
4800/// inconsistently across YAML emitters and NFC/NFD normalization;
4801/// control characters silently corrupt the next read).
4802///
4803/// Until this gate landed `validate_placement` only refused the
4804/// `Some("")` empty arm via [`AplicacaoError::ShardedKeyEmpty`]; a
4805/// structurally invalid `:shard-key` (`":shard-key \" $tenantId\""` —
4806/// leading space from paste-from-aligned-doc, `":shard-key \"$tenant
4807/// Id\""` — embedded space, `":shard-key \"$tenantId\\n\""` — trailing
4808/// newline from paste-from-shell-heredoc, `":shard-key \"$tenàntId\""`
4809/// — un-Punycode-encoded IDN, `":shard-key \"$tenantId\\x01\""` —
4810/// control character from paste-from-binary, the 64-byte over-cap
4811/// paste-from-doc multi-line slug) silently passed validate. The future
4812/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass
4813/// would then surface the malformed value either as a runtime
4814/// extractor-evaluation error (whitespace breaks the extractor's token
4815/// boundary, no match) or as a silently-different shard assignment
4816/// across YAML emitters (non-ASCII normalizes differently between the
4817/// caixa-mesh-side YAML emitter and the in-cluster reconciler's YAML
4818/// parser, the same entity ID maps to two distinct shards on a
4819/// re-render). Lifting the shape gate to caixa-build time makes the
4820/// extractor-floor invariant a structural property of every validated
4821/// `Placement`: every `Sharded` placement past `validate_placement` has
4822/// a `:shard-key` the future M4 reconciler can hash without
4823/// re-validating at the runtime layer.
4824///
4825/// Mirrors the [`AplicacaoError::ContratoSlotInvalid`] /
4826/// [`AplicacaoError::ContratoSubjectInvalid`] /
4827/// [`AplicacaoError::ContratoEndpointInvalid`] payload-axis shape gates
4828/// on the peer `:contratos` payload axes — each lifts the
4829/// runtime-side parser's intersection-floor to a caixa-build-time gate,
4830/// closing the canonical "this passed validate but the runtime parser
4831/// rejected it" surprise.
4832fn validate_placement_shard_key(key: &str) -> Result<(), AplicacaoError> {
4833    // Empty is gated separately at the call site via the more
4834    // self-locating [`AplicacaoError::ShardedKeyEmpty`] diagnostic;
4835    // re-checking here keeps the predicate usable from any future call
4836    // site (the M4 CR materializer's per-shard-key validator) without
4837    // an empty-check footgun.
4838    if key.is_empty() {
4839        return Err(AplicacaoError::ShardedKeyEmpty);
4840    }
4841    if key.len() > PLACEMENT_SHARD_KEY_MAX_LEN {
4842        return Err(AplicacaoError::shard_key_invalid(
4843            key,
4844            format!(
4845                "exceeds :shard-key max length of {PLACEMENT_SHARD_KEY_MAX_LEN} bytes \
4846                 (got {} bytes; realistic Akka-style entity-id extractor expressions \
4847                 — `tenantId`, `$tenantId`, `metadata.tenantId`, `${{tenant}}` — sit \
4848                 well under 32 bytes, this length suggests a paste-from-doc \
4849                 multi-line blob landed in `:shard-key` instead of a single-token \
4850                 extractor expression)",
4851                key.len()
4852            ),
4853        ));
4854    }
4855    for &b in key.as_bytes() {
4856        if (0x21..=0x7E).contains(&b) {
4857            continue;
4858        }
4859        let reason = if b == b' ' {
4860            "contains a space (Akka-style entity-id extractor expressions are \
4861             single-token references like `tenantId` / `$tenantId` / `metadata.tenantId`; \
4862             whitespace breaks the extractor's token boundary at the runtime layer, \
4863             and the paste-from-aligned-doc / paste-from-CSV footgun silently lands \
4864             a multi-token blob in one `:shard-key` slot)"
4865                .to_string()
4866        } else if b == b'\t' {
4867            "contains a tab character (paste-from-aligned-doc footgun; the \
4868             Akka-style entity-id extractor reads `:shard-key` as a single-token \
4869             reference, embedded whitespace breaks the token boundary at the \
4870             runtime hash-extractor pass)"
4871                .to_string()
4872        } else if b == b'\n' || b == b'\r' {
4873            format!(
4874                "contains line terminator 0x{b:02x} (paste-from-shell-heredoc / \
4875                 paste-from-multiline-doc footgun; the Akka-style entity-id \
4876                 extractor reads `:shard-key` as a single-token reference, embedded \
4877                 newlines either truncate the value at the YAML emitter layer or \
4878                 break the token boundary at the runtime hash-extractor pass)"
4879            )
4880        } else if b < 0x20 || b == 0x7F {
4881            format!(
4882                "contains control character 0x{b:02x} (the canonical \
4883                 paste-from-binary / paste-from-screen-cleared-terminal footgun; \
4884                 control characters silently corrupt round-trip serialization \
4885                 across YAML emitters and break the runtime hash-extractor's \
4886                 single-token parser)"
4887            )
4888        } else {
4889            format!(
4890                "contains non-ASCII byte 0x{b:02x} (the canonical \
4891                 paste-from-Unicode-doc footgun; non-ASCII bytes round-trip \
4892                 inconsistently across NFC/NFD normalization on APFS / ext4 / \
4893                 across YAML emitter implementations — the same entity ID can \
4894                 silently map to two distinct shards on a re-render. Use a \
4895                 printable-ASCII extractor expression like `tenantId`, \
4896                 `$tenantId`, or `metadata.tenantId`)"
4897            )
4898        };
4899        return Err(AplicacaoError::shard_key_invalid(key, reason));
4900    }
4901    Ok(())
4902}
4903
4904/// Reject `:contratos :de` / `:contratos :para` values whose shape
4905/// can never legitimately match a validated `:membros :caixa`. Thin
4906/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
4907/// shared parser-shaped reason into the
4908/// [`AplicacaoError::ContratoCaixaInvalid`] variant, so the per-edge
4909/// diagnostic is self-locating (which slot — `:de` or `:para` — and
4910/// the offending value verbatim) and the author can grep their
4911/// caixa.lisp for `:de "<name>"` / `:para "<name>"` and fix it in
4912/// one edit.
4913///
4914/// Until this gate landed an empty or DNS-1123-malformed `:de` /
4915/// `:para` (`:de ""`, `:de "Cart"` the canonical TitleCase-from-an-ADR
4916/// typo, `:de "my_cart"` the Python-module-name leak, `:de "team.cart"`
4917/// the namespace-dot-on-a-label confusion, `:de "-cart"` / `:de "cart-"`
4918/// the boundary-hyphen violation, the 64-byte over-cap slug, `:de "café"`
4919/// un-Punycode-encoded IDN) silently passed the per-axis check and
4920/// surfaced as [`AplicacaoError::ContratoMemberMissing`] at the
4921/// membership lookup — diagnostic-framed as "this caixa is not in
4922/// `:membros`" when the root cause is "this `:de` value is not a
4923/// well-shaped Servico-name identifier and could never legitimately
4924/// match any validated member". Because every `:membros :caixa` is
4925/// shape-validated through [`validate_membro_caixa`] (3f9d7a0), the
4926/// `names` HashSet structurally never contains an empty / malformed
4927/// string, so the membership lookup arm misframes every empty /
4928/// malformed input. Lifting the shape arm ahead of the lookup
4929/// preserves the legitimate `ContratoMemberMissing` arm (a
4930/// well-shaped `:de` that simply isn't in `:membros` — a phantom
4931/// reference) while routing every structurally-impossible-to-match
4932/// input through the narrower self-locating shape diagnostic.
4933///
4934/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
4935/// (3f9d7a0) and [`AplicacaoError::PlacementClusterInvalid`]
4936/// (6c8c00b) — the third Aplicacao-level Servico-name reference axis
4937/// to land on the canonical [`crate::render::is_dns_1123_label`]
4938/// floor. The `slot: &'static str` field carries the kebab-case
4939/// `:de` / `:para` tag verbatim, mirroring [`BehaviorSpec::validate`]'s
4940/// per-callback-slot diagnostic shape and the
4941/// [`ManifestError::CodePathDuplicate`] (e113ace) / [`DepError::DepIsSelf`]
4942/// (85f102c) cross-list-tag pattern.
4943fn validate_contrato_caixa(slot: &'static str, caixa: &str) -> Result<(), AplicacaoError> {
4944    // Routes through the shared
4945    // [`crate::render::require_valid_dns_1123_label`] gate the peer
4946    // name axes each land on. The `slot: &'static str` field flows
4947    // through both error variants so the diagnostic names which
4948    // per-edge axis (`:de` vs `:para`) the offending value came from.
4949    crate::render::require_valid_dns_1123_label(
4950        caixa,
4951        || AplicacaoError::ContratoCaixaEmpty { slot },
4952        |reason| AplicacaoError::ContratoCaixaInvalid {
4953            slot,
4954            caixa: caixa.to_string(),
4955            reason,
4956        },
4957    )
4958}
4959
4960/// Reject `:entrada :para` values whose shape can never legitimately
4961/// match a validated `:membros :caixa`. Thin wrapper around
4962/// [`crate::render::is_dns_1123_label`] that maps the shared parser-
4963/// shaped reason into the [`AplicacaoError::EntradaParaInvalid`]
4964/// variant, so the diagnostic is self-locating (the offending
4965/// `:entrada :para` value is named verbatim) and the author can grep
4966/// their caixa.lisp for `:para "<name>"` and fix it in one edit.
4967///
4968/// Until this gate landed an empty or DNS-1123-malformed `:entrada
4969/// :para` (`:para ""`, `:para "Cart"` the canonical TitleCase-from-an-
4970/// ADR typo, `:para "my_cart"` the Python-module-name leak,
4971/// `:para "team.cart"` the namespace-dot-on-a-label confusion,
4972/// `:para "-cart"` / `:para "cart-"` the boundary-hyphen violation,
4973/// the 64-byte over-cap slug, `:para "café"` un-Punycode-encoded IDN)
4974/// silently passed the per-axis check and surfaced as
4975/// [`AplicacaoError::EntradaMemberMissing`] at the membership lookup
4976/// — diagnostic-framed as "this caixa is not in `:membros`" when the
4977/// root cause is "this `:entrada :para` value is not a well-shaped
4978/// Servico-name identifier and could never legitimately match any
4979/// validated member". Because every `:membros :caixa` is shape-
4980/// validated through [`validate_membro_caixa`] (3f9d7a0), the `names`
4981/// `HashSet` structurally never contains an empty / malformed string,
4982/// so the membership lookup arm misframes every empty / malformed
4983/// input. Lifting the shape arm ahead of the lookup preserves the
4984/// legitimate `EntradaMemberMissing` arm (a well-shaped `:para` that
4985/// simply isn't in `:membros` — a phantom reference) while routing
4986/// every structurally-impossible-to-match input through the narrower
4987/// self-locating shape diagnostic.
4988///
4989/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
4990/// (3f9d7a0), [`AplicacaoError::PlacementClusterInvalid`] (6c8c00b),
4991/// and [`AplicacaoError::ContratoCaixaInvalid`] (8d5af6b) — the
4992/// fourth and last Aplicacao-level Servico-name reference axis to
4993/// land on the canonical [`crate::render::is_dns_1123_label`] floor.
4994/// No `slot: &'static str` field because there is only one axis
4995/// (`:entrada :para`), unlike the dual-axis `:contratos :de`/`:para`;
4996/// the simpler shape mirrors [`validate_membro_caixa`] and
4997/// [`validate_placement_cluster`].
4998fn validate_entrada_para(para: &str) -> Result<(), AplicacaoError> {
4999    // Empty is gated separately at the call site for a self-locating
5000    // diagnostic; re-checking here keeps the predicate usable from any
5001    // future call site (the M4 CR materializer's per-`:entrada`
5002    // validator) without an empty-check footgun. Routes through the
5003    // shared [`crate::render::require_valid_dns_1123_label`] gate the
5004    // peer name axes each land on.
5005    crate::render::require_valid_dns_1123_label(
5006        para,
5007        || AplicacaoError::EntradaParaEmpty,
5008        |reason| AplicacaoError::entrada_para_invalid(para, reason),
5009    )
5010}
5011
5012/// Reject `:entrada :host` values the K8s Gateway API v1 apiserver
5013/// would refuse at admission time. The contract — exactly the regex
5014/// the Gateway API CRD's OpenAPI schema enforces on `Listener.hostname`
5015/// and `HTTPRoute.spec.hostnames[]`,
5016/// `^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
5017/// (max length 253; per-label max length 63):
5018///
5019///   - lowercase RFC 1123 DNS subdomain (`[a-z0-9-]` only; no
5020///     uppercase, no underscore, no Unicode/IDN — IDN must be
5021///     pre-encoded as Punycode `xn--…` by the author);
5022///   - exactly one optional leading wildcard label (`*.`); a wildcard
5023///     in any non-leading label position is rejected;
5024///   - each `.`-separated label is 1..=63 bytes, with non-hyphen
5025///     alphanumeric at both boundaries (no `-foo`, no `foo-`);
5026///   - total length 1..=253 bytes;
5027///   - no IPv4 literal (Gateway API forbids IP literals);
5028///   - no scheme (`https://`, `http://`), no port (`:8080`), no
5029///     whitespace, no path (`/`).
5030///
5031/// Lifted as a typed gate (rather than an inline cascade in
5032/// `validate()`) so the contract lives in one place — every future
5033/// per-host axis (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5034/// materializer's host validator, the future per-`:entrada` SAN
5035/// emission for cert-manager Certificates, the multi-`:entrada`
5036/// host-collision gate when M4 lands `:entrada` as a `Vec`) reaches
5037/// for the same predicate, not its own. Same compounding shape as
5038/// `is_canonical_rate_limit_window` (808017c) and
5039/// [`WitTarget::label`] (previously the free `contrato_target_label`
5040/// helper, 5dbcfaf; lifted onto the typed [`WitTarget`] enum so the
5041/// per-variant label match is compiler-checked-exhaustive).
5042///
5043/// The diagnostic carries the offending `host:` verbatim plus a
5044/// parser-shaped `reason:` naming the specific violation, so the
5045/// author can grep their caixa.lisp for `:host "<host>"` and fix it
5046/// in one edit. Same diagnostic shape as `MembroVersaoInvalid`
5047/// (9888b13).
5048fn validate_entrada_host(host: &str) -> Result<(), AplicacaoError> {
5049    // Empty is already gated by `EmptyEntradaHost` at the call site;
5050    // re-checking here keeps the predicate usable from any future
5051    // call site (M4 CR materializer) without an empty-check footgun.
5052    if host.is_empty() {
5053        return Err(AplicacaoError::EmptyEntradaHost);
5054    }
5055    if host.len() > crate::render::GATEWAY_API_HOSTNAME_MAX_LEN {
5056        return Err(AplicacaoError::entrada_host_invalid(
5057            host,
5058            format!(
5059                "exceeds Gateway API v1 Hostname max length of {cap} bytes \
5060                 (got {} bytes; the K8s apiserver rejects longer hostnames at admission time)",
5061                host.len(),
5062                cap = crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
5063            ),
5064        ));
5065    }
5066    if host.contains("://") {
5067        return Err(AplicacaoError::entrada_host_invalid(
5068            host,
5069            "must not carry a scheme (drop the `https://` or `http://` prefix; \
5070             Gateway API takes the bare hostname)",
5071        ));
5072    }
5073    if host.contains('/') {
5074        return Err(AplicacaoError::entrada_host_invalid(
5075            host,
5076            "must not carry a path (drop the `/…` suffix; Gateway API path \
5077             matching is in `:entrada :paths`)",
5078        ));
5079    }
5080    // After the `://` scheme-prefix and `/` path arms have ruled out the
5081    // two `:`-bearing shapes the Gateway API actively rejects with
5082    // location-shaped diagnostics, any remaining `:` in the host body is
5083    // either the canonical "I put the port in the `:host` slot"
5084    // authoring footgun (`"checkout.quero.cloud:8080"` — the `:port`
5085    // slot lives one axis away on the same `:entrada` block) or an
5086    // unbracketed IPv6 literal (`"2001:db8::1"`) which Gateway API v1
5087    // Hostname forbids identically to the IPv4-literal arm below. Both
5088    // shapes silently fell through the `://` and `/` arms before this
5089    // lift and surfaced as a deep `label "<rest>:<port>" contains
5090    // invalid character ':'` diagnostic from the per-byte loop near the
5091    // bottom of this predicate, which named the offending byte but not
5092    // the canonical authoring fix — for the port case the author has to
5093    // know the `:entrada` block carries a separate `:port u16` slot
5094    // (`caixa-core/src/aplicacao.rs:1667`, `default_port = 8080`) and
5095    // move the value over; for the IPv6 case the author has to know
5096    // Gateway API v1 forbids IP literals across the board. The contract
5097    // doc-comment above already promises "no port (`:8080`)" verbatim
5098    // in the rejected-shape enumeration but the predicate's
5099    // implementation refused the `:` only as a side-effect of the
5100    // per-label `[a-z0-9-]` character-class loop; this arm brings the
5101    // implementation in line with the documented contract by surfacing
5102    // the canonical fix at the top-level shape gate, peer with how the
5103    // `://` arm names the scheme prefix and the `/` arm names the
5104    // `:entrada :paths` axis. Same compounding trajectory the recent
5105    // `is_gateway_api_http_path` (6a17961) per-byte tightening followed
5106    // — the typed slot's rejected set matches the apiserver's rejected
5107    // set, structurally, with a self-locating diagnostic at the
5108    // offending axis instead of a deep parser-shape leak.
5109    if host.contains(':') {
5110        return Err(AplicacaoError::entrada_host_invalid(
5111            host,
5112            "must not contain `:` (the port belongs in the `:entrada :port` \
5113             slot — a separate `u16` axis on the same `:entrada` block, \
5114             defaulting to 8080 — not in the host body; drop the `:<port>` \
5115             suffix and author the bare hostname. If you intended an IPv6 \
5116             literal (`2001:db8::1` / `::1` / `fe80::1`), Gateway API v1 \
5117             Hostname forbids IP literals identically to the IPv4-literal \
5118             arm — use a DNS name)",
5119        ));
5120    }
5121    // Routed through the lifted [`crate::render::find_ascii_whitespace_byte`]
5122    // predicate — the same single source of truth every peer
5123    // ASCII-whitespace scan in caixa-core flows through: the four
5124    // typed-magnitude codec sites (`limits::parse_byte_size` backing
5125    // `:limits :memory`, `limits::parse_duration` backing `:limits
5126    // :wall-clock`, `limits::parse_millicores` backing `:limits :cpu`,
5127    // `aplicacao::rate_limit_codec::parse` backing `:politicas
5128    // :rate-limit`) and the shared duration codec
5129    // (`supervisor::duration_codec::parse`) backing `:supervisor
5130    // :restart-window` / `:politicas :timeout` / `:politicas
5131    // :circuit-breaker :window`. This landing closes the last string-typed
5132    // slot in caixa-core still calling `.bytes().any(|b|
5133    // b.is_ascii_whitespace())` inline — every ASCII-whitespace scan
5134    // across every typed slot now shares one predicate, so a future
5135    // stricter classification (BOM `\u{FEFF}` / ZWSP `\u{200B}` / ZWJ
5136    // `\u{200D}` — the "invisible but not `char::is_whitespace`" class
5137    // deliberately excluded from the peer non-ASCII predicate) can
5138    // extend at this shared site in one edit rather than seven
5139    // independent scans diverging over time. Naming the offending byte
5140    // in the diagnostic (`0x20` space / `0x09` tab / `0x0a` LF / `0x0c`
5141    // FF / `0x0d` CR) matches the substrate-wide "the diagnostic carries
5142    // the offending byte verbatim" discipline every peer codec site
5143    // already carries (`limits.rs:722` / `limits.rs:784` / `limits.rs:845`
5144    // / `supervisor.rs:823` / `aplicacao.rs:1640`).
5145    if let Some(b) = crate::render::find_ascii_whitespace_byte(host) {
5146        return Err(AplicacaoError::entrada_host_invalid(
5147            host,
5148            format!(
5149                "contains ASCII whitespace byte 0x{b:02x} (Gateway API v1 \
5150                 Hostname is a single-token DNS name — leading, trailing, \
5151                 or embedded whitespace breaks the K8s apiserver's Hostname \
5152                 regex at admission time; the paste-from-aligned-doc / \
5153                 paste-from-shell-history / paste-from-CSV footgun silently \
5154                 lands a multi-token blob in `:entrada :host`. Strip every \
5155                 whitespace byte and author the bare hostname — space \
5156                 `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d` all \
5157                 refuse identically)"
5158            ),
5159        ));
5160    }
5161    // Peer of the ASCII-whitespace scan above: route the non-ASCII
5162    // subset of Unicode `White_Space` through the shared
5163    // [`crate::render::find_non_ascii_whitespace_char`] predicate — the
5164    // single source of truth every peer non-ASCII-whitespace scan in
5165    // caixa-core flows through: `limits::parse_byte_size` (`:limits
5166    // :memory`), `limits::parse_duration` (`:limits :wall-clock`),
5167    // `limits::parse_millicores` (`:limits :cpu`),
5168    // `aplicacao::rate_limit_codec::parse` (`:politicas :rate-limit`),
5169    // and `supervisor::duration_codec::parse` (`:supervisor
5170    // :restart-window` / `:politicas :timeout` / `:politicas
5171    // :circuit-breaker :window`). Before this arm, a NBSP-prefixed host
5172    // (`"\u{00A0}checkout.quero.cloud"` — paste-from-typography), a
5173    // LINE-SEPARATOR-suffixed host (`"checkout.quero.cloud\u{2028}"` —
5174    // paste-from-web-doc), or an EM-SPACE-split host
5175    // (`"checkout.\u{2003}quero.cloud"` — paste-from-typography)
5176    // survived this predicate's ASCII byte-scan (none of the UTF-8
5177    // bytes of `\u{00A0}` / `\u{2028}` / `\u{2003}` match
5178    // `u8::is_ascii_whitespace`), then landed on the per-label
5179    // `bytes[0].is_ascii_alphanumeric()` arm near the bottom of this
5180    // predicate with the generic `label "…" must start and end with an
5181    // alphanumeric` diagnostic — a "far from source at build-time"
5182    // leak that names the label-shape violation but not the
5183    // paste-from-typography origin the author actually needs to fix.
5184    // Peer with the four codec sites the 1b75b38 landing pinned: the
5185    // typed slot's diagnostic axis names the offending codepoint
5186    // (`U+XXXX`) verbatim rather than laundering the value through a
5187    // downstream label-shape arm, so the author can grep their
5188    // caixa.lisp for the invisible codepoint at the surfaced position
5189    // rather than eyeball a multi-byte host for embedded NBSP / LINE
5190    // SEPARATOR / EM-SPACE. Same "single lifted source of truth"
5191    // discipline the peer ASCII-whitespace arm (720ac3b) carries:
5192    // drift between any two typed-slot sites' non-ASCII-whitespace
5193    // rejection set becomes a single-edit fix at the shared predicate
5194    // rather than N independent inline scans diverging over time, and
5195    // a future stricter classification (BOM `\u{FEFF}` / ZWSP
5196    // `\u{200B}` / ZWJ `\u{200D}` — the "invisible but not
5197    // `char::is_whitespace`" class the peer non-ASCII predicate's
5198    // doc-comment names as the follow-up trajectory) extends at the
5199    // shared predicate in one edit rather than seven.
5200    if let Some(ch) = crate::render::find_non_ascii_whitespace_char(host) {
5201        return Err(AplicacaoError::entrada_host_invalid(
5202            host,
5203            format!(
5204                "contains non-ASCII Unicode whitespace character {ch:?} \
5205                 (U+{codepoint:04X}) — Gateway API v1 Hostname is a \
5206                 single-token DNS name limited to `[a-z0-9-]` labels; \
5207                 the paste-from-typography footgun silently lands an \
5208                 invisible codepoint (NBSP `U+00A0`, LINE SEPARATOR \
5209                 `U+2028`, EM-SPACE `U+2003`, IDEOGRAPHIC SPACE \
5210                 `U+3000`, and every other member of the Unicode \
5211                 `White_Space` property outside the ASCII byte range) \
5212                 in `:entrada :host`, which the K8s apiserver's \
5213                 Hostname regex refuses at admission time far from the \
5214                 caixa.lisp source line. Strip every non-ASCII \
5215                 whitespace character and author the bare hostname \
5216                 with only ASCII bytes (write \"checkout.quero.cloud\" \
5217                 verbatim)",
5218                codepoint = ch as u32,
5219            ),
5220        ));
5221    }
5222
5223    // Strip the optional single leading wildcard label *before* the
5224    // trailing-dot check so the bare `"*."` form surfaces the more
5225    // self-locating "wildcard without domain" diagnostic instead of
5226    // the generic "trailing dot" one.
5227    let (had_wildcard, rest) = match host.strip_prefix("*.") {
5228        Some(r) => (true, r),
5229        None => (false, host),
5230    };
5231    if had_wildcard && rest.is_empty() {
5232        return Err(AplicacaoError::entrada_host_invalid(
5233            host,
5234            "wildcard `*.` must be followed by a domain (e.g. `*.example.com`)",
5235        ));
5236    }
5237    if rest.contains('*') {
5238        return Err(AplicacaoError::entrada_host_invalid(
5239            host,
5240            "wildcard `*` is allowed only as the first label (`*.example.com`); \
5241             no inner or trailing `*` labels",
5242        ));
5243    }
5244    if rest.ends_with('.') {
5245        return Err(AplicacaoError::entrada_host_invalid(
5246            host,
5247            "must not have a trailing `.` (Gateway API hostnames are not \
5248             fully-qualified with a root dot; the apiserver regex rejects \
5249             trailing dots)",
5250        ));
5251    }
5252
5253    // Reject pure IPv4 literals: four dot-separated labels, every
5254    // label all-ASCII-digits. Gateway API v1 explicitly forbids IP
5255    // literals as Hostnames.
5256    let labels: Vec<&str> = rest.split('.').collect();
5257    if labels.len() == 4
5258        && labels
5259            .iter()
5260            .all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_digit()))
5261    {
5262        return Err(AplicacaoError::entrada_host_invalid(
5263            host,
5264            "must not be an IPv4 literal (Gateway API v1 Hostname forbids IP \
5265             literals; use a DNS name)",
5266        ));
5267    }
5268
5269    // Per-label shape: 1..=63 bytes, lowercase ASCII alphanumeric +
5270    // hyphen, with non-hyphen at both boundaries.
5271    for label in &labels {
5272        if label.is_empty() {
5273            return Err(AplicacaoError::entrada_host_invalid(
5274                host,
5275                "has an empty label (consecutive `..` or a leading `.`)",
5276            ));
5277        }
5278        if label.len() > crate::render::DNS_1123_LABEL_MAX_LEN {
5279            return Err(AplicacaoError::entrada_host_invalid(
5280                host,
5281                format!(
5282                    "label {label:?} exceeds DNS-1123 label max length of \
5283                     {cap} bytes (got {} bytes)",
5284                    label.len(),
5285                    cap = crate::render::DNS_1123_LABEL_MAX_LEN,
5286                ),
5287            ));
5288        }
5289        let bytes = label.as_bytes();
5290        if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
5291            return Err(AplicacaoError::entrada_host_invalid(
5292                host,
5293                format!(
5294                    "label {label:?} must start and end with an alphanumeric \
5295                     (no leading or trailing `-`)"
5296                ),
5297            ));
5298        }
5299        for &b in bytes {
5300            let valid = b.is_ascii_digit() || b.is_ascii_lowercase() || b == b'-';
5301            if !valid {
5302                let msg = if b.is_ascii_uppercase() {
5303                    format!(
5304                        "label {label:?} contains uppercase character {ch:?} \
5305                         (Gateway API hostnames are lowercase-only; use {lower:?})",
5306                        ch = b as char,
5307                        lower = label.to_ascii_lowercase()
5308                    )
5309                } else if b == b'_' {
5310                    format!(
5311                        "label {label:?} contains `_` (Gateway API hostnames \
5312                         allow only `[a-z0-9-]`; use `-` instead)"
5313                    )
5314                } else {
5315                    format!(
5316                        "label {label:?} contains invalid character {ch:?} \
5317                         (Gateway API hostnames allow only `[a-z0-9-]`)",
5318                        ch = b as char
5319                    )
5320                };
5321                return Err(AplicacaoError::entrada_host_invalid(host, msg));
5322            }
5323        }
5324    }
5325    Ok(())
5326}
5327
5328/// Reject `:entrada :paths` entries the K8s Gateway API v1 apiserver
5329/// would refuse at admission time. Thin wrapper around
5330/// [`crate::render::is_gateway_api_http_path`] that maps the shared
5331/// parser-shaped reason into the [`AplicacaoError::EntradaPathInvalid`]
5332/// variant, preserving the more self-locating
5333/// [`AplicacaoError::EntradaPathEmpty`] /
5334/// [`AplicacaoError::EntradaPathNotAbsolute`] diagnostics when the
5335/// path fails those narrower invariants first.
5336///
5337/// The contract is the canonical HTTP-path grammar — `1..=
5338/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`] (1024) bytes,
5339/// leading `/`, no consecutive `/`, no `.`/`..` segments, no `?`/`#`/
5340/// whitespace/control/non-ASCII bytes — shared with the
5341/// `:contratos :endpoint` axis through the lifted predicate so drift
5342/// between either landing site and the K8s apiserver-side
5343/// HTTPPathMatch.value OpenAPI schema is a build error visible at
5344/// the predicate, not a per-renderer "this passed validate but failed
5345/// admission" surprise. The diagnostic carries the offending `path:`
5346/// verbatim plus a parser-shaped `reason:` naming the specific
5347/// violation, so the author can grep their caixa.lisp for `:paths`
5348/// and fix it in one edit. Same diagnostic shape as
5349/// [`AplicacaoError::ContratoEndpointInvalid`] on the peer HTTP-path
5350/// axis.
5351fn validate_entrada_path(path: &str) -> Result<(), AplicacaoError> {
5352    // Empty and missing-leading-`/` are already gated at the call
5353    // site by `EntradaPathEmpty` and `EntradaPathNotAbsolute`; re-
5354    // checking here keeps the per-axis narrower diagnostics in force
5355    // when the predicate is reached directly (and `is_gateway_api_http_path`
5356    // itself defends against `bytes[0]`-style indexing on empty
5357    // input).
5358    if path.is_empty() {
5359        return Err(AplicacaoError::EntradaPathEmpty);
5360    }
5361    if !path.starts_with('/') {
5362        return Err(AplicacaoError::EntradaPathNotAbsolute {
5363            path: path.to_string(),
5364        });
5365    }
5366    crate::render::is_gateway_api_http_path(path)
5367        .map_err(|reason| AplicacaoError::entrada_path_invalid(path, reason))
5368}
5369
5370mod rate_limit_codec {
5371    // `Duration` is no longer named here — the codec routes through
5372    // the substrate primitive [`super::RateLimitUnit::window_from_suffix`]
5373    // (parse arm, `&str → Duration`) and [`super::RateLimit::canonical_unit`]
5374    // (render arm, `Duration → RateLimitUnit`) typed dispatches that carry
5375    // the canonical `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection on the
5376    // closed-set enum's arm-table rather than through vestigial free-helper
5377    // delegates.
5378    use super::{RateLimit, RateLimitUnit};
5379    use serde::{Deserializer, Serializer};
5380
5381    pub fn serialize<S: Serializer>(v: &Option<RateLimit>, s: S) -> Result<S::Ok, S::Error> {
5382        // Route through the canonical [`crate::render::serialize_option_via_str`]
5383        // — the substrate-side single-owner primitive for the forward
5384        // arm of the typed-magnitude codec family. See its docstring
5385        // for the full sibling roster.
5386        crate::render::serialize_option_via_str(v, s, render)
5387    }
5388
5389    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RateLimit>, D::Error> {
5390        // Route through the canonical [`crate::render::deserialize_option_via_str`]
5391        // — the substrate-side single-owner primitive for the reverse
5392        // arm of the typed-magnitude codec family. See its docstring
5393        // for the full sibling roster.
5394        crate::render::deserialize_option_via_str(d, parse)
5395    }
5396
5397    fn parse(s: &str) -> Result<RateLimit, String> {
5398        // Paired whitespace-rejection arm — same canonical-form
5399        // render-determinism discipline as the peer
5400        // `limits::parse_byte_size` / `limits::parse_duration` /
5401        // `limits::parse_millicores` /
5402        // `supervisor::duration_codec::parse` sites: the ASCII
5403        // byte-scan closes the WhatWG-conformant whitespace bytes
5404        // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
5405        // `char::is_whitespace` scan closes the strictly-complementary
5406        // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
5407        // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
5408        // codepoints) that `str::trim` at parse entry silently strips.
5409        // Either drift class would round-trip through `render` to a
5410        // *different* canonical form on next emit — breaking the
5411        // THEORY.md Part V render-determinism contract on
5412        // `:politicas :rate-limit`.
5413        //
5414        // Routed through the lifted [`crate::render::reject_whitespace`]
5415        // primitive — the substrate-side single-owner paired-arm gate
5416        // every typed-magnitude codec in caixa-core shares.
5417        crate::render::reject_whitespace::<String, _, _>(
5418            s,
5419            |b| {
5420                format!(
5421                    "rate-limit: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
5422                 authoring form for `:politicas :rate-limit` is `<integer>/<s|m|h>` (e.g. \
5423                 `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) with no whitespace bytes \
5424                 anywhere. A whitespace-carrying shape (`\" 100/s\"`, `\"100/s \"`, \
5425                 `\"100 /s\"`, `\"100/ s\"`, `\"100 / s\"`, `\"100/s\\n\"`, `\"\\t100/s\"`) \
5426                 round-trips through `render` to a *different* canonical form (`\"100/s\"`) \
5427                 on first serialize — breaking the THEORY.md Part V render-determinism \
5428                 contract every typed slot carries. Strip every whitespace byte (write \
5429                 `\"100/s\"` verbatim)"
5430                )
5431            },
5432            |ch| {
5433                format!(
5434                    "rate-limit: value {s:?} contains non-ASCII Unicode whitespace character \
5435                 {ch:?} (U+{cp:04X}) — the canonical authoring form for `:politicas \
5436                 :rate-limit` is `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, \
5437                 `\"10000/h\"`) with no whitespace characters anywhere (ASCII or Unicode). \
5438                 A non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}100/s\"`, \
5439                 `\"100/s\\u{{2028}}\"`, `\"100\\u{{2003}}/s\"`) survives the ASCII \
5440                 byte-scan but `str::trim` (which uses `char::is_whitespace` — the \
5441                 Unicode `White_Space` property, strictly wider than the ASCII byte set) \
5442                 silently strips it at parse entry, and the value round-trips through \
5443                 `render` to a *different* canonical form (`\"100/s\"`) on first \
5444                 serialize — breaking the THEORY.md Part V render-determinism contract \
5445                 every typed slot carries. Strip every non-ASCII whitespace character \
5446                 (write `\"100/s\"` verbatim with only ASCII bytes)",
5447                    cp = ch as u32
5448                )
5449            },
5450        )?;
5451        let s = s.trim();
5452        let (rate_str, unit) = s
5453            .split_once('/')
5454            .ok_or_else(|| format!("rate-limit must be `<n>/<unit>`, got {s:?}"))?;
5455        let rate_trim = rate_str.trim();
5456        // The canonical authoring form for `:politicas :rate-limit` is
5457        // `<integer>/<s|m|h>` — every magnitude [`render`] emits is a
5458        // non-negative integer with no decimal point and no leading
5459        // sign, so the parser's accepted set must match for
5460        // serialize/deserialize to round-trip without canonical-form
5461        // drift. Until this gate landed the parser accepted any
5462        // `u32::from_str`-shaped magnitude — and current Rust
5463        // `u32::from_str` permissively accepts a leading `+` (`"+100"`
5464        // → 100), so `"+100/s"` parsed to `RateLimit { 100, 1s }` and
5465        // serde silently round-tripped to `"100/s"` on the next emit
5466        // (a *different* canonical string) — breaking the THEORY.md
5467        // Part V render-determinism contract on the fifth typed-codec
5468        // surface in caixa-core (peer with the four duration codecs the
5469        // 1c55a2a / 818dd38 / d1fd67b / 737a676 / d53c922 trajectory
5470        // already covered: `supervisor::duration_codec` backing three
5471        // typed-duration slots, `limits::parse_duration` backing
5472        // `:limits :wall-clock`, `limits::parse_byte_size` backing
5473        // `:limits :memory`). The fractional / decimal-shaped sibling
5474        // (`"1.5/s"`, `"1.0/s"`, `"0.5/m"`) lands on `u32::from_str`'s
5475        // existing rejection arm, but the diagnostic is value-laundered
5476        // (the bare `"rate-limit rate \"1.5\" not a u32"` wording
5477        // doesn't name the canonical-form remediation or the round-trip
5478        // drift the next emit would produce); this gate lifts the
5479        // fractional arm onto the same canonical-form diagnostic the
5480        // peer codecs carry.
5481        //
5482        // Strict canonical form: every byte of the magnitude is an
5483        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
5484        // inputs the gate distinguishes "non-canonical-but-numeric"
5485        // (parses as f64 or i64 — surfaced with a self-locating
5486        // diagnostic naming the canonical authoring form and the
5487        // round-trip drift the rejected shape would produce on first
5488        // serialize) from "garbage" (parses as neither — surfaced with
5489        // the existing narrower `"not a u32"` wording so its
5490        // diagnostic shape remains stable for the parser-shape footgun
5491        // case).
5492        //
5493        // Routed through the lifted
5494        // [`crate::render::is_digit_only_magnitude`] predicate — the
5495        // same source of truth the four peer typed-magnitude codec
5496        // sites share.
5497        let digit_only = crate::render::is_digit_only_magnitude(rate_trim);
5498        if !digit_only {
5499            let numeric = rate_trim.parse::<f64>().is_ok() || rate_trim.parse::<i64>().is_ok();
5500            if numeric {
5501                return Err(format!(
5502                    "rate-limit: rate {rate_trim:?} is not a non-negative integer — the \
5503                     canonical authoring form for `:politicas :rate-limit` is \
5504                     `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
5505                     with no decimal point and no leading `+` / `-` sign. A fractional / \
5506                     signed magnitude (`\"1.5/s\"`, `\"+100/s\"`, `\"-1/s\"`) round-trips \
5507                     through `render` to a *different* canonical form (`\"1/s\"`, \
5508                     `\"100/s\"`, parser-reject) on first serialize — breaking the \
5509                     THEORY.md Part V render-determinism contract every typed slot \
5510                     carries. Pick an integer rate that fits the desired window \
5511                     (write `\"6000/m\"` instead of `\"1.66/s\"`)"
5512                ));
5513            }
5514            return Err(format!("rate-limit rate {rate_str:?} not a u32"));
5515        }
5516        // Leading-zero arm — peer with the prior `"+100/s"` arm above
5517        // (4eeae98's predecessor) on the same canonical-form
5518        // render-determinism axis. The digit-only gate accepts
5519        // `"0100/s"`, `"00/s"`, `"007/h"` as `u32::from_str` parses
5520        // them losslessly (= 100, 0, 7), but `render` emits the
5521        // leading-zero-stripped form (`"100/s"`, `"0/s"`, `"7/h"`) —
5522        // a *different* canonical string on the next emit, breaking
5523        // the THEORY.md Part V render-determinism contract the same
5524        // way `"+100/s"` did before the leading-`+` arm landed. The
5525        // single-byte magnitude `"0"` itself round-trips losslessly
5526        // through `render` (`render(0)` emits `"0/s"`) — the
5527        // downstream [`AplicacaoError::PolicyRateLimitZero`] gate is
5528        // what refuses rate-zero authoring, so `"0/s"` stays in the
5529        // accepted set at this codec layer and the diagnostic
5530        // partitioning between canonical-form drift (this arm) and
5531        // semantic-zero (the downstream gate) remains stable.
5532        // Peer with the future leading-zero arms on the three peer
5533        // typed-magnitude codecs the trajectory acknowledges:
5534        // `supervisor::duration_codec`, `limits::parse_duration`,
5535        // `limits::parse_byte_size` — each carries the same
5536        // canonical-form-drift class today; this gate lands the
5537        // discipline on the fourth typed-magnitude codec in
5538        // caixa-core first because the peer `"+100/s"` arm above is
5539        // the closest predecessor on the trajectory.
5540        //
5541        // Routed through the lifted
5542        // [`crate::render::is_leading_zero_padded_magnitude`]
5543        // predicate — the same source of truth the four peer
5544        // typed-magnitude codec sites share.
5545        if crate::render::is_leading_zero_padded_magnitude(rate_trim) {
5546            return Err(format!(
5547                "rate-limit: rate {rate_trim:?} has a non-canonical leading zero — the \
5548                 canonical authoring form for `:politicas :rate-limit` is \
5549                 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
5550                 with no leading-zero padding on the magnitude. A leading-zero magnitude \
5551                 (`\"0100/s\"`, `\"00/s\"`, `\"007/h\"`) round-trips through `render` to \
5552                 a *different* canonical form (`\"100/s\"`, `\"0/s\"`, `\"7/h\"`) on \
5553                 first serialize — breaking the THEORY.md Part V render-determinism \
5554                 contract every typed slot carries. Strip the leading zeros (write \
5555                 `\"100/s\"` instead of `\"0100/s\"`)"
5556            ));
5557        }
5558        // The digit-only gate guarantees every byte is `[0-9]`, and
5559        // the leading-zero arm above guarantees the magnitude is
5560        // either the single byte `"0"` or starts with `[1-9]`, so
5561        // the only way `u32::from_str` can fail here is overflow
5562        // (the magnitude exceeds `u32::MAX`). Surface that with an
5563        // overflow-shaped wording so the diagnostic names the
5564        // offending magnitude verbatim rather than collapsing onto
5565        // the non-canonical arm. Same shape
5566        // `supervisor::duration_codec` (1c55a2a) carries on the peer
5567        // duration-codec axis.
5568        let rate: u32 = rate_trim.parse::<u32>().map_err(|_| {
5569            format!("rate-limit rate {rate_trim:?} (digit-only magnitude overflows u32)")
5570        })?;
5571        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives on
5572        // the closed-set typed enum [`super::RateLimitUnit`]; this parse
5573        // arm reads the `&str → Duration` projection through the
5574        // substrate primitive [`super::RateLimitUnit::window_from_suffix`]
5575        // (a two-step typed dispatch composing [`super::RateLimitUnit::from_suffix`]
5576        // with [`super::RateLimitUnit::window`]) rather than the vestigial
5577        // module-private `rate_limit_window_from_unit` free helper the
5578        // predecessor 61421a6 left as the last unlifted delegate on this
5579        // axis. One typed dispatch on the substrate primitive instead of
5580        // one runtime call through the free-helper delegate; the sole
5581        // production consumer of the `&str → Duration` axis (this parse
5582        // arm) now reaches for exactly one typed method on the closed-set
5583        // enum, sibling to the codec's render arm's
5584        // [`super::RateLimit::canonical_unit`] dispatch on the paired
5585        // `Duration → RateLimitUnit` axis and to the validate gate's
5586        // [`super::RateLimit::canonical_unit`] shape-probe on the
5587        // canonical-window axis. A future rate-limit-unit addition (a
5588        // `"d"` day suffix once Envoy's `rate_limit_action` grows
5589        // daily-bucket support, a `"ms"` sub-second window once
5590        // high-throughput per-edge policies come into scope per
5591        // MESH-COMPOSITION §III.2 #3) is one variant + one arm per method
5592        // on the closed-set enum, and the compiler enforces exhaustiveness
5593        // on every consumer's `match self` arms — this parse arm's
5594        // accepted-suffix set, the render arm's emitted-suffix set, the
5595        // validate gate's canonical-window set, and every future
5596        // per-`:contratos`-edge rate-limit-override overlay all pick it up
5597        // by construction.
5598        let unit = unit.trim();
5599        let window = RateLimitUnit::window_from_suffix(unit)
5600            .ok_or_else(|| format!("unknown rate-limit window unit {unit:?}"))?;
5601        Ok(RateLimit { rate, window })
5602    }
5603
5604    fn render(rl: RateLimit) -> String {
5605        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
5606        // module scope on the closed-set typed enum [`super::RateLimitUnit`];
5607        // this render arm reads the `Duration → RateLimitUnit` projection
5608        // through the substrate primitive [`super::RateLimit::canonical_unit`]
5609        // (returns `None` on every non-canonical window — the sub-second /
5610        // non-`{1, 60, 3600}` shapes the validate gate rejects), then
5611        // formats the returned typed enum through its
5612        // [`std::fmt::Display`] impl (which routes through
5613        // [`super::RateLimitUnit::as_suffix`]). Two typed dispatches on
5614        // the substrate primitive instead of one runtime `find_map`
5615        // walk through the free-helper delegate chain
5616        // [`super::rate_limit_window_unit`] (the vestigial free helper's
5617        // sole production consumer was this arm; every other consumer of
5618        // the `Duration → unit` axis — the validate gate below and the
5619        // future M4 per-Aplicacao Envoy config reconciler — now reads
5620        // the same typed method).
5621        //
5622        // A future rate-limit-unit addition (a `"d"` day suffix once
5623        // Envoy's `rate_limit_action` grows daily-bucket support) is
5624        // one variant + one arm per method on the closed-set enum, and
5625        // the compiler enforces exhaustiveness on every consumer's
5626        // `match self` arms — the codec's `parse` accepted-suffix set,
5627        // this render arm's emitted-suffix set, the validate gate's
5628        // canonical-window set, and every future per-`:contratos`-edge
5629        // rate-limit-override overlay all pick it up by construction.
5630        if let Some(unit) = rl.canonical_unit() {
5631            format!("{}/{unit}", rl.rate())
5632        } else {
5633            // Defensive fallback for non-canonical windows. Note:
5634            // [`AplicacaoSpec::validate_politicas`] rejects any
5635            // non-canonical `:rate-limit :window` via
5636            // [`AplicacaoError::PolicyRateLimitWindowNotCanonical`], so
5637            // a validated `RateLimit` never reaches this branch. The
5638            // emitted `<n>/<k>s` form is *not* round-trippable through
5639            // [`parse`] (which accepts only the closed-set
5640            // [`super::RateLimitUnit`] suffixes, not `<k>s` with an
5641            // explicit count) — the validate gate is what makes the
5642            // round-trip a structural property; this branch exists only
5643            // so a programmatic non-validated serialize doesn't panic.
5644            format!("{}/{}s", rl.rate(), rl.window().as_secs())
5645        }
5646    }
5647}
5648
5649// ── placement strategy ───────────────────────────────────────────────
5650
5651/// How the Aplicacao distributes across clusters. Three options:
5652///
5653/// - `SingleNode` — one cluster runs the app at a time; takeover on
5654///   death (Erlang/OTP distributed-app semantics).
5655/// - `Replicated` — every named cluster runs an instance (active-active).
5656/// - `Sharded` — entities distribute by hash key across clusters
5657///   (Akka cluster sharding).
5658#[derive(
5659    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
5660)]
5661pub enum PlacementStrategy {
5662    SingleNode,
5663    Replicated,
5664    Sharded,
5665}
5666
5667/// Substrate-canonical M3-mesh-shaped per-`:placement :estrategia`
5668/// distribution-strategy default for the `:placement :estrategia` axis —
5669/// the [`PlacementStrategy::Replicated`] active-active-across-every-named-
5670/// cluster arm (MESH-COMPOSITION §II.2), extracted as a typed `pub const`
5671/// so every substrate-side consumer that resolves "what
5672/// [`PlacementStrategy`] variant does an author-omitted `:placement
5673/// :estrategia` slot degrade onto?" reaches for exactly one substrate-
5674/// primitive [`PlacementStrategy`].
5675///
5676/// The `:placement :estrategia` default axis has three production
5677/// consumers on the substrate side today: the [`Default for
5678/// PlacementStrategy`] impl's return arm, the [`Default for Placement`]
5679/// impl's struct-literal `estrategia` field, and the serde-side
5680/// `#[serde(default)]` on [`Placement::estrategia`] that resolves an
5681/// author-omitted `:placement :estrategia` scalar through the [`Default
5682/// for PlacementStrategy`] impl. Prior to this lift the three folded onto
5683/// a raw `Self::Replicated` arm at the [`Default for PlacementStrategy`]
5684/// impl and implicit `PlacementStrategy::default()` routes at the sibling
5685/// consumers, with no compile-time link back to the paired
5686/// [`crate::manifest::Caixa::aplicacao_view`] fold's
5687/// `.unwrap_or_default()` `Option<Placement>` collapse arm — the fourth
5688/// production consumer that resolves an author-omitted `:placement` slot
5689/// (entirely omitted, not just the `:estrategia` scalar within a declared
5690/// `:placement` block) through [`Placement::default`] which then routes
5691/// through this same discriminator. A future coherent rebrand of the
5692/// `:placement :estrategia` default (a widening to `Sharded` once the
5693/// substrate discovers hash-keyed distribution as the more common
5694/// production shape, a tightening to `SingleNode` for stateful Erlang/OTP
5695/// distributed-app-takeover semantics MESH-COMPOSITION §II.1 already
5696/// names, a per-cluster overlay the operator pins through a future
5697/// `:placement-overrides` slot) would have had to migrate a lifted
5698/// discriminator on one path and open-coded discriminators on the peers
5699/// in lockstep or the four consumers would silently drift out of
5700/// pairing. Lifting the resolution rule to a typed `pub const` on the
5701/// substrate primitive means the M3-mesh-canonical `:placement
5702/// :estrategia` default migrates as one unit on any future axis change.
5703///
5704/// The [`PlacementStrategy::Replicated`] value pins MESH-COMPOSITION
5705/// §II.2's active-active-across-every-named-cluster arm — the closest
5706/// canonical M3 production reference the substrate carries, matching the
5707/// caixa-mesh default axis every M3 renderer already keys off (a
5708/// `programs.yaml` fan-out that emits one `HelmRelease` per cluster is
5709/// the canonical shape a `:membros`+`:contratos`-declared Aplicacao lands on
5710/// under the substrate's fleet-programs aggregator without an explicit
5711/// `:placement :estrategia` override). The two alternatives the closed
5712/// [`PlacementStrategy::ALL`] accept-set carries
5713/// ([`PlacementStrategy::SingleNode`] — Erlang/OTP distributed-app
5714/// takeover, MESH-COMPOSITION §II.1; [`PlacementStrategy::Sharded`] —
5715/// Akka-style hash-keyed distribution across clusters,
5716/// MESH-COMPOSITION §II.4) express deliberate takeover / hash-keyed
5717/// postures an author declares explicitly, never a posture an omitted
5718/// slot should silently assume.
5719///
5720/// Lifted as a typed `pub const` so the M3-mesh-canonical default has
5721/// exactly one source of truth on the `:placement :estrategia` axis, on
5722/// the same substrate-primitive lift discipline the sibling M2
5723/// per-supervisor default set carries
5724/// ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`],
5725/// [`crate::supervisor::SUPERVISOR_MAX_RESTARTS_DEFAULT`],
5726/// [`crate::supervisor::SUPERVISOR_RESTART_WINDOW_DEFAULT`],
5727/// [`crate::supervisor::SUPERVISOR_CHILD_RESTART_DEFAULT`]) and the peer
5728/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes
5729/// ([`crate::render::DEFAULT_NAMESPACE`],
5730/// [`crate::render::DEFAULT_LIBRARY_NAME`],
5731/// [`crate::render::DEFAULT_SERVICO_PORT`]). The first typed default on
5732/// the M3 mesh-primitive-defining slot family to converge onto the
5733/// substrate-primitive-lift discipline the M2 supervisor-slot family
5734/// already carries end-to-end.
5735pub const PLACEMENT_ESTRATEGIA_DEFAULT: PlacementStrategy = PlacementStrategy::Replicated;
5736
5737impl Default for PlacementStrategy {
5738    fn default() -> Self {
5739        // Route the [`Default for PlacementStrategy`] impl through the
5740        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
5741        // `pub const` rather than a raw `Self::Replicated` arm — one
5742        // source of truth for the M3-mesh-canonical active-active-
5743        // across-every-named-cluster `:placement :estrategia` default
5744        // (MESH-COMPOSITION §II.2), on the same substrate-primitive
5745        // lift discipline the sibling M2 per-supervisor default set
5746        // ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`] +
5747        // paired halves) carries end-to-end. Pinned by
5748        // `placement_strategy_default_routes_through_lifted_default`.
5749        PLACEMENT_ESTRATEGIA_DEFAULT
5750    }
5751}
5752
5753impl PlacementStrategy {
5754    /// Exhaustive iteration surface for every consumer that reads the
5755    /// full closed-set (the future M4 admission-webhook's accepted-
5756    /// strategy listing in its rejection body, a future `feira app
5757    /// placement --list` CLI-side surfacing of the accepted arm-set,
5758    /// any future round-trip fuzz harness). A future variant addition
5759    /// (an `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint
5760    /// names as a trajectory item) extends this slice as a single edit
5761    /// and every consumer picks up the new entry by construction — the
5762    /// compiler-checked exhaustiveness on the sibling method `match`
5763    /// arms is the build-time guarantee that no arm forgets to grow.
5764    /// Same shape as the sibling closed-set typed enums'
5765    /// [`RateLimitUnit::ALL`] (6bce03d) and
5766    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
5767    /// surfaces — the third closed-set typed enum on the caixa surface
5768    /// to converge onto the same discipline.
5769    pub const ALL: &'static [Self] = &[Self::SingleNode, Self::Replicated, Self::Sharded];
5770
5771    /// Canonical camelCase-schema discriminator scalar this variant
5772    /// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
5773    /// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
5774    /// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5775    /// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
5776    /// every substrate consumer that dispatches on the strategy (the
5777    /// `lareira-fleet-programs` aggregator, the future `app-operator`
5778    /// reconciler, the M3 Adaptive compression pass) reads the same
5779    /// byte-string the `Serialize` derive emits — the pin test in
5780    /// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
5781    /// asserts the two paths agree.
5782    #[must_use]
5783    pub const fn as_str(self) -> &'static str {
5784        match self {
5785            Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
5786            Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
5787            Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
5788        }
5789    }
5790
5791    /// Substrate-canonical reverse projection on the `:placement
5792    /// :estrategia` closed-set axis — parses the camelCase-schema
5793    /// discriminator scalar back to the typed variant, or `None` when
5794    /// `s` is outside the closed-set arm-string set [`Self::as_str`]
5795    /// emits. Dispatches on the same lifted
5796    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
5797    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5798    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] constants the
5799    /// [`Self::as_str`] emitter walks, so the parse and emit halves of
5800    /// the round-trip migrate through one caixa-core edit on any future
5801    /// arm addition (an `Anycast` mesh-anycast arm the MESH-COMPOSITION
5802    /// §II.5 hint names as a trajectory item lands one variant + one
5803    /// arm per method and the compiler enforces exhaustiveness on every
5804    /// consumer's `match self` arms).
5805    ///
5806    /// Prior to this lift the substrate carried only the forward
5807    /// `Self → &str` projection (the [`Self::as_str`] emitter, the
5808    /// [`std::fmt::Display`] impl routed through it, the `Serialize`
5809    /// derive that emits the same byte-string under
5810    /// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]) — every non-serde
5811    /// consumer that wanted to parse a wire-form strategy scalar had to
5812    /// re-inline a three-arm `match s { "SingleNode" => …, "Replicated"
5813    /// => …, "Sharded" => …, _ => … }` cascade that expressed no
5814    /// compile-time link back to the typed variant's canonical lifted
5815    /// constant. A future variant rename or a per-arm serde-attribute
5816    /// drift would silently split the wire byte-string one non-serde
5817    /// consumer parsed from the one the emitter wrote, with the
5818    /// failure surfacing at parse time far from the rebrand commit.
5819    ///
5820    /// Same closed-set-reverse-projection discipline the sibling
5821    /// [`crate::CaixaKind::from_wire`] (2aa6d23) and
5822    /// [`RateLimitUnit::from_suffix`] typed enums carry on the peer
5823    /// wire-side `str → Self` axes — extended onto the M3 mesh-primitive-
5824    /// defining `:placement :estrategia` closed-set axis, the third
5825    /// substrate-side closed-set typed enum to converge on the two-way
5826    /// `str ↔ Self` round-trip. Method-named `from_wire` (not `from_str`)
5827    /// to match the peer [`crate::CaixaKind::from_wire`] shape verbatim
5828    /// and side-step the [`std::str::FromStr`]-collision clippy
5829    /// (`clippy::should_implement_trait`) the plain `from_str` name
5830    /// carries; a future explicit [`std::str::FromStr`] impl can layer
5831    /// on top by delegating to this canonical arm-dispatch method.
5832    ///
5833    /// Returns `Option<Self>` (rather than `Result<Self, _>`) to match
5834    /// the sibling [`crate::CaixaKind::from_wire`] shape: the caller
5835    /// picks the diagnostic form appropriate for its use site — a
5836    /// future `feira app placement --set` CLI-side arg-parse that wants
5837    /// an `"unknown strategy: {s} (accepted: SingleNode, Replicated,
5838    /// Sharded)"` diagnostic builds one on top by iterating
5839    /// [`Self::ALL`], while the future M4 admission-webhook's rejection
5840    /// path folds `None` onto its per-CR structured refusal body.
5841    #[must_use]
5842    pub fn from_wire(s: &str) -> Option<Self> {
5843        match s {
5844            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE => Some(Self::SingleNode),
5845            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED => Some(Self::Replicated),
5846            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED => Some(Self::Sharded),
5847            _ => None,
5848        }
5849    }
5850
5851    /// Substrate-canonical per-arm predicate naming the cross-slot
5852    /// `:placement :estrategia` ↔ `:placement :shard-key` invariant on the
5853    /// closed-set typed [`PlacementStrategy`] enum: `true` iff the strategy
5854    /// consumes the paired [`Placement::shard_key`] axis (and therefore
5855    /// requires — and is the only strategy that permits — a non-empty
5856    /// `:shard-key` on the paired slot). Today the accept-set is the
5857    /// singleton `{Sharded}` — `Sharded` is the sole Akka-style
5858    /// hash-keyed distribution arm (MESH-COMPOSITION §II.4) that keys off a
5859    /// per-entity extractor expression; `SingleNode` (Erlang/OTP
5860    /// distributed-app takeover — §II.1) and `Replicated` (active-active
5861    /// across every named cluster) have no hash-keyed routing axis to
5862    /// consume the slot and refuse a declared-but-inert `:shard-key`
5863    /// through [`AplicacaoError::ShardKeyOnNonSharded`].
5864    ///
5865    /// Every validated [`Placement`] past [`AplicacaoSpec::validate_placement`]
5866    /// satisfies `placement.shard_key().is_some() ==
5867    /// placement.estrategia().requires_shard_key()` by construction — the
5868    /// cross-slot partition the pin
5869    /// [`tests::validate_placement_admits_paired_shape_iff_strategy_requires_shard_key`]
5870    /// locks load-bearing, so every downstream consumer that reaches for
5871    /// the paired shape (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
5872    /// CR materializer's per-CR shard-key resolver, the future
5873    /// [`feira app graph --shard-key`] per-Aplicacao column, the future
5874    /// per-cluster Akka-style cluster-sharding reconciler's per-entity
5875    /// hash-routing gate, the M5 adaptive-placement engine's per-strategy
5876    /// shard-key requirement probe, a future author-facing tatara-lisp
5877    /// linter that flags `(:placement (:estrategia Replicated :shard-key
5878    /// "tenantId"))` shapes before `feira lint` reaches
5879    /// [`AplicacaoSpec::validate`]) can reach for one typed dispatch on
5880    /// the substrate primitive — the predicate names *the cross-slot
5881    /// invariant*, not the arm identity.
5882    ///
5883    /// Prior to this lift the "does this strategy consume `:shard-key`"
5884    /// classification lived under the `gen_platform::IsVariant`-derived
5885    /// [`Self::is_sharded`] predicate at three fixture-builder sites in
5886    /// this crate (the [`tests::placement_strategy_variants_round_trip`]
5887    /// per-variant `Placement`-builder's `if s.is_sharded() { Some("$key"…)
5888    /// } else { None }` cascade, the
5889    /// [`tests::estrategia_returns_placement_estrategia_verbatim_across_permutations`]
5890    /// per-variant `Placement`-builder's `estrategia.is_sharded().then(||
5891    /// "tenantId".to_string())` cascade, and the
5892    /// [`tests::validate_placement_reads_through_lifted_estrategia_accessor`]
5893    /// per-variant spec-mutator's identical `.is_sharded().then(…)`
5894    /// cascade). Each site conflated two semantically distinct questions:
5895    /// "is the variant `Sharded`?" (arm-identity, what
5896    /// [`Self::is_sharded`] answers) and "does the variant consume
5897    /// `:shard-key`?" (cross-slot-invariant, what this predicate answers).
5898    /// The two questions land on the same three-way answer under today's
5899    /// closed accept-set (both trip on the singleton `{Sharded}`), but a
5900    /// future arm addition that consumed `:shard-key` under a different
5901    /// name (a hypothetical `Anycast` mesh-anycast arm the MESH-COMPOSITION
5902    /// §II.5 roadmap-hint names that hash-partitions across the cluster
5903    /// pool by client-IP hash rather than an author-declared extractor
5904    /// expression, a hypothetical `WeightedShard` variant that carries a
5905    /// shard-key + per-cluster weight table under a promoted M5
5906    /// adaptive-placement engine) or an addition that did *not* consume
5907    /// `:shard-key` on a semantically Sharded-shaped arm would silently
5908    /// split the two questions. Any consumer that read
5909    /// `.is_sharded().then(…)` for the shard-key requirement gate would
5910    /// silently misclassify the new arm as non-consuming — a fixture
5911    /// builder would omit `:shard-key` where the new arm required one and
5912    /// [`AplicacaoSpec::validate_placement`] would refuse the fixture with
5913    /// [`AplicacaoError::ShardedWithoutKey`] far from the arm-addition
5914    /// commit, a future M4 CR materializer would fall through the
5915    /// `.is_sharded()`-only branch to the non-shard-key resolver arm and
5916    /// silently emit an empty extractor at the Akka reconciler layer.
5917    ///
5918    /// Lifting the classification as a substrate-primitive method on the
5919    /// closed-set typed enum names the cross-slot invariant on the
5920    /// primitive that owns the partition: every future arm addition
5921    /// declares its `:shard-key` consumption in one place (this predicate's
5922    /// `match self` arm-set), and every downstream consumer that reaches
5923    /// for the paired shape reads through one typed dispatch. Same
5924    /// discipline as the sibling [`WitContract::is_capability`] (7b97d26)
5925    /// per-arm predicate on the pre-projection WIT-shape axis and the
5926    /// [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
5927    /// paired predicate on the post-projection typed-view axis — a
5928    /// per-arm semantic-classification predicate paired with the
5929    /// arm-identity predicate the derive already emits, closing the drift
5930    /// footgun on the cross-slot invariant axis.
5931    ///
5932    /// Method-named `requires_shard_key` (not `has_shard_key`, not
5933    /// `is_shard_keyed`, not `takes_shard_key`) because the cross-slot
5934    /// invariant reads as "this strategy *requires* the paired
5935    /// `:shard-key` axis" — the `SingleNode`/`Replicated` arms *refuse*
5936    /// the axis through [`AplicacaoError::ShardKeyOnNonSharded`], not
5937    /// merely omit it. The `has_*` framing would read as an accessor
5938    /// (returning the presence of an already-carried value) rather than a
5939    /// requirement (naming the invariant the paired slot must satisfy).
5940    /// Returns `bool` (not `Option<()>` or a marker-type witness), same
5941    /// shape as the sibling [`WitContract::is_capability`] /
5942    /// [`Self::is_sharded`] per-arm boolean predicates on the closed-set
5943    /// arm-family, so every consumer reaches for `.requires_shard_key()`
5944    /// as a drop-in replacement for the `.is_sharded()` conflated read
5945    /// without a return-shape migration.
5946    #[must_use]
5947    pub const fn requires_shard_key(self) -> bool {
5948        match self {
5949            Self::Sharded => true,
5950            Self::SingleNode | Self::Replicated => false,
5951        }
5952    }
5953}
5954
5955// Compile-time pins on the [`PlacementStrategy::requires_shard_key`]
5956// cross-slot-invariant per-arm predicate: the module-scope const-eval
5957// assertions below trip at caixa-core build time (not test time) if a
5958// future edit rewires the predicate's arm-set away from the singleton
5959// `{Sharded}` accept-set MESH-COMPOSITION §II.4 pins. The
5960// [`tests::placement_strategy_requires_shard_key_partitions_the_arm_set`]
5961// runtime pin covers the same truth-table with a more descriptive
5962// diagnostic on failure; these const-eval items add a build-time failure
5963// surface strictly stronger than the runtime pin (a downstream renderer's
5964// `const`-context reader that composed against a rebound predicate would
5965// still surface here before the test suite even ran) and side-step the
5966// `clippy::assertions_on_constants` lint the runtime `assert!(CONST)` pin
5967// would otherwise accumulate on the caixa-core module baseline.
5968const _: () = assert!(!PlacementStrategy::SingleNode.requires_shard_key());
5969const _: () = assert!(!PlacementStrategy::Replicated.requires_shard_key());
5970const _: () = assert!(PlacementStrategy::Sharded.requires_shard_key());
5971
5972/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
5973/// the pretty-printed byte-string every consumer that formats the strategy
5974/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
5975/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
5976/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
5977/// per-Aplicacao strategy line, the future M4 CR materializer's per-
5978/// admission-webhook rejection body) reaches for the same lifted
5979/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
5980/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5981/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
5982/// `Serialize` derive already emits under
5983/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
5984/// [`PlacementStrategy::as_str`] helper already returns.
5985///
5986/// Until this lift landed the sibling OTP-shape typed enums —
5987/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
5988/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
5989/// so [`std::fmt::Display`] routes through the same discriminant string
5990/// the wire format emits) — carried a stable [`std::fmt::Display`]
5991/// surface but [`PlacementStrategy`] did not; every consumer reaching
5992/// for a strategy byte-string past the wire format had to pick between
5993/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
5994/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
5995/// derive), any two of which a future variant rename or
5996/// `#[serde(rename_all = "kebab-case")]` attribute would silently
5997/// desynchronize — with the failure surfacing as a downstream renderer /
5998/// operator's per-strategy dispatch reading one spelling while the wire
5999/// format emitted another, far from the source rebrand commit and with
6000/// no field naming the drift. Routing `Display` through
6001/// [`PlacementStrategy::as_str`] makes the three paths
6002/// (`Debug` for structural inspection, `Display` for user-facing text,
6003/// `Serialize` for the wire format) converge on the same lifted
6004/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
6005/// the diagnostic byte-string, and the pretty-printed byte-string move
6006/// as a single unit through one canonical declaration each, by
6007/// construction. Same trajectory as [`PlacementStrategy::as_str`]
6008/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
6009/// closes the third path.
6010///
6011/// Pin tests
6012/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
6013/// and
6014/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
6015/// assert the three paths agree byte-for-byte on every variant, so a
6016/// future variant rename or per-arm serde attribute drift is a build
6017/// error visible at caixa-core test time, not a silent per-consumer
6018/// dispatch miss at apply / reconcile time.
6019impl std::fmt::Display for PlacementStrategy {
6020    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6021        f.write_str(self.as_str())
6022    }
6023}
6024
6025/// Where the Aplicacao runs.
6026#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
6027#[serde(rename_all = "camelCase")]
6028pub struct Placement {
6029    /// Distribution strategy.
6030    #[serde(default)]
6031    pub estrategia: PlacementStrategy,
6032
6033    /// Named clusters that host this Aplicacao. Required for
6034    /// `Replicated` and `SingleNode`; for `Sharded` declares the
6035    /// shard pool.
6036    #[serde(default)]
6037    pub clusters: Vec<String>,
6038
6039    /// Optional hint to the placement engine: `"data-locality"`,
6040    /// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
6041    #[serde(default, skip_serializing_if = "Option::is_none")]
6042    pub affinity: Option<String>,
6043
6044    /// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
6045    #[serde(default, skip_serializing_if = "Option::is_none")]
6046    pub shard_key: Option<String>,
6047}
6048
6049impl Placement {
6050    /// Substrate-canonical per-`:placement` Akka-cluster-sharding
6051    /// `:shard-key` extractor-expression scalar accessor every consumer
6052    /// of the Aplicacao's hash-keyed distribution routing keys off —
6053    /// returns the author-declared `:placement :shard-key` byte-string
6054    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
6055    /// own `Option<String>` storage; `None` when the slot is absent
6056    /// (the canonical shape under `:estrategia Replicated` /
6057    /// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
6058    /// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
6059    /// partition — `validate` refuses any `Placement` past this call
6060    /// that lands `Some` on a non-`Sharded` strategy or `None` on
6061    /// `Sharded`).
6062    ///
6063    /// The `:placement :shard-key` slot carries the Akka-style
6064    /// cluster-sharding entity-id extractor expression
6065    /// (MESH-COMPOSITION §II.4) — validated by
6066    /// [`validate_placement_shard_key`] to be a non-empty printable-
6067    /// ASCII single-token reference (`tenantId`, `$tenantId`,
6068    /// `metadata.tenantId`, `${tenant}` — the canonical shapes the
6069    /// future M4 Akka-style cluster-sharding reconciler hashes without
6070    /// re-validating at the runtime layer), and every downstream
6071    /// consumer that reads the key keys off this scalar (the
6072    /// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
6073    /// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
6074    /// declared-but-inert refusal diagnostic, the caixa-mesh
6075    /// per-Aplicacao `placement.shardKey` emit path the substrate
6076    /// operator's per-entity hash-routing reader consumes, the future
6077    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6078    /// per-shard-key resolver).
6079    ///
6080    /// Prior to this lift the `.shard_key` field was accessed inline at
6081    /// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
6082    /// `Sharded` arm's `match &self.placement.shard_key { None => …,
6083    /// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
6084    /// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
6085    /// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
6086    /// — two open-coded field-accesses that expressed no compile-time
6087    /// link back to the typed slot. A future extension of the
6088    /// `:placement :shard-key` axis to a richer author surface — a
6089    /// per-cluster override the operator pins through a future
6090    /// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
6091    /// §II.4 roadmap acknowledges, a per-tenant extractor-expression
6092    /// alias table the M4 CR materializer resolves per-CR, a
6093    /// per-Aplicacao dynamic `:shard-key` derivation the future
6094    /// adaptive placement engine computes from `:affinity` weights —
6095    /// would have had to be threaded through both open-coded copies in
6096    /// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
6097    /// arm refusal would silently disagree on which extractor
6098    /// expression a given Placement resolves to. Lifting the resolution
6099    /// rule to a typed method on the substrate primitive means every
6100    /// downstream consumer of the Aplicacao's per-`:placement`
6101    /// hash-key surface reaches for exactly one typed dispatch — the
6102    /// resolver's accept-set migrates as a unit on any future axis
6103    /// addition.
6104    ///
6105    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
6106    /// [`WitContract::destination`] / [`WitContract::world_ref`]
6107    /// (7f0fd43, 0804823) scalar accessors, per-`:membros`
6108    /// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
6109    /// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
6110    /// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
6111    /// typed dispatch on the substrate primitive, thin projections at
6112    /// each consumer" discipline extended onto the per-`:placement`
6113    /// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
6114    /// First `Option<&str>`-return accessor on the M3 mesh-slot family
6115    /// — opens the "optional per-slot scalar" projection pattern the
6116    /// sibling per-`:placement` `:affinity`, per-`:politicas`
6117    /// `:rate-limit` future lifts fold on. Named `shard_key()` to
6118    /// match the storage field's name; the accessor's identity name
6119    /// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
6120    /// slot's docstring already carries.
6121    #[must_use]
6122    pub const fn shard_key(&self) -> Option<&str> {
6123        match &self.shard_key {
6124            Some(s) => Some(s.as_str()),
6125            None => None,
6126        }
6127    }
6128
6129    /// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
6130    /// compression-hint scalar accessor every weighting-consumer of the
6131    /// Aplicacao's per-hint routing surface keys off — returns the
6132    /// author-declared `:placement :affinity` byte-string verbatim as
6133    /// an `Option<&str>`, borrowed from the typed slot's own
6134    /// `Option<String>` storage; `None` when the slot is absent (the
6135    /// canonical shape of an Aplicacao that leaves the compression
6136    /// weighting up to the placement engine's cluster-default arm — no
6137    /// author-authored `data-locality` / `low-latency` / etc. hint
6138    /// biases the routing).
6139    ///
6140    /// The `:placement :affinity` slot carries the M3 Adaptive-
6141    /// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
6142    /// by [`validate_placement_affinity`] to be a DNS-1123 label
6143    /// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
6144    /// K8s-conformant label-selector shape every apiserver-side pod-
6145    /// affinity / node-affinity materializer already gates on
6146    /// admission), and every downstream consumer that reads the hint
6147    /// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
6148    /// per-hint value-shape gate, the caixa-mesh per-Aplicacao
6149    /// `placement.affinity` overlay emit path the substrate operator's
6150    /// per-hint weighting-consumer reads, the future M4
6151    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
6152    /// pod-affinity / node-affinity selector resolver).
6153    ///
6154    /// Prior to this lift the `.affinity` field was accessed inline at
6155    /// the sole caixa-core site — the
6156    /// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
6157    /// `if let Some(a) = &self.placement.affinity { …
6158    /// validate_placement_affinity(a)? … }` cascade — one open-coded
6159    /// field-access that expressed no compile-time link back to the
6160    /// typed slot. A future extension of the `:placement :affinity`
6161    /// axis to a richer author surface — a per-cluster override the
6162    /// operator pins through a future `:placement :affinity-overrides`
6163    /// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
6164    /// tenant hint alias table the M4 CR materializer resolves per-CR,
6165    /// a per-Aplicacao dynamic `:affinity` derivation the future
6166    /// adaptive placement engine computes from `:clusters` topology —
6167    /// would have had to be threaded through the open-coded copy in
6168    /// lockstep with any future caixa-mesh / caixa-flux / M4 CR
6169    /// materializer reader that landed on the axis, or the per-hint
6170    /// value-shape gate and its downstream weighting consumers would
6171    /// silently disagree on which hint a given Placement resolves to.
6172    /// Lifting the resolution rule to a typed method on the substrate
6173    /// primitive means every downstream consumer of the Aplicacao's
6174    /// per-`:placement` compression-hint surface reaches for exactly
6175    /// one typed dispatch — the resolver's accept-set migrates as a
6176    /// unit on any future axis addition.
6177    ///
6178    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
6179    /// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
6180    /// optional-scalar axis — same "one typed dispatch on the substrate
6181    /// primitive, thin projections at each consumer" discipline extended
6182    /// onto the per-`:placement` M3-Adaptive-compression-hint
6183    /// `Option<String>` optional-scalar axis. Second `Option<&str>`-
6184    /// return accessor on the M3 mesh-slot family; closes the last
6185    /// un-lifted per-`:placement` `Option<String>` axis. Named
6186    /// `affinity()` to match the storage field's name; the accessor's
6187    /// identity name maps onto the canonical MESH-COMPOSITION §II.4
6188    /// vocabulary the slot's docstring already carries.
6189    #[must_use]
6190    pub const fn affinity(&self) -> Option<&str> {
6191        match &self.affinity {
6192            Some(s) => Some(s.as_str()),
6193            None => None,
6194        }
6195    }
6196
6197    /// Substrate-canonical per-`:placement` `:estrategia` distribution-
6198    /// strategy scalar accessor every consumer that dispatches on the
6199    /// Aplicacao's per-cluster distribution shape keys off — returns the
6200    /// author-declared `:placement :estrategia` variant verbatim as a
6201    /// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
6202    /// `PlacementStrategy` storage.
6203    ///
6204    /// The `:placement :estrategia` slot carries the closed-set
6205    /// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
6206    /// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
6207    /// `Replicated` — active-active across every named cluster; `Sharded`
6208    /// — Akka-style hash-keyed entity distribution across the cluster pool
6209    /// per §II.4) that every downstream consumer of the Aplicacao's
6210    /// per-cluster fan-out shape keys off. Validated by
6211    /// [`AplicacaoSpec::validate_placement`] to be paired coherently with
6212    /// the sibling `:shard-key` axis (`shard_key.is_some() ==
6213    /// matches!(estrategia, Sharded)` — the cross-slot partition the
6214    /// [`Placement::shard_key`] accessor's docstring pins), and every
6215    /// downstream consumer that reads the strategy keys off this scalar
6216    /// (the [`AplicacaoSpec::validate_placement`]
6217    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
6218    /// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
6219    /// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
6220    /// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
6221    /// declared-but-inert refusal's
6222    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
6223    /// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
6224    /// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
6225    /// emit path the substrate operator's per-strategy fan-out reader
6226    /// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
6227    /// materializer's per-strategy admission-webhook resolver).
6228    ///
6229    /// Prior to this lift the `.estrategia` field was accessed inline at
6230    /// four sites — the [`AplicacaoSpec::validate_placement`]
6231    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
6232    /// `estrategia: self.placement.estrategia`, the same method's
6233    /// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
6234    /// partition dispatch, the non-`Sharded`-arm
6235    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
6236    /// `estrategia: self.placement.estrategia`, and the `feira app graph`
6237    /// per-Aplicacao strategy print line at
6238    /// `println!("… {} …", spec.placement.estrategia, …)`
6239    /// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
6240    /// expressed no compile-time link back to the typed slot. A future
6241    /// extension of the `:placement :estrategia` axis to a richer author
6242    /// surface (a per-cluster override the operator pins through a future
6243    /// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
6244    /// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
6245    /// materializer resolves per-CR, a per-Aplicacao dynamic strategy
6246    /// derivation the future adaptive placement engine computes from
6247    /// `:affinity` + `:clusters` topology) would have had to be threaded
6248    /// through every open-coded copy in lockstep — one consumer reading
6249    /// the raw variant while a peer read the operator-resolved variant
6250    /// would silently split the `PlacementWithoutClusters` /
6251    /// `ShardKeyOnNonSharded` diagnostic quotes from the actual
6252    /// partition-dispatch input, a two-consumer split at the validator
6253    /// far from the source `caixa.lisp` with no field naming the
6254    /// strategy-drift root cause. Lifting the resolution rule to a typed
6255    /// method on the substrate primitive means every downstream consumer
6256    /// of the Aplicacao's per-`:placement` distribution-strategy surface
6257    /// reaches for exactly one typed dispatch — the resolver's accept-set
6258    /// migrates as a unit on any future axis addition.
6259    ///
6260    /// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
6261    /// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
6262    /// same "one typed dispatch on the substrate primitive, thin
6263    /// projections at each consumer" discipline extended onto the
6264    /// per-`:placement` distribution-strategy `Copy`-composite-enum
6265    /// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
6266    /// family; first `Copy`-return accessor on the M3 mesh-slot
6267    /// `Placement` type — companion to the sibling per-`:placement`
6268    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
6269    /// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
6270    /// optional-scalar axes, closing the last unlifted per-`:placement`
6271    /// scalar-value axis (the closed-set `PlacementStrategy`
6272    /// distribution-strategy discriminator) so every downstream
6273    /// per-`:placement` reader now routes through a typed dispatch on
6274    /// the substrate primitive. Named `estrategia()` to match the storage
6275    /// field's name; the accessor's identity name maps onto the
6276    /// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
6277    /// already carries. Declared `pub const fn` (matching the peer M3
6278    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
6279    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
6280    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
6281    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
6282    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
6283    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
6284    /// [`RateLimit`] — every one a `pub const fn`) so every future
6285    /// substrate-side `const`-context consumer of the resolved
6286    /// distribution-strategy variant (a `const _: () = assert!(…)`
6287    /// module-scope invariant pin on a per-fixture typed [`Placement`],
6288    /// a future M4 admission-webhook `const fn` resolver over a typed
6289    /// [`Placement`], any `const fn` composer that fans on the strategy
6290    /// at compile time) reaches through the same typed dispatch on the
6291    /// substrate primitive at const-eval time as at runtime. Pinned by
6292    /// [`placement_estrategia_accessor_is_const_fn`] which witnesses the
6293    /// const-eval posture at module scope via `const _:() = …` items so
6294    /// any future accidental downgrade to non-`const` trips at caixa-core
6295    /// build time.
6296    #[must_use]
6297    pub const fn estrategia(&self) -> PlacementStrategy {
6298        self.estrategia
6299    }
6300
6301    /// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
6302    /// per-cluster distribution-target slice accessor every consumer that
6303    /// walks the Aplicacao's declared cluster-pool keys off — returns the
6304    /// author-declared `:placement :clusters` `Vec<String>` verbatim as a
6305    /// `&[String]` slice-view, borrowed from the typed slot's own
6306    /// `Vec<String>` storage (a zero-copy slice-view over the same
6307    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
6308    /// through). Non-optional: the empty slice is the load-bearing
6309    /// pre-validation sentinel every downstream consumer of the paired
6310    /// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
6311    /// off — every strategy in the closed
6312    /// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
6313    /// requires a non-empty list (`SingleNode` / `Replicated` use the
6314    /// list as hosting / takeover candidates per Erlang/OTP distributed-
6315    /// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
6316    /// shard pool per Akka cluster-sharding convention, §II.4), so the
6317    /// `.is_empty()` probe is the shared pre-condition every
6318    /// [`AplicacaoSpec::validate_placement`] arm heads on.
6319    ///
6320    /// The `:placement :clusters` slot carries the K8s-conformant DNS-
6321    /// 1123-label per-cluster distribution-target list — the same
6322    /// set-not-multiset shape the sibling `:membros :caixa` /
6323    /// `:children :caixa` axes carry (`validate_placement`'s per-entry
6324    /// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
6325    /// pins the shape). Every downstream consumer that fans on the list
6326    /// keys off this slice (the [`AplicacaoSpec::validate_placement`]
6327    /// pre-flight `.is_empty()` probe that trips
6328    /// [`AplicacaoError::PlacementWithoutClusters`], the same method's
6329    /// per-cluster value-shape + duplicate-detection fan-out loop, the
6330    /// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
6331    /// that materializes the list verbatim onto every
6332    /// programs.yaml entry the substrate operator's per-cluster
6333    /// `placement.clusters | contains .Values.cluster` filter reads,
6334    /// the `feira app graph` per-Aplicacao cluster print line, the
6335    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6336    /// per-cluster admission-webhook fan-out, the future M5 adaptive-
6337    /// placement engine's cluster-topology reader).
6338    ///
6339    /// Prior to this lift the `.clusters` `Vec<String>` was accessed
6340    /// inline at three production sites — the
6341    /// [`AplicacaoSpec::validate_placement`] pre-flight
6342    /// `self.placement.clusters.is_empty()` refusal probe, the same
6343    /// method's per-cluster validate loop's
6344    /// `for c in &self.placement.clusters` traversal head, and the
6345    /// `feira app graph` per-Aplicacao print line's
6346    /// `spec.placement.clusters` `{:?}` formatter argument
6347    /// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
6348    /// that expressed no compile-time link back to the typed slot. A
6349    /// future extension of the `:placement :clusters` axis to a richer
6350    /// author surface (a per-tenant cluster-pool overlay the operator
6351    /// pins through a future `:placement :clusters-overrides` slot the
6352    /// MESH-COMPOSITION §V cross-cluster-federation roadmap
6353    /// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
6354    /// the future M5 adaptive-placement engine computes from
6355    /// `:affinity` weights + live cluster-topology probes, a promotion
6356    /// of the plain `Vec<String>` to a richer `{static, dynamic}`
6357    /// partition once the substrate operator's cluster-membership
6358    /// reconciler comes into typed scope) would have had to be threaded
6359    /// through all three open-coded copies in lockstep or one consumer
6360    /// would silently disagree with the peers on which cluster-pool a
6361    /// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
6362    /// reading the raw slot while the peer per-cluster validate loop
6363    /// read an operator-resolved slot would silently split the paired
6364    /// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
6365    /// `PlacementClusterDuplicate` refusal cascade's actual traversal
6366    /// input from the pre-flight input, a three-consumer split at the
6367    /// validator and formatter far from the source `caixa.lisp` with
6368    /// no field naming the cluster-pool-drift root cause. Lifting the
6369    /// resolution rule to a typed method on the substrate primitive
6370    /// means every downstream consumer of the Aplicacao's
6371    /// per-`:placement` cluster-pool surface reaches for exactly one
6372    /// typed dispatch — the resolver's accept-set migrates as a unit
6373    /// on any future axis addition.
6374    ///
6375    /// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
6376    /// slot — sibling to the seed M2
6377    /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
6378    /// slice-return accessor on the peer per-`:supervisor` static-
6379    /// child-list `Vec`-carry axis, extended onto the first M3 mesh-
6380    /// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
6381    /// primitive, thin projections at each consumer" discipline. The
6382    /// three peer `Vec`-carry axes still unlifted at the time of this
6383    /// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
6384    /// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
6385    /// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
6386    /// [`crate::UpgradeFromEntry::instructions`]
6387    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
6388    /// — inherit this accessor's discipline as future compounding runs
6389    /// migrate their consumers onto the shared slice-return shape.
6390    /// Fourth (and final) accessor on the M3 mesh-slot `Placement`
6391    /// type, sibling to the two `Option<&str>`-return
6392    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
6393    /// (74ec2d3) accessors and the `Copy`-return
6394    /// [`Placement::estrategia`] (921fe1b) accessor — closes the last
6395    /// unlifted per-`:placement` field axis (the `Vec<String>`
6396    /// distribution-target-list carrier) so every downstream
6397    /// per-`:placement` reader now routes through a typed dispatch on
6398    /// the substrate primitive. Named `clusters()` to match the storage
6399    /// field's name verbatim and the tatara-lisp author-surface term
6400    /// (`:clusters`) the field's own docstring already carries; the
6401    /// accessor's identity maps onto the canonical MESH-COMPOSITION
6402    /// §II.1 / §II.4 vocabulary the slot's docstring already reaches
6403    /// for. Returns `&[String]` (not `&Vec<String>`) because every
6404    /// downstream consumer of the cluster list treats it as a read-only
6405    /// sequence — the slice-view is the narrowest borrow that supports
6406    /// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
6407    /// `.len()`) without leaking the backing `Vec`'s
6408    /// grow/push/reserve surface that no consumer of the typed view
6409    /// reaches for (the storage-side `Vec` remains reachable through
6410    /// the `pub clusters` field for the mutation-carrying serde
6411    /// round-trip and per-test fixture-mutation paths).
6412    #[must_use]
6413    pub const fn clusters(&self) -> &[String] {
6414        self.clusters.as_slice()
6415    }
6416}
6417
6418impl Default for Placement {
6419    fn default() -> Self {
6420        Self {
6421            // Route the struct-literal `estrategia` default arm through
6422            // the substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`]
6423            // typed `pub const` rather than the transitively-derived
6424            // [`PlacementStrategy::default`] route — one source of truth
6425            // for the M3-mesh-canonical [`PlacementStrategy::Replicated`]
6426            // active-active-across-every-named-cluster arm
6427            // (MESH-COMPOSITION §II.2) that both this struct-literal
6428            // altitude and the sibling [`Default for PlacementStrategy`]
6429            // impl already key off through the same substrate primitive.
6430            // Pinned by
6431            // `placement_default_estrategia_routes_through_lifted_default`.
6432            estrategia: PLACEMENT_ESTRATEGIA_DEFAULT,
6433            clusters: Vec::new(),
6434            affinity: None,
6435            shard_key: None,
6436        }
6437    }
6438}
6439
6440// ── external entry point ─────────────────────────────────────────────
6441
6442/// External entry point — what an outside caller sees. Renders to a
6443/// Gateway / Ingress + a route to the named member Servico.
6444#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
6445#[serde(rename_all = "camelCase")]
6446pub struct Entrada {
6447    /// Public hostname (e.g. `"checkout.quero.cloud"`).
6448    pub host: String,
6449
6450    /// Member Servico the gateway routes to. Must be in `:membros`.
6451    pub para: String,
6452
6453    /// Optional path filter — if set, only matching paths route to
6454    /// this Aplicacao (the rest fall through to other route rules).
6455    #[serde(default)]
6456    pub paths: Vec<String>,
6457
6458    /// Default port on the destination Servico (the trigger.service.port).
6459    #[serde(default = "default_port")]
6460    pub port: u16,
6461}
6462
6463impl Entrada {
6464    /// Substrate-canonical per-`:entrada` URL-path fallback resolver
6465    /// every HTTPRoute-aware renderer keys off — returns the author-
6466    /// declared `:entrada :paths` list verbatim when non-empty, and the
6467    /// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
6468    /// all fallback otherwise (so an Aplicacao author who declares an
6469    /// external `:entrada` block but no per-path rule surface still
6470    /// gets a route whose sole `HTTPPathMatch` matches every incoming
6471    /// request under the paired
6472    /// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
6473    ///
6474    /// Prior to this lift the "if `:entrada :paths` is empty use the
6475    /// substrate catch-all; else return each declared path verbatim"
6476    /// cascade lived inline at
6477    /// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
6478    /// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
6479    /// per-Aplicacao HTTPRoute per-rule path-list emit site the
6480    /// substrate ships today, with no typed method on the substrate
6481    /// primitive that named the rule. A future path-resolution axis
6482    /// addition — a per-cluster `:entrada :default-path` override the
6483    /// operator pins through a future `:placement`-scoped slot, an
6484    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
6485    /// admission-webhook floor that materializes the catch-all before
6486    /// the CR lands, a future per-`:entrada :paths` overlay from a
6487    /// per-cluster policy the future `feira app deploy` pipeline
6488    /// consumes — would have to be threaded through every renderer's
6489    /// inline copy of the cascade in lockstep or one consumer would
6490    /// silently disagree with the peers on which path list a given
6491    /// `:entrada` block resolves to. Lifting the rule to a typed
6492    /// method on the substrate primitive means every downstream
6493    /// HTTPRoute-aware consumer (the M4 CR materializer, the future
6494    /// per-cluster overlay resolver, every future per-Aplicacao
6495    /// snapshot renderer) reaches for exactly one typed dispatch —
6496    /// the resolver's accept-set moves as a unit on any future axis
6497    /// addition.
6498    ///
6499    /// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
6500    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
6501    /// per-`:entrada` scalar-value axes — extends the "one typed
6502    /// dispatch on the substrate primitive, thin projections at each
6503    /// consumer" discipline onto the per-`:entrada` path-list
6504    /// resolution axis every HTTPRoute-aware renderer consumes. Same
6505    /// shape as the [`MeshPolicy::is_empty`] typed predicate on the
6506    /// sibling `:politicas` primitive — one typed method on the
6507    /// substrate primitive that names the cascade every renderer
6508    /// otherwise re-inlines.
6509    #[must_use]
6510    pub fn resolved_paths(&self) -> Vec<&str> {
6511        // Route the internal cascade-head + per-entry projection reads
6512        // through the lifted [`Self::paths`] slice accessor rather than
6513        // the raw `self.paths` field access — the substrate-primitive
6514        // per-`:entrada` path-list resolver's two internal reads now
6515        // key off the canonical raw-slot surface every downstream
6516        // per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
6517        // per-entry value-shape gate, `feira app graph`'s per-Aplicacao
6518        // entrada summary line's `{:?}` Debug print) routes through, so
6519        // any future rebrand on the typed slot's raw-slot reader lands
6520        // at exactly one place. Same two-consumer coherence discipline
6521        // the sibling `Placement::clusters` (a6e18d7) accessor pins on
6522        // the peer M3 mesh-slot `Vec<String>`-carry axis.
6523        if self.paths().is_empty() {
6524            vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
6525        } else {
6526            self.paths().iter().map(String::as_str).collect()
6527        }
6528    }
6529
6530    /// Substrate-canonical per-`:entrada` DNS-hostname singular
6531    /// accessor every Gateway-API `Listener.hostname` reader keys off
6532    /// — returns the author-declared `:entrada :host` byte-string
6533    /// verbatim as a `&str`, borrowed from the typed slot's own
6534    /// [`String`] storage.
6535    ///
6536    /// Named the "singular" half of the DNS-hostname resolver pair on
6537    /// the substrate primitive: the parent-Gateway per-listener
6538    /// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
6539    /// (`Listener.hostname: Option<PreciseHostname>` — at most one
6540    /// hostname per listener), and this accessor is the typed dispatch
6541    /// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
6542    /// reaches for. Its plural sibling [`Entrada::hostnames`] carries
6543    /// the per-HTTPRoute `spec.hostnames[]` list axis the same
6544    /// per-Aplicacao ingress-hostname surface projects onto.
6545    ///
6546    /// Prior to this lift the `entrada.host.clone()` byte-string was
6547    /// accessed inline at two `caixa-mesh` sites — the parent-Gateway
6548    /// per-listener singular `hostname:` axis
6549    /// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
6550    /// per-HTTPRoute plural `spec.hostnames[]` axis
6551    /// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
6552    /// consumers read the same `entrada.host` field but the two-site
6553    /// duplication expressed no compile-time contract that the singular
6554    /// Gateway-listener filter and the plural `HTTPRoute` filter list
6555    /// stay in lockstep on future extensions of the `:entrada` slot to
6556    /// a multi-hostname author surface (an `:entrada :alt-hosts` list
6557    /// overlay, a per-cluster SNI fan-out the operator pins through a
6558    /// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
6559    /// Aplicacao` CR materializer's per-listener virtual-host filter
6560    /// admission-webhook overlay). Any such extension would have to be
6561    /// threaded through every renderer's inline copy of the resolution
6562    /// in lockstep or the Gateway listener's `hostname:` filter would
6563    /// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
6564    /// — a Gateway-API-conformance divergence whose apply-time symptom
6565    /// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
6566    /// `NoMatchingParent` — the API server rejects the route because
6567    /// its `hostnames[]` filter doesn't intersect the parent listener's
6568    /// `hostname` filter) is far from the source `caixa.lisp` and never
6569    /// surfaces in the emitted YAML. Lifting the singular and plural
6570    /// resolvers to typed methods on the substrate primitive means
6571    /// every consumer of the Aplicacao's ingress-hostname surface
6572    /// reaches for exactly one typed dispatch, and the pair-invariant
6573    /// `hostnames() == vec![hostname()]` pinned by the sibling
6574    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
6575    /// keeps the two axes in lockstep by construction.
6576    ///
6577    /// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
6578    /// (1449891) path-list resolver on the per-HTTPRoute per-rule
6579    /// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
6580    /// the substrate primitive, thin projections at each consumer"
6581    /// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
6582    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
6583    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
6584    /// [`Entrada::resolved_paths`] lifts apply on the sibling per-
6585    /// `:entrada` scalar-value + list-value axes.
6586    #[must_use]
6587    pub const fn hostname(&self) -> &str {
6588        self.host.as_str()
6589    }
6590
6591    /// Substrate-canonical per-`:entrada` DNS-hostname plural
6592    /// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
6593    /// keys off — returns the singleton `[hostname()]` list under
6594    /// today's single-hostname-per-Aplicacao author surface, and the
6595    /// authoritative multi-hostname list under a future
6596    /// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
6597    ///
6598    /// Plural half of the DNS-hostname resolver pair — see the
6599    /// companion [`Entrada::hostname`] docstring for the two-consumer
6600    /// lift + pair-invariant discipline (`hostnames() ==
6601    /// vec![hostname()]`, pinned load-bearing by the sibling
6602    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
6603    /// test).
6604    ///
6605    /// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
6606    /// per-`:entrada` plural-list resolver on the per-HTTPRoute
6607    /// per-rule path-list axis — same `Vec<&str>` shape, same
6608    /// substrate-primitive-owns-the-resolver discipline extended to
6609    /// the per-HTTPRoute virtual-host filter-list axis.
6610    #[must_use]
6611    pub fn hostnames(&self) -> Vec<&str> {
6612        vec![self.hostname()]
6613    }
6614
6615    /// Substrate-canonical per-`:entrada` destination-Servico scalar
6616    /// accessor every Gateway-API `HTTPRoute` reader keys off — returns
6617    /// the author-declared `:entrada :para` byte-string verbatim as a
6618    /// `&str`, borrowed from the typed slot's own [`String`] storage.
6619    ///
6620    /// The `:entrada :para` slot names the single member Servico the
6621    /// external Gateway routes to (validated by
6622    /// [`AplicacaoSpec::validate`] to be a
6623    /// [`Membro::caixa`] the Aplicacao declares — a stray
6624    /// `:para` that doesn't name a member is
6625    /// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
6626    /// backend-attachment miss at cluster-apply time). Under today's
6627    /// single-destination author surface `:entrada :para` is the ingress
6628    /// apex Servico's canonical identity; under a hypothetical
6629    /// future multi-backend author surface (a `:entrada
6630    /// :split :backends` weighted-fan-out overlay for canary /
6631    /// blue-green traffic-split rollouts, per-path override for
6632    /// path-based per-Servico routing beyond the single-apex model,
6633    /// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6634    /// per-CR admission-webhook that promotes the scalar to a
6635    /// weighted list) this accessor is the substrate primitive's typed
6636    /// dispatch every downstream `HTTPRoute`-aware consumer routes
6637    /// through, so the resolution shape migrates as a unit on one
6638    /// caixa-core edit rather than a coordinated rewrite across every
6639    /// renderer's inline field-access.
6640    ///
6641    /// Prior to this lift the `entrada.para` byte-string was accessed
6642    /// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
6643    /// `metadata.name` composer's per-destination discriminator arg
6644    /// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
6645    /// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
6646    /// per-HTTPRoute per-rule `backendRefs[0].name` axis
6647    /// (`entrada.para.clone()`,
6648    /// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
6649    /// consumers read the same `entrada.para` field but the two-site
6650    /// duplication expressed no compile-time contract that the HTTPRoute
6651    /// name-discriminator and the per-rule backend name stay in
6652    /// lockstep on future extensions of the `:entrada` slot to a
6653    /// multi-destination author surface. Any such extension would have
6654    /// to be threaded through every renderer's inline copy of the
6655    /// destination projection in lockstep or the HTTPRoute
6656    /// `metadata.name` would silently reference a different destination
6657    /// than its own `backendRefs[]` — an operator-side
6658    /// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
6659    /// grep-by-name lookup would land on a route whose `backendRefs[]`
6660    /// silently point at a peer Servico, dropping every external
6661    /// `:entrada` flow at the gateway with the destination-drift root
6662    /// cause invisible in the emitted YAML.
6663    ///
6664    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
6665    /// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
6666    /// the per-listener singular / per-HTTPRoute plural filter axes and
6667    /// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
6668    /// resolver on the per-HTTPRoute per-rule matches axis. Same "one
6669    /// typed dispatch on the substrate primitive, thin projections at
6670    /// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
6671    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
6672    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
6673    /// [`Entrada::resolved_paths`] (1449891) lifts apply on the
6674    /// sibling per-`:entrada` scalar-value + list-value axes — this
6675    /// accessor closes the last unlifted per-`:entrada` scalar axis
6676    /// (the destination-Servico byte-string) so every downstream
6677    /// per-`:entrada` reader now routes through a typed dispatch on
6678    /// the substrate primitive.
6679    #[must_use]
6680    pub const fn destination(&self) -> &str {
6681        self.para.as_str()
6682    }
6683
6684    /// Substrate-canonical per-`:entrada` L4-port scalar accessor every
6685    /// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
6686    /// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
6687    /// reader keys off — returns the author-declared `:entrada :port`
6688    /// value verbatim as a `u16`, `Copy`-projected from the typed slot's
6689    /// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
6690    /// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
6691    /// [`AplicacaoError::EntradaPortZero`], not a silent
6692    /// admission-webhook rejection at cluster-apply time).
6693    ///
6694    /// The `:entrada :port` slot carries the destination Servico's
6695    /// canonical in-cluster L4 listener port (`trigger.service.port` on
6696    /// the `pleme-computeunit` library chart), and every downstream
6697    /// consumer that reads the port keys off this scalar (the
6698    /// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
6699    /// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
6700    /// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
6701    /// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
6702    /// CR materializer's per-Aplicacao gateway port resolver).
6703    ///
6704    /// Prior to this lift the `.port` field was accessed inline at two
6705    /// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
6706    /// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
6707    /// the [`AplicacaoSpec::port_for_destination`] resolver's
6708    /// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
6709    /// open-coded field-accesses that expressed no compile-time link
6710    /// back to the typed slot. A future extension of the `:entrada :port`
6711    /// axis to a richer author surface — a per-cluster override the
6712    /// operator pins through a future `:placement :default-port` slot the
6713    /// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
6714    /// `Option<u16>`-shape migration once the substrate grows per-`:membros`
6715    /// heterogeneous listener ports, an M4
6716    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
6717    /// admission-webhook floor that promotes the scalar to a
6718    /// per-destination map — would have had to be threaded through both
6719    /// open-coded copies in lockstep or the structural-floor validator
6720    /// and the [`AplicacaoSpec::port_for_destination`] resolver would
6721    /// silently disagree on which port a given [`Entrada`] resolves to.
6722    /// Lifting the resolution rule to a typed method on the substrate
6723    /// primitive means every downstream consumer of the Aplicacao's
6724    /// per-`:entrada` L4-port surface reaches for exactly one typed
6725    /// dispatch — the resolver's accept-set migrates as a unit on any
6726    /// future axis addition.
6727    ///
6728    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
6729    /// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
6730    /// accessors on the per-`:entrada` scalar-value axis — same "one
6731    /// typed dispatch on the substrate primitive, thin projections at
6732    /// each consumer" discipline extended onto the per-`:entrada`
6733    /// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
6734    /// the M3 mesh-slot `Entrada` type — closes the last unlifted
6735    /// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
6736    /// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
6737    /// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
6738    /// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
6739    /// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
6740    /// storage field's name; the accessor's identity name maps onto the
6741    /// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
6742    /// already carries. Declared `pub const fn` (matching the peer M3
6743    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
6744    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
6745    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
6746    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
6747    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
6748    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
6749    /// [`RateLimit`], and the sibling per-`:placement`
6750    /// [`Placement::estrategia`] on the peer M3 mesh-slot `Copy`-composite-
6751    /// enum scalar axis — every one a `pub const fn`) so every future
6752    /// substrate-side `const`-context consumer of the resolved
6753    /// per-`:entrada` L4-port scalar (a `const _: () = assert!(…)`
6754    /// module-scope pin on a per-fixture typed [`Entrada`] anchoring
6755    /// `entrada.port() >= SERVICO_PORT_MIN` at compile time, a future M4
6756    /// admission-webhook `const fn` per-CR gateway-port floor over a
6757    /// typed [`Entrada`], any `const fn` composer that fans on the port
6758    /// at compile time) reaches through the same typed dispatch on the
6759    /// substrate primitive at const-eval time as at runtime. Pinned by
6760    /// [`entrada_port_accessor_is_const_fn`] which witnesses the
6761    /// const-eval posture at module scope via `const _:() = …` items so
6762    /// any future accidental downgrade to non-`const` trips at caixa-core
6763    /// build time.
6764    #[must_use]
6765    pub const fn port(&self) -> u16 {
6766        self.port
6767    }
6768
6769    /// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
6770    /// slice accessor every HTTPRoute-aware renderer keys off when it
6771    /// wants the raw author-declared path-list (not the fallback-
6772    /// applied projection [`Self::resolved_paths`] returns) — returns
6773    /// the author-declared `:entrada :paths` list verbatim as `&[String]`,
6774    /// borrowed from the typed slot's own [`Vec<String>`] storage.
6775    ///
6776    /// Named the "raw slot" half of the per-`:entrada` path-list resolver
6777    /// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
6778    /// (1449891) closes the fallback-applying arm every per-Aplicacao
6779    /// HTTPRoute per-rule `matches[].path` emitter routes through (empty
6780    /// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
6781    /// catch-all; non-empty slot → per-entry verbatim projection); this
6782    /// accessor closes the raw-slot arm every consumer that must see the
6783    /// author's declaration verbatim (the [`AplicacaoSpec::validate`]
6784    /// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
6785    /// not `Err(EntradaPathEmpty)`, so it cannot route through the
6786    /// fallback-applying sibling; the `feira app graph` per-Aplicacao
6787    /// external-gateway summary line's `{:?}` Debug print — which must
6788    /// name the author's declaration, not the substrate's fallback, so
6789    /// an author reading their graph output can grep their caixa.lisp
6790    /// for the exact list they authored) routes through.
6791    ///
6792    /// Prior to this lift the `.paths` field was accessed inline at four
6793    /// production sites: the two internal reads in [`Self::resolved_paths`]
6794    /// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
6795    /// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
6796    /// value-shape gate's `for p in &e.paths` traversal head, and the
6797    /// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
6798    /// Debug print — four open-coded field-accesses that expressed no
6799    /// compile-time link back to the typed slot. A future extension of
6800    /// the `:entrada :paths` axis to a richer author surface — a
6801    /// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
6802    /// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
6803    /// spec supports through `matches[].method`), a per-path per-header
6804    /// filter overlay (`matches[].headers[]`), a per-cluster override
6805    /// the operator pins through a future `:placement :path-overlay`
6806    /// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6807    /// per-CR admission-webhook that normalized the list at admission
6808    /// time — would have had to be threaded through every open-coded
6809    /// copy in lockstep or the validator's per-entry gate would silently
6810    /// disagree with the renderer's per-entry emit on which list a given
6811    /// `:entrada` block resolves to. Lifting the resolution to a typed
6812    /// method on the substrate primitive means every downstream consumer
6813    /// of the Aplicacao's per-`:entrada` path-list surface reaches for
6814    /// exactly one typed dispatch — the resolver's accept-set migrates
6815    /// as a unit on any future axis addition.
6816    ///
6817    /// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
6818    /// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
6819    /// carry axis — same "one typed dispatch on the substrate primitive,
6820    /// thin projections at each consumer" discipline extended onto the
6821    /// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
6822    /// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
6823    /// carrier) so every downstream per-`:entrada` reader now routes
6824    /// through a typed dispatch on the substrate primitive. Returns
6825    /// `&[String]` (not `&Vec<String>`) because every downstream consumer
6826    /// treats the list as a read-only sequence — the slice-view is the
6827    /// narrowest borrow that supports every present + roadmapped consumer
6828    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
6829    /// `Vec`'s grow/push/reserve surface that no consumer of the typed
6830    /// view reaches for (the storage-side `Vec` remains reachable through
6831    /// the `pub paths` field for the mutation-carrying serde round-trip
6832    /// and per-test fixture-mutation paths).
6833    #[must_use]
6834    pub const fn paths(&self) -> &[String] {
6835        self.paths.as_slice()
6836    }
6837}
6838
6839/// Canonical default L4 port every typed Servico exposes on its
6840/// in-cluster K8s Service (the `trigger.service.port` axis the
6841/// `pleme-computeunit` library chart emits, the `:entrada :port` author
6842/// surface defaults to when the author omits the slot, and the
6843/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
6844/// `:entrada` block matches the per-`:contratos` destination Servico).
6845/// The single source of truth all three typed-port consumers reach for:
6846///
6847///   - [`Entrada::port`]'s serde default (via the
6848///     [`default_port`] helper this constant feeds); the author surface
6849///     `(:entrada (:host … :para …))` without an explicit `:port` slot
6850///     reads back as a typed [`Entrada`] carrying this exact value;
6851///   - the
6852///     [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
6853///     emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
6854///     fallback, fired when the typed `:entrada` block doesn't name
6855///     the per-`:contratos` destination Servico — the typed
6856///     `:contratos` graph carries no per-destination port axis (the
6857///     destination port is the destination Servico's
6858///     `lareira-<nome>` chart's `trigger.service.port`, which the
6859///     Aplicacao-level renderer has no visibility into without a
6860///     resolver round-trip), so the renderer falls back to the
6861///     substrate's canonical Servico-port assumption — by
6862///     construction the same value the destination's own
6863///     `pleme-computeunit` chart emits, the same value the
6864///     destination's own typed `:entrada :port` slot defaults to;
6865///   - every future per-Servico renderer the absorption-roadmap
6866///     acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
6867///     CR materializer's per-edge port resolver, the future
6868///     per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
6869///     emitter's per-route bucket key, the future caixa-otel
6870///     collector-pipeline emitter's per-Servico scrape port).
6871///
6872/// Until this lift landed the value `8080` lived at two production-code
6873/// call-sites: the [`default_port`] helper at
6874/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
6875/// and the `.unwrap_or(8080)` literal at
6876/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
6877/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
6878/// resolver). A future Servico-port rebrand — the substrate moving the
6879/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
6880/// gateway grows direct `:80` listeners, to `8443` once the substrate
6881/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
6882/// override the operator pins through a future
6883/// `:placement :default-port` slot — without a coordinated edit on
6884/// both sides would silently emit Servicos listening on one port and
6885/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
6886/// The CNP's apply-time symptom (the policy is admitted but every L4
6887/// flow on the destination Servico's actual port silently drops because
6888/// it doesn't match the whitelisted port) is far from the rebrand
6889/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
6890/// in hubble traces, not in `kubectl describe`. Lifting the literal to
6891/// a shared constant closes the drift footgun structurally — both
6892/// consumers read from the same `u16`, so any rebrand reaches both
6893/// sites by construction.
6894///
6895/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
6896/// per-renderer canonical-K8s-axis constant — the namespace string
6897/// and the canonical Servico port both lived as duplicated literals
6898/// across caixa-core / caixa-mesh / caixa-flux before their respective
6899/// lifts. Same "the typed constant lives in one place" discipline the
6900/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
6901/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
6902/// shared-string axes.
6903///
6904/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
6905pub const DEFAULT_SERVICO_PORT: u16 = 8080;
6906
6907/// Structural floor for the typed `:entrada :port` axis — every
6908/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
6909/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
6910///
6911/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
6912/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
6913/// interprets as "let the kernel pick a free port at bind time", not a
6914/// well-defined destination the substrate's per-`:entrada` Gateway API
6915/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
6916/// carrying `port: 0` degenerates to a nominal-only routing target: the
6917/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
6918/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
6919/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
6920/// at build time rather than at `kubectl apply` time), and the
6921/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
6922/// (caixa-mesh/src/lib.rs:2657 through
6923/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
6924/// [`Entrada::port`] typed value — silently emits a policy whose
6925/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
6926/// actual listener, dropping every L4 flow at the eBPF data plane far
6927/// from the source caixa.lisp with no field naming the port-zero-drift
6928/// root cause.
6929///
6930/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
6931/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
6932/// on the top edge (unlike the peer capped-`u32` `:politicas` /
6933/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
6934/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
6935/// well below `u32::MAX` and therefore need explicit typed caps).
6936///
6937/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
6938/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
6939/// scalar every `(:entrada (:host … :para …))` slot without an explicit
6940/// `:port` inherits through the serde default hook; this constant names
6941/// the accept-set floor every declared port must satisfy. The pair is
6942/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
6943/// substrate's default must satisfy its own accept-set floor by
6944/// construction) — a future rebrand that accidentally moved
6945/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
6946/// negative-cast typo, a per-cluster override the operator pins through
6947/// a future `:placement :default-port` slot that lands out-of-range)
6948/// would silently invalidate the serde-default emission at every
6949/// author-side `(:entrada (:host … :para …))` slot — the compile-time
6950/// invariant pin
6951/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
6952/// closes the drift footgun at caixa-core build time.
6953///
6954/// Lifted as a typed `pub const` (rather than an inline `0` literal at
6955/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
6956/// has exactly one source of truth — the future M4
6957/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
6958/// gateway resolver, the future per-Servico
6959/// `computeunit.trigger.service.port` renderer's per-CR port-value
6960/// validator, and every downstream test-fixture navigator asserting
6961/// the accept-set floor all read from one place. Same shape every
6962/// other typed bracket-floor / bracket-ceiling in this crate carries
6963/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
6964/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
6965/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
6966/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
6967/// [`POLICY_RATE_LIMIT_MAX`]).
6968pub const SERVICO_PORT_MIN: u16 = 1;
6969
6970const fn default_port() -> u16 {
6971    DEFAULT_SERVICO_PORT
6972}
6973
6974// ── the typed view ───────────────────────────────────────────────────
6975
6976/// Typed composition view of the flat Aplicacao slots on
6977/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
6978/// validation + downstream renderer consumption.
6979#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
6980#[serde(rename_all = "camelCase")]
6981pub struct AplicacaoSpec {
6982    pub membros: Vec<Membro>,
6983    pub contratos: Vec<WitContract>,
6984    pub politicas: MeshPolicy,
6985    pub placement: Placement,
6986    pub entrada: Option<Entrada>,
6987}
6988
6989impl AplicacaoSpec {
6990    /// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
6991    /// per-Aplicacao member-list slice-return accessor every
6992    /// per-Aplicacao member-list reader keys off — returns the author-
6993    /// declared `:membros` list verbatim as a `&[Membro]` slice-view
6994    /// over the same backing buffer the raw `self.membros.as_slice()`
6995    /// field access borrows from.
6996    ///
6997    /// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
6998    /// member list — the load-bearing identity of the application graph
6999    /// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
7000    /// multiset). Every per-`:membros` entry pairs a `:caixa` member-
7001    /// caixa name (through the lifted [`Membro::nome`] (4a32abf)
7002    /// accessor) with a `:versao` semver-requirement string (through
7003    /// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
7004    /// and every downstream consumer that fans on the member-set keys
7005    /// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
7006    /// membership-lookup `HashSet<&str>` seed's collect input, the
7007    /// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
7008    /// [`AplicacaoError::NoMembros`] refusal probe, the same method's
7009    /// per-member DNS-1123 / semver-requirement / duplicate-detection
7010    /// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
7011    /// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
7012    /// programs.yaml per-`:membros` fan-out emitter's per-entry
7013    /// mapping-composition loop, the `feira app graph` per-Aplicacao
7014    /// member-count print line and per-member tree traversal,
7015    /// every future wasm-operator (M4) per-Aplicacao CR materializer's
7016    /// per-member `ComputeUnit` fan-out, the future M5 adaptive-
7017    /// placement engine's per-member weight-topology reader).
7018    ///
7019    /// Prior to this lift the `.membros` `Vec<Membro>` was accessed
7020    /// inline at six production sites — the [`AplicacaoSpec::validate`]
7021    /// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
7022    /// [`AplicacaoSpec::validate_membros`]'s pre-flight
7023    /// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
7024    /// probe, the same method's per-member `for m in &self.membros`
7025    /// validate-loop traversal head, the
7026    /// [`AplicacaoSpec::detect_sync_cycles`]'s
7027    /// `for m in &self.membros` adjacency-list seed, the
7028    /// [`caixa_mesh::programs_for_aplicacao`] emitter's
7029    /// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
7030    /// paired with the peer `for m in &spec.membros` per-entry fan-out
7031    /// loop, and the `feira app graph` per-Aplicacao print line's
7032    /// `spec.membros.len()` count formatter argument paired with the
7033    /// peer `for m in &spec.membros` per-member tree traversal — six
7034    /// open-coded field-accesses that expressed no compile-time link
7035    /// back to the typed slot. A future extension of the `:membros`
7036    /// axis to a richer author surface (a per-cluster member-set
7037    /// overlay the operator pins through a future
7038    /// `:membros-overrides` slot the MESH-COMPOSITION §V federation
7039    /// roadmap acknowledges, a per-tenant member-alias table the M4
7040    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
7041    /// CR at admission time, a per-Aplicacao dynamic member-set
7042    /// derivation the future adaptive-placement engine computes from
7043    /// weighted membership topology, a promotion of the plain
7044    /// `Vec<Membro>` to a richer `{static, dynamic}` partition once
7045    /// Orleans-style virtual-actor dynamic-membership comes into typed
7046    /// scope) would have had to be threaded through all six open-coded
7047    /// copies in lockstep or one consumer would silently disagree with
7048    /// the peers on which member-set a given Aplicacao resolves to —
7049    /// the `HashSet<&str>` name-set seed reading the raw slot while
7050    /// the peer `.is_empty()` refusal probe read an operator-resolved
7051    /// slot would silently split the `:contratos` membership-lookup
7052    /// input from the pre-flight-refusal input, a six-consumer split
7053    /// at the validator + programs.yaml emitter + graph printer far
7054    /// from the source `caixa.lisp` with no field naming the member-
7055    /// set-drift root cause. Lifting the resolution rule to a typed
7056    /// method on the substrate primitive means every downstream
7057    /// consumer of the Aplicacao's per-`:membros` member-list surface
7058    /// reaches for exactly one typed dispatch — the resolver's accept-
7059    /// set migrates as a unit on any future axis addition.
7060    ///
7061    /// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
7062    /// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
7063    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
7064    /// static-child-list `Vec`-carry axis, and to the M3
7065    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
7066    /// on the peer per-`:placement` distribution-target-list `Vec`-
7067    /// carry axis. Same "one typed dispatch on the substrate primitive,
7068    /// thin projections at each consumer" discipline. The two peer
7069    /// `Vec`-carry axes still unlifted at the time of this lift —
7070    /// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
7071    /// WIT-typed edge list) and
7072    /// [`crate::UpgradeFromEntry::instructions`]
7073    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
7074    /// — inherit this accessor's discipline as future compounding runs
7075    /// migrate their consumers onto the shared slice-return shape.
7076    /// First `&[T]`-return accessor on the top-level M3 mesh-slot
7077    /// `AplicacaoSpec` type itself, extending the discipline beyond
7078    /// the inner per-slot types ([`crate::Placement`],
7079    /// [`crate::SupervisorSpec`]) onto the outermost typed composition
7080    /// view every renderer consumes. Named `membros()` to match the
7081    /// storage field's name verbatim and the tatara-lisp author-
7082    /// surface term (`:membros`) the field's own docstring already
7083    /// carries; the accessor's identity maps onto the canonical
7084    /// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
7085    /// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
7086    /// every downstream consumer of the member list treats it as a
7087    /// read-only sequence — the slice-view is the narrowest borrow
7088    /// that supports every present + roadmapped consumer
7089    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
7090    /// backing `Vec`'s grow/push/reserve surface that no consumer of
7091    /// the typed view reaches for (the storage-side `Vec` remains
7092    /// reachable through the `pub membros` field for the mutation-
7093    /// carrying serde round-trip and per-test fixture-mutation paths).
7094    #[must_use]
7095    pub const fn membros(&self) -> &[Membro] {
7096        self.membros.as_slice()
7097    }
7098
7099    /// Substrate-canonical per-`:contratos` `Vec<WitContract>`
7100    /// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
7101    /// accessor every per-Aplicacao contract-list reader keys off —
7102    /// returns the author-declared `:contratos` list verbatim as a
7103    /// `&[WitContract]` slice-view over the same backing buffer the raw
7104    /// `self.contratos.as_slice()` field access borrows from.
7105    ///
7106    /// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
7107    /// WIT-typed edge list — the load-bearing set of directed edges
7108    /// on the application graph whose nodes are the `:membros` entries
7109    /// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
7110    /// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
7111    /// six-tuple is the edge identity every downstream duplicate gate
7112    /// keys off). Every per-`:contratos` entry pairs a `:de` source-
7113    /// Servico caller name + a `:para` destination-Servico callee name
7114    /// (through the lifted [`WitContract::source`] +
7115    /// [`WitContract::destination`] (7f0fd43) accessor pair on the
7116    /// caller/callee-Servico axis) with a `:wit` world-reference
7117    /// (through the lifted [`WitContract::world_ref`] (0804823)
7118    /// accessor) and the target-shape-appropriate payload-carrier
7119    /// scalar (through the lifted [`WitContract::endpoint`] (7020470),
7120    /// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
7121    /// (ed22b66) accessor on the per-target-shape payload-carrier
7122    /// axis). Every downstream consumer that fans on the edge-set
7123    /// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
7124    /// name-set / self-edge / target-shape / dedup fan-out loop, the
7125    /// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
7126    /// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
7127    /// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
7128    /// grouping loop, the `feira app graph` per-Aplicacao contract-
7129    /// count print line and per-contract tree traversal, every future
7130    /// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
7131    /// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
7132    /// mesh-policy overlay resolver's per-contract typed-edge weight
7133    /// reader).
7134    ///
7135    /// Prior to this lift the `.contratos` `Vec<WitContract>` was
7136    /// accessed inline at four production sites — the
7137    /// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
7138    /// per-edge validate-loop traversal head (which drives every
7139    /// per-edge name-set membership lookup, self-edge check,
7140    /// target-shape dispatch, and dedup `HashSet` insert), the
7141    /// [`AplicacaoSpec::detect_sync_cycles`]'s
7142    /// `for c in &self.contratos` adjacency-list seed head (which
7143    /// drives every per-edge sync-vs-pub-sub partition and per-edge
7144    /// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
7145    /// emitter's `for c in &spec.contratos` per-`(:de, :para)`
7146    /// `BTreeMap` grouping loop head (which drives every per-CNP
7147    /// fan-out emit), and the `feira app graph` per-Aplicacao print
7148    /// line's `spec.contratos.len()` count formatter argument paired
7149    /// with the peer `for c in &spec.contratos` per-contract tree
7150    /// traversal — four open-coded field-accesses that expressed no
7151    /// compile-time link back to the typed slot. A future extension
7152    /// of the `:contratos` axis to a richer author surface (a
7153    /// per-cluster contract overlay the operator pins through a
7154    /// future `:contratos-overrides` slot the MESH-COMPOSITION §V
7155    /// federation roadmap acknowledges, a per-tenant edge-policy
7156    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
7157    /// materializer resolves per-CR at admission time, a per-edge
7158    /// weight scalar the future adaptive-placement engine reads to
7159    /// bias sync-subgraph routing, a promotion of the plain
7160    /// `Vec<WitContract>` to a richer `{static, dynamic}` partition
7161    /// once virtual-actor-style dynamic-edge composition comes into
7162    /// typed scope) would have had to be threaded through all four
7163    /// open-coded copies in lockstep or one consumer would silently
7164    /// disagree with the peers on which edge-set a given Aplicacao
7165    /// resolves to — the validator's per-edge dedup `HashSet` seed
7166    /// reading the raw slot while the peer sync-cycle adjacency-list
7167    /// seed read an operator-resolved slot would silently split the
7168    /// build-time edge-set gate from the runtime deadlock-detection
7169    /// gate, a four-consumer split at the validator, the cycle
7170    /// detector, the CNP emitter, and the graph printer far from
7171    /// the source `caixa.lisp` with no field naming the edge-set-
7172    /// drift root cause. Lifting the resolution rule to a typed method on the
7173    /// substrate primitive means every downstream consumer of the
7174    /// Aplicacao's per-`:contratos` edge-list surface reaches for
7175    /// exactly one typed dispatch — the resolver's accept-set
7176    /// migrates as a unit on any future axis addition.
7177    ///
7178    /// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
7179    /// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
7180    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
7181    /// static-child-list `Vec`-carry axis, to the M3
7182    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
7183    /// on the peer per-`:placement` distribution-target-list `Vec`-
7184    /// carry axis, and to the immediately-adjacent sibling M3
7185    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
7186    /// the peer per-`:membros` node-list `Vec`-carry axis — the
7187    /// per-`:contratos` edge-list accessor is the natural pair of
7188    /// the per-`:membros` node-list accessor (graph edges over graph
7189    /// nodes; every graph-shaped consumer reads both). Same "one
7190    /// typed dispatch on the substrate primitive, thin projections
7191    /// at each consumer" discipline. The last remaining `Vec`-carry
7192    /// axis still unlifted at the time of this lift —
7193    /// [`crate::UpgradeFromEntry::instructions`]
7194    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction
7195    /// list) — inherits this accessor's discipline as future
7196    /// compounding runs migrate its consumers onto the shared slice-
7197    /// return shape. Second `&[T]`-return accessor on the top-level
7198    /// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
7199    /// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
7200    /// `:contratos` are the two `Vec` fields on the outer typed
7201    /// composition view — `:politicas`, `:placement`, `:entrada` are
7202    /// scalar/option-shaped and already route through their per-slot
7203    /// accessor families). Named `contratos()` to match the storage
7204    /// field's name verbatim and the tatara-lisp author-surface term
7205    /// (`:contratos`) the field's own docstring already carries; the
7206    /// accessor's identity maps onto the canonical MESH-COMPOSITION
7207    /// §III.1 vocabulary the slot's docstring already reaches for.
7208    /// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
7209    /// every downstream consumer of the contract list treats it as a
7210    /// read-only sequence — the slice-view is the narrowest borrow
7211    /// that supports every present + roadmapped consumer
7212    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
7213    /// backing `Vec`'s grow/push/reserve surface that no consumer of
7214    /// the typed view reaches for (the storage-side `Vec` remains
7215    /// reachable through the `pub contratos` field for the mutation-
7216    /// carrying serde round-trip and per-test fixture-mutation paths).
7217    #[must_use]
7218    pub const fn contratos(&self) -> &[WitContract] {
7219        self.contratos.as_slice()
7220    }
7221
7222    /// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
7223    /// per-Aplicacao mesh-policy composite-reference accessor every
7224    /// per-Aplicacao policy-block reader keys off — returns the author-
7225    /// declared `:politicas` composite verbatim as a `&MeshPolicy`
7226    /// reference over the same backing storage the raw `&self.politicas`
7227    /// field access borrows from.
7228    ///
7229    /// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
7230    /// mesh-policy composite — the load-bearing container of every
7231    /// mesh-level operational-policy axis every downstream mesh-artifact
7232    /// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
7233    /// mesh-policy overlay is the single typed surface a
7234    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
7235    /// from). Every per-`:politicas` axis threads through a lifted
7236    /// per-slot accessor on the [`MeshPolicy`] type: the
7237    /// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
7238    /// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
7239    /// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
7240    /// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
7241    /// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
7242    /// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
7243    /// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
7244    /// Envoy-local-rate-limit-mesh token-bucket-declaration composite
7245    /// accessor. Every downstream consumer that reaches for a policy
7246    /// axis first passes through this outer accessor onto the composite
7247    /// and then dispatches onto the per-axis accessor — the two-level
7248    /// dispatch means every per-`:politicas` reader now routes through
7249    /// a typed dispatch on the substrate primitive at both altitudes.
7250    ///
7251    /// Prior to this lift the `.politicas` `MeshPolicy` composite was
7252    /// accessed inline at four production sites — the
7253    /// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
7254    /// &self.politicas;` traversal seed (which drives every per-axis
7255    /// zero-floor + upper-cap + canonical-form bracket dispatch through
7256    /// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
7257    /// `p.rate_limit()` on the axis-level lifted accessors), the
7258    /// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
7259    /// emitter's `spec.politicas.mtls_required()` field-then-accessor
7260    /// chain (which drives every per-`(:de, :para)` CNP
7261    /// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
7262    /// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
7263    /// timeout + retry overlay emitter's paired
7264    /// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
7265    /// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
7266    /// deadline + budget overlay onto the emitted `HTTPRoute`) — four
7267    /// open-coded outer-field accesses that expressed no compile-time
7268    /// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
7269    /// future extension of the `:politicas` outer axis to a richer
7270    /// author surface (a per-cluster policy overlay the operator pins
7271    /// through a future `:politicas-overrides` slot the MESH-COMPOSITION
7272    /// §V federation roadmap acknowledges, a per-tenant policy-alias
7273    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
7274    /// resolves per-CR at admission time, a per-Aplicacao dynamic
7275    /// policy-composite derivation the future adaptive-placement engine
7276    /// computes from a per-cluster load-topology reader, a promotion of
7277    /// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
7278    /// partition once virtual-actor-style dynamic-mesh-policy
7279    /// composition comes into typed scope) would have had to be threaded
7280    /// through all four open-coded copies in lockstep or one consumer
7281    /// would silently disagree with the peers on which mesh-policy
7282    /// composite a given Aplicacao resolves to — the validator's
7283    /// per-axis bracket-dispatch seed reading the raw slot while the
7284    /// peer CNP mTLS-overlay emitter read an operator-resolved slot
7285    /// would silently split the build-time policy-shape gate from the
7286    /// runtime CNP-emission gate, a four-consumer split at the
7287    /// validator, the CNP emitter, and the `HTTPRoute` emitter far from
7288    /// the source `caixa.lisp` with no field naming the policy-drift
7289    /// root cause. Lifting the resolution rule to a typed method on the
7290    /// substrate primitive means every downstream consumer of the
7291    /// Aplicacao's per-`:politicas` mesh-policy composite surface
7292    /// reaches for exactly one typed dispatch — the resolver's accept-
7293    /// set migrates as a unit on any future axis addition.
7294    ///
7295    /// First `&Composite`-return accessor on the top-level M3 mesh-slot
7296    /// `AplicacaoSpec` type itself — sibling to the seed slice-return
7297    /// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
7298    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
7299    /// close the two `Vec`-carry axes on the outer typed composition
7300    /// view; the outer `:politicas` composite-reference axis is the
7301    /// natural pair to the paired outer `Vec`-carry accessors on the
7302    /// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
7303    /// emitter reads all four axes as one unit (graph nodes + graph
7304    /// edges + mesh policy + placement pool). Peer to the same
7305    /// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
7306    /// slot: every M2 `SupervisorSpec`-scoped composite reader
7307    /// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
7308    /// `restart_window`, `children`) already routes through the M2
7309    /// `SupervisorSpec` accessor family — this lift extends the same
7310    /// "one typed dispatch on the substrate primitive at the outer
7311    /// composition altitude" discipline to the M3 mesh-slot
7312    /// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
7313    /// remaining peer outer-composite axes still unlifted at the time
7314    /// of this lift — [`AplicacaoSpec::placement`] (`Placement`
7315    /// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
7316    /// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
7317    /// inherit this accessor's discipline as future compounding runs
7318    /// migrate their consumers onto the shared reference-return shape.
7319    /// Named `politicas()` to match the storage field's name verbatim
7320    /// and the tatara-lisp author-surface term (`:politicas`) the
7321    /// field's own docstring already carries; the accessor's identity
7322    /// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
7323    /// slot's docstring already reaches for. Returns `&MeshPolicy`
7324    /// (not the owning composite by copy or clone) because every
7325    /// downstream consumer of the mesh-policy composite treats it as a
7326    /// read-only per-axis dispatch source — the reference-view is the
7327    /// narrowest borrow that supports every present + roadmapped
7328    /// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
7329    /// emptiness probe) without cloning the composite through every
7330    /// consumer's fast path.
7331    #[must_use]
7332    pub const fn politicas(&self) -> &MeshPolicy {
7333        &self.politicas
7334    }
7335
7336    /// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
7337    /// per-Aplicacao distribution-composite composite-reference accessor
7338    /// every per-Aplicacao placement-block reader keys off — returns the
7339    /// author-declared `:placement` composite verbatim as a `&Placement`
7340    /// reference over the same backing storage the raw `&self.placement`
7341    /// field access borrows from.
7342    ///
7343    /// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
7344    /// distribution composite — the load-bearing container of every
7345    /// where-does-this-Aplicacao-run axis every downstream cluster-artifact
7346    /// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
7347    /// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
7348    /// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
7349    /// hosting-pool identity, §V for the `M3-Adaptive`-compression
7350    /// `:affinity` hint). Every per-`:placement` axis threads through a
7351    /// lifted per-slot accessor on the [`Placement`] type: the
7352    /// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
7353    /// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
7354    /// per-cluster distribution-target slice-return accessor, the
7355    /// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
7356    /// optional-scalar accessor, and the [`Placement::shard_key`]
7357    /// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
7358    /// downstream consumer that reaches for a placement axis first passes
7359    /// through this outer accessor onto the composite and then dispatches
7360    /// onto the per-axis accessor — the two-level dispatch means every
7361    /// per-`:placement` reader now routes through a typed dispatch on the
7362    /// substrate primitive at both altitudes.
7363    ///
7364    /// Prior to this lift the `.placement` `Placement` composite was
7365    /// accessed inline at three production sites — the
7366    /// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
7367    /// seed (six `self.placement.<axis>()` field-then-inner-accessor
7368    /// chains: the pre-flight `.clusters().is_empty()` refusal probe
7369    /// paired with the `.estrategia()` diagnostic-carry copy, the per-
7370    /// cluster `.clusters()` validate-loop traversal head, the per-
7371    /// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
7372    /// non-`Sharded` partition's `.estrategia()` match arm scrutinee
7373    /// paired with the shape-gate cascade's `.shard_key()` /
7374    /// `.estrategia()` diagnostic-carry pair), the
7375    /// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
7376    /// per-entry placement-block emitter's outer
7377    /// `serde_yaml::to_value(&spec.placement)` composite-serialization
7378    /// seed (which fans onto every per-cluster `programs[]` entry as a
7379    /// self-describing distribution overlay the aggregator filters by),
7380    /// and the `feira app graph` per-Aplicacao print line's paired
7381    /// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
7382    /// then-inner-accessor chains (which drive the human-readable
7383    /// distribution summary of the typed Aplicacao view) — three open-
7384    /// coded outer-field accesses that expressed no compile-time link
7385    /// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
7386    /// extension of the `:placement` outer axis to a richer author surface
7387    /// (a per-cluster placement overlay the operator pins through a
7388    /// future `:placement-overrides` slot the MESH-COMPOSITION §V
7389    /// federation roadmap acknowledges, a per-tenant placement-alias
7390    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
7391    /// resolves per-CR at admission time, a per-Aplicacao dynamic
7392    /// placement-composite derivation the future M5 adaptive-placement
7393    /// engine computes from a per-cluster load-topology reader, a
7394    /// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
7395    /// partition once Orleans-style virtual-actor dynamic-placement comes
7396    /// into typed scope) would have had to be threaded through all three
7397    /// open-coded copies in lockstep or one consumer would silently
7398    /// disagree with the peers on which placement composite a given
7399    /// Aplicacao resolves to — the validator's per-axis bracket-dispatch
7400    /// seed reading the raw slot while the peer
7401    /// `programs_for_aplicacao` emitter read an operator-resolved slot
7402    /// would silently split the build-time distribution-shape gate from
7403    /// the runtime programs.yaml distribution-annotation gate, a three-
7404    /// consumer split at the validator, the programs.yaml emitter, and
7405    /// the `feira app graph` printer far from the source `caixa.lisp`
7406    /// with no field naming the placement-drift root cause. Lifting the
7407    /// resolution rule to a typed method on the substrate primitive
7408    /// means every downstream consumer of the Aplicacao's per-
7409    /// `:placement` distribution composite surface reaches for exactly
7410    /// one typed dispatch — the resolver's accept-set migrates as a unit
7411    /// on any future axis addition.
7412    ///
7413    /// Second `&Composite`-return accessor on the top-level M3 mesh-slot
7414    /// `AplicacaoSpec` type itself — sibling to the seed
7415    /// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
7416    /// composite-reference accessor on the peer per-`:politicas` outer-
7417    /// composite axis, and to the paired slice-return accessors
7418    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
7419    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
7420    /// the two `Vec`-carry axes on the outer typed composition view; the
7421    /// outer `:placement` composite-reference axis is the natural pair
7422    /// to the peer `:politicas` composite-reference axis on the two
7423    /// operationally-symmetric M3 mesh slots (`:politicas` carries the
7424    /// how-to-run policy overlay, `:placement` carries the where-to-run
7425    /// distribution composite — every whole-Aplicacao mesh-artifact
7426    /// emitter reads both as one unit). Same "one typed dispatch on the
7427    /// substrate primitive, thin projections at each consumer"
7428    /// discipline the peer per-`:politicas` composite-reference axis
7429    /// already routes through. The one remaining outer-composite axis
7430    /// still unlifted at the time of this lift —
7431    /// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
7432    /// external-gateway composite) — inherits this accessor's discipline
7433    /// as the next compounding run migrates its consumers onto the shared
7434    /// reference-return shape, closing the outer-composite altitude on
7435    /// every M3 mesh-slot axis. Named `placement()` to match the storage
7436    /// field's name verbatim and the tatara-lisp author-surface term
7437    /// (`:placement`) the field's own docstring already carries; the
7438    /// accessor's identity maps onto the canonical MESH-COMPOSITION §II
7439    /// vocabulary the slot's docstring already reaches for. Returns
7440    /// `&Placement` (not the owning composite by copy or clone) because
7441    /// every downstream consumer of the placement composite treats it as
7442    /// a read-only per-axis dispatch source — the reference-view is the
7443    /// narrowest borrow that supports every present + roadmapped consumer
7444    /// (per-axis accessor dispatch, serde composite-serialization) without
7445    /// cloning the composite through every consumer's fast path.
7446    #[must_use]
7447    pub const fn placement(&self) -> &Placement {
7448        &self.placement
7449    }
7450
7451    /// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
7452    /// per-Aplicacao external-gateway composite optional-composite-
7453    /// reference accessor every per-Aplicacao gateway-block reader
7454    /// keys off — returns the author-declared `:entrada` composite
7455    /// verbatim as an `Option<&Entrada>` reference over the same
7456    /// backing storage the raw `self.entrada.as_ref()` field access
7457    /// borrows from, with `None` naming the internal-only mesh shape
7458    /// (the author-omitted `:entrada` slot the K8s Gateway API v1
7459    /// gateway_routes emitter treats as "emit nothing" and the peer
7460    /// `feira app graph` printer treats as "internal-only mesh").
7461    ///
7462    /// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
7463    /// external-gateway composite — the load-bearing container of
7464    /// every does-this-Aplicacao-expose-a-public-endpoint axis every
7465    /// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
7466    /// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
7467    /// hostname axis, §III.4 for the `:para` destination-Servico
7468    /// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
7469    /// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
7470    /// axis threads through a lifted per-slot accessor on the
7471    /// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
7472    /// Gateway-API `Listener.hostname` scalar accessor, the paired
7473    /// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
7474    /// singleton-list resolver, the [`Entrada::destination`] (821a80e)
7475    /// backendRefs destination-Servico scalar accessor, the
7476    /// [`Entrada::resolved_paths`] path-fallback resolver, and the
7477    /// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
7478    /// scalar accessor. Every downstream consumer that reaches for
7479    /// an entrada axis first passes through this outer accessor onto
7480    /// the composite and then dispatches onto the per-axis accessor
7481    /// — the two-level dispatch means every per-`:entrada` reader
7482    /// now routes through a typed dispatch on the substrate primitive
7483    /// at both altitudes.
7484    ///
7485    /// Prior to this lift the `.entrada` `Option<Entrada>` composite
7486    /// was accessed inline at four production sites — the
7487    /// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
7488    /// gate's `if let Some(e) = &self.entrada { … }` traversal head
7489    /// (which drives every per-axis refusal on the composite: the
7490    /// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
7491    /// `EntradaMemberMissing` membership lookup against the
7492    /// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
7493    /// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
7494    /// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
7495    /// per-path shape gate on each entry of `e.paths`), the
7496    /// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
7497    /// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
7498    /// composite-projection seed (which drives the destination-
7499    /// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
7500    /// backendRefs port emitter fans on), the
7501    /// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
7502    /// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
7503    /// early-return seed (which drives the "no `:entrada` ⇒ no
7504    /// external artifacts" partition on the whole-Aplicacao Gateway-
7505    /// API emitter's fan-out), and the `feira app graph` per-
7506    /// Aplicacao print line's `if let Some(e) = &spec.entrada`
7507    /// external-gateway summary emitter (which drives the human-
7508    /// readable `entrada: host → para (paths=…, port=…)` /
7509    /// `entrada: (internal-only mesh)` partition on the typed
7510    /// Aplicacao view) — four open-coded outer-field accesses that
7511    /// expressed no compile-time link back to the typed slot at the
7512    /// [`AplicacaoSpec`] altitude. A future extension of the
7513    /// `:entrada` outer axis to a richer author surface (a
7514    /// multi-`:entrada` list the M4 CR materializer resolves per-CR
7515    /// at admission time so an Aplicacao can expose a public-web +
7516    /// admin-web pair, a per-cluster `:entrada-overrides` slot the
7517    /// MESH-COMPOSITION §V federation roadmap acknowledges so an
7518    /// operator can pin a per-cluster hostname override without
7519    /// re-authoring the `caixa.lisp`, a promotion of the plain
7520    /// `Option<Entrada>` to a richer `{single, multi}` partition once
7521    /// the multi-`:entrada` roadmap lands) would have had to be
7522    /// threaded through all four open-coded copies in lockstep or one
7523    /// consumer would silently disagree with the peers on which
7524    /// entrada composite a given Aplicacao resolves to — the
7525    /// validator's per-axis bracket-dispatch seed reading the raw
7526    /// slot while the peer `gateway_routes` emitter read an
7527    /// operator-resolved slot would silently split the build-time
7528    /// gateway-shape gate from the runtime Gateway + HTTPRoute
7529    /// emission gate, a four-consumer split at the validator, the
7530    /// `port_for_destination` L4-port resolver, the `gateway_routes`
7531    /// emitter, and the `feira app graph` printer far from the
7532    /// source `caixa.lisp` with no field naming the entrada-drift
7533    /// root cause. Lifting the resolution rule to a typed method on
7534    /// the substrate primitive means every downstream consumer of
7535    /// the Aplicacao's per-`:entrada` external-gateway composite
7536    /// surface reaches for exactly one typed dispatch — the
7537    /// resolver's accept-set migrates as a unit on any future axis
7538    /// addition.
7539    ///
7540    /// Third and final `&Composite`-return accessor on the top-level
7541    /// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
7542    /// unlifted outer-composite axis on the outer typed composition
7543    /// view, sibling to the seed [`AplicacaoSpec::politicas`]
7544    /// (534dc21) `&MeshPolicy` mesh-policy composite-reference
7545    /// accessor on the per-`:politicas` outer-composite axis and to
7546    /// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
7547    /// distribution-composite composite-reference accessor on the
7548    /// per-`:placement` outer-composite axis; extends the outer-
7549    /// composite reference-return discipline the two peers already
7550    /// route through onto the last unlifted per-`AplicacaoSpec`
7551    /// outer-composite axis. The `:entrada` outer-composite axis is
7552    /// the natural pair to the two peer outer-composite axes on the
7553    /// three operationally-symmetric M3 mesh-slot outer composites
7554    /// (`:politicas` carries the how-to-run policy overlay,
7555    /// `:placement` carries the where-to-run distribution composite,
7556    /// `:entrada` carries the who-can-reach-it external-gateway
7557    /// composite — every whole-Aplicacao mesh-artifact emitter reads
7558    /// all three as one unit). Same "one typed dispatch on the
7559    /// substrate primitive, thin projections at each consumer"
7560    /// discipline the peer outer-composite axes already route through.
7561    /// Named `entrada()` to match the storage field's name verbatim
7562    /// and the tatara-lisp author-surface term (`:entrada`) the
7563    /// field's own docstring already carries; the accessor's
7564    /// identity maps onto the canonical MESH-COMPOSITION §III.4
7565    /// vocabulary the slot's docstring already reaches for. Returns
7566    /// `Option<&Entrada>` (not the owning composite by copy or
7567    /// clone) because every downstream consumer of the entrada
7568    /// composite treats it as a read-only per-axis dispatch source
7569    /// — the reference-view is the narrowest borrow that supports
7570    /// every present + roadmapped consumer (per-axis accessor
7571    /// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
7572    /// port-fallback projection, early-return partition on the
7573    /// `None` arm) without cloning the composite through every
7574    /// consumer's fast path. The `Option` half of the return-type
7575    /// preserves the load-bearing "author-omitted `:entrada` ⇒
7576    /// internal-only mesh" partition (not a default composite the
7577    /// downstream must reject on emptiness) — the accessor projects
7578    /// the raw `Option<Entrada>` slot's presence bit through the
7579    /// reference-return unchanged.
7580    #[must_use]
7581    pub const fn entrada(&self) -> Option<&Entrada> {
7582        self.entrada.as_ref()
7583    }
7584
7585    /// Validate the typed shape:
7586    ///   - `:membros` is non-empty; every entry has a non-empty `:caixa`
7587    ///     and a non-empty `:versao`; no two entries share the same
7588    ///     `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
7589    ///     not a multiset)
7590    ///   - every `:contratos` :de + :para must be in `:membros`
7591    ///   - no `:contratos` edge is a self-edge (`:de == :para`) — a
7592    ///     contract is an inter-Servico edge, so a Servico contracting
7593    ///     with itself is a build error under every WIT shape
7594    ///     (MESH-COMPOSITION §III.1)
7595    ///   - no two `:contratos` entries agree on
7596    ///     `(de, para, wit, endpoint, subject, slot)` — the typed-graph
7597    ///     edges are a set, not a multiset (peer of the `:membros` /
7598    ///     `:placement :clusters` / `:entrada :paths` duplicate gates)
7599    ///   - `:entrada :para` must be in `:membros`
7600    ///   - `:placement Sharded` must declare `:shard-key` (non-empty);
7601    ///     `:placement Replicated`/`SingleNode` must NOT declare
7602    ///     `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
7603    ///     consumes it (MESH-COMPOSITION §II.4), and the typed partition
7604    ///     between strategy and shard-key is symmetric: every validated
7605    ///     `Placement` has `shard_key.is_some()` iff `estrategia ==
7606    ///     Sharded`
7607    ///   - every `:placement` strategy must declare ≥1 `:clusters` entry —
7608    ///     `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
7609    ///     the shard pool (MESH-COMPOSITION §III.1)
7610    ///   - every `:clusters` entry is non-empty and unique
7611    ///   - `:placement :affinity`, when set, is non-empty
7612    ///   - the synchronous-`:contratos` subgraph is acyclic
7613    ///     (MESH-COMPOSITION §III.3)
7614    ///   - every declared `:politicas` value is operationally meaningful
7615    ///     (zero timeout, zero retries, zero breaker thresholds, zero rate
7616    ///     limit are all build errors — MESH-COMPOSITION §V CSE invariants;
7617    ///     omit the field instead to express "no policy on this axis")
7618    pub fn validate(&self) -> Result<(), AplicacaoError> {
7619        self.validate_membros()?;
7620
7621        // `:contratos` per-slot gate — folds both structural axes on the
7622        // slot into one substrate primitive: the per-entry cascade (shape
7623        // + membership + self-loop + `:wit` emptiness + WIT-shape ↔
7624        // target + whole-edge dedup) and the cross-edge sync-cycle axis
7625        // ([`AplicacaoSpec::detect_sync_cycles`], MESH-COMPOSITION §III.3
7626        // — pub-sub edges excluded, "acyclic by construction"). Same
7627        // fold-per-axis-plus-cross-axis discipline the sibling
7628        // [`AplicacaoSpec::validate_politicas`] per-slot gate carries via
7629        // [`MeshPolicy::validate`] (f03a154 / 90a6f87), extended here
7630        // onto `:contratos` so every future consumer of the slot (the M4
7631        // admission webhook re-checking `:contratos` after a per-edge
7632        // patch, the per-edge policy resolver MESH-COMPOSITION §III.2 #3
7633        // acknowledges) reaches *both* structural axes through one call.
7634        self.validate_contratos()?;
7635
7636        self.validate_entrada()?;
7637
7638        self.validate_placement()?;
7639
7640        self.validate_politicas()?;
7641
7642        Ok(())
7643    }
7644
7645    /// The `:membros` graph-node name set — the membership oracle every
7646    /// per-Aplicacao name-reference axis resolves against.
7647    ///
7648    /// Three per-Aplicacao axes carry a Servico-name *reference* rather
7649    /// than a Servico-name *declaration*: `:contratos :de`, `:contratos
7650    /// :para`, and `:entrada :para`. Each must resolve to a declared
7651    /// `:membros :caixa` (MESH-COMPOSITION §III.1 — the typed edges and
7652    /// the external gateway both address graph nodes, so a reference to
7653    /// a node the graph does not contain is a build error). All three
7654    /// resolve against *this* set, so the set's construction is the one
7655    /// shared substrate primitive underneath the whole reference-
7656    /// resolution surface.
7657    ///
7658    /// Lifted out of [`AplicacaoSpec::validate`]'s inline
7659    /// `self.membros().iter().map(Membro::nome).collect()` builder so
7660    /// the two per-slot gates that consume it — the per-`:contratos`
7661    /// membership arms still inline at `validate` and the lifted
7662    /// [`AplicacaoSpec::validate_entrada`] below — reach the same
7663    /// oracle through one dispatch rather than each open-coding the
7664    /// projection. Every future consumer on the same axis (the M4
7665    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
7666    /// reference resolver, the per-`:contratos`-edge `:politicas`
7667    /// override MESH-COMPOSITION §III.2 #3 acknowledges — which
7668    /// resolves an edge's endpoints against the same membership set
7669    /// before it can key a per-edge policy off them) inherits the
7670    /// projection through the same call, so a future rebrand of the
7671    /// node-identity axis (a namespace-qualified member name the CR
7672    /// materializer applies per-CR, the `:membros :nome-suffix`
7673    /// overlay §III.2 acknowledges) lands at exactly one place rather
7674    /// than at every reference-resolution site in lockstep. Peer of
7675    /// the sibling per-slot substrate primitives
7676    /// [`MeshPolicy::validate`] (f03a154) and
7677    /// [`WitContract::identity`] on their own axes.
7678    fn membro_names(&self) -> std::collections::HashSet<&str> {
7679        self.membros().iter().map(Membro::nome).collect()
7680    }
7681
7682    /// Reject `:contratos` entries whose endpoints are malformed,
7683    /// reference a Servico outside the graph, self-loop, carry an
7684    /// empty `:wit` shape, duplicate a prior entry on the six-axis
7685    /// identity key, or close a synchronous-edge cycle in the
7686    /// resulting typed graph.
7687    ///
7688    /// The `:contratos` slot is the typed inter-Servico edge set
7689    /// (MESH-COMPOSITION §III.1): each entry is a WIT-typed directed
7690    /// edge whose `:de` / `:para` reference two distinct members and
7691    /// whose `:wit` picks the payload shape the paired L4/L7 renderer
7692    /// (caixa-mesh's per-`(:de, :para)` `CiliumNetworkPolicy` +
7693    /// per-HTTP `HTTPRoute`) fans out on.
7694    ///
7695    /// Two structural axes on the slot are folded into this per-slot
7696    /// gate: the per-entry axis (six per-edge arms, listed below) and
7697    /// the cross-edge synchronous-cycle axis (MESH-COMPOSITION §III.3,
7698    /// dispatched to [`AplicacaoSpec::detect_sync_cycles`] after the
7699    /// per-entry cascade). Same
7700    /// per-axis-plus-cross-axis-fold-into-one-per-slot-gate discipline
7701    /// the sibling [`AplicacaoSpec::validate_politicas`] per-slot gate
7702    /// carries via [`MeshPolicy::validate`] (f03a154 / 90a6f87) on the
7703    /// `:politicas` slot, extended here onto `:contratos`.
7704    ///
7705    /// Six per-entry axes are gated first, in the canonical
7706    /// edge-direction order the paired diagnostics already encode
7707    /// (per-arm value shape before graph-membership lookup; structural
7708    /// self-edge before payload-shape target dispatch; whole-edge dedup
7709    /// last):
7710    ///
7711    ///   - per-arm `:de` / `:para` value shape via
7712    ///     [`validate_contrato_caixa`] (empty + DNS-1123 grammar),
7713    ///     `:de` before `:para`;
7714    ///   - per-edge graph-membership against the
7715    ///     [`AplicacaoSpec::membro_names`] oracle via
7716    ///     [`WitContract::require_endpoints_in`] (folds the twin
7717    ///     `:de` / `:para` arms onto one substrate-primitive
7718    ///     dispatch), `:de` before `:para`;
7719    ///   - structural self-edge via [`WitContract::is_self_loop`]
7720    ///     (caller-equals-callee under any WIT shape);
7721    ///   - `:wit` emptiness ([`AplicacaoError::EmptyWit`]);
7722    ///   - WIT shape ↔ target consistency via [`WitContract::target`]
7723    ///     (the four `WitTarget` arms — `Http` / `PubSub` / `Store` /
7724    ///     `Capability` — each carry their own required payload field);
7725    ///   - six-axis whole-edge dedup via [`WitContract::identity`]
7726    ///     ([`ContratoIdentity`]'s `(de, para, wit, endpoint, subject,
7727    ///     slot)` tuple).
7728    ///
7729    /// One cross-edge axis is gated last, after the per-entry cascade
7730    /// completes cleanly:
7731    ///
7732    ///   - synchronous-edge cycle detection via
7733    ///     [`AplicacaoSpec::detect_sync_cycles`] (iterative DFS with
7734    ///     three-coloring over the sync-only subgraph, pub-sub edges
7735    ///     skipped per MESH-COMPOSITION §III.3 —
7736    ///     [`AplicacaoError::ContratoCycle`]). Runs *after* the
7737    ///     per-entry cascade so a per-entry defect surfaces through its
7738    ///     narrower shape/membership/dedup arm before the cross-edge
7739    ///     cycle diagnostic, matching the pre-fold `validate`-side
7740    ///     dispatch ordering (`validate_contratos()? →
7741    ///     detect_sync_cycles()?`).
7742    ///
7743    /// Lifted out of [`AplicacaoSpec::validate`]'s inline `let mut
7744    /// seen_contracts = …; for c in self.contratos() { … }` block onto
7745    /// a named per-slot gate, closing the last unlifted per-slot gate
7746    /// on the M3 mesh-slot family. Every peer slot already carries the
7747    /// shape ([`AplicacaoSpec::validate_membros`],
7748    /// [`AplicacaoSpec::validate_entrada`],
7749    /// [`AplicacaoSpec::validate_placement`],
7750    /// [`AplicacaoSpec::validate_politicas`]).
7751    ///
7752    /// Self-contained on `&self` — it resolves its own membership
7753    /// oracle through [`AplicacaoSpec::membro_names`] rather than
7754    /// borrowing one threaded down from `validate`, and runs its own
7755    /// cross-edge cycle probe rather than deferring the axis to an
7756    /// outer dispatch — so a future consumer that re-validates *one*
7757    /// slot against a mutated spec (the M4 admission webhook
7758    /// re-checking `:contratos` after a per-`(:de, :para)` edge patch
7759    /// without re-walking `:membros` / `:entrada` / `:placement` /
7760    /// `:politicas`, or the M4 per-edge policy resolver
7761    /// MESH-COMPOSITION §III.2 #3 acknowledges — which resolves an
7762    /// effective per-edge [`MeshPolicy`] and must re-check the edge's
7763    /// own identity closure *and* the sync-cycle invariant before it
7764    /// can key a per-edge override off the endpoint tuple) reaches
7765    /// *both* structural axes on the slot through one call, exactly as
7766    /// [`AplicacaoSpec::validate_politicas`] reaches both per-axis and
7767    /// cross-axis surfaces on `:politicas` through
7768    /// [`MeshPolicy::validate`].
7769    fn validate_contratos(&self) -> Result<(), AplicacaoError> {
7770        let names = self.membro_names();
7771
7772        // Identity key for the typed-edge duplicate gate below: every
7773        // field that distinguishes one contract from another. Two
7774        // entries that agree on all six are *the same edge declared
7775        // twice*, the typed-graph analogue of duplicate `:membros` /
7776        // `:placement :clusters` / `:entrada :paths` entries (which
7777        // are already build errors at this layer). Rejecting it at the
7778        // validate gate closes a renderer-side footgun: caixa-mesh's
7779        // `cilium_network_policies` keys each emitted policy by
7780        // `<aplicacao>-<de>-to-<para>`, so two contracts with identical
7781        // (de, para) and identical payload would land as two K8s
7782        // objects with colliding `metadata.name`, rejected at apply
7783        // time far from the source caixa.lisp.
7784        let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
7785            std::collections::HashSet::new();
7786        for c in self.contratos() {
7787            // Per-axis value-shape gate on every `:contratos` name
7788            // reference, before any graph-membership lookup. Empty +
7789            // DNS-1123-malformed `:de`/`:para` values silently fell
7790            // through to `ContratoMemberMissing` at the lookup arm
7791            // because every `:membros :caixa` is shape-validated
7792            // (3f9d7a0), so the `names` set structurally cannot contain
7793            // an empty / malformed string and the membership-lookup
7794            // diagnostic always misframed the root cause as
7795            // "this caixa is not in `:membros`". The shape gate runs
7796            // ahead of the lookup so structurally-impossible-to-match
7797            // inputs route through the narrower self-locating
7798            // diagnostic, preserving the legitimate "well-shaped
7799            // phantom reference" arm. `:de` runs before `:para` per
7800            // the canonical edge-direction order the existing
7801            // membership lookup, self-edge check, target dispatch,
7802            // and diagnostic strings already use.
7803            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
7804            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
7805            // Per-edge graph-membership gate on the twin `:de` / `:para`
7806            // arms — folded onto the substrate-primitive dispatch
7807            // [`WitContract::require_endpoints_in`] so every per-edge
7808            // consumer of the endpoint-resolution axis (this per-slot
7809            // gate at build time, the M4 admission webhook re-checking
7810            // one edge after a per-`(:de, :para)` patch, the per-edge
7811            // `:politicas` override MESH-COMPOSITION §III.2 #3
7812            // acknowledges) reaches the axis through one call rather
7813            // than re-inlining the twin `if !names.contains(...)`
7814            // cascade. `:de` fires before `:para` inside the primitive,
7815            // preserving byte-equal diagnostic ordering with the
7816            // pre-lift inline cascade.
7817            c.require_endpoints_in(&names)?;
7818            // A `:contratos` entry is an *inter*-Servico contract
7819            // (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
7820            // typed edge between two distinct graph nodes. An edge whose
7821            // `:de` equals its `:para` is a Servico contracting with
7822            // itself — a degenerate edge under every WIT shape. Firing
7823            // the gate before the `:wit`/`target()` shape checks means
7824            // the structural "this edge can't exist" error precedes the
7825            // narrower payload-shape diagnostics, and shape-agnostically
7826            // covers all four `WitTarget` arms (HTTP / Store / Capability
7827            // / PubSub) at one point. Peer of the duplicate-`:contratos`
7828            // / duplicate-`:membros` set gates: both reject a structurally
7829            // ill-formed graph at the typed surface, before the renderer
7830            // emits a K8s object that fails or no-ops far from the source
7831            // caixa.lisp.
7832            if c.is_self_loop() {
7833                return Err(AplicacaoError::ContratoSelfLoop {
7834                    caixa: c.source().to_string(),
7835                    wit: c.world_ref().to_string(),
7836                });
7837            }
7838            if c.world_ref().is_empty() {
7839                return Err(AplicacaoError::empty_wit(c.edge_pair()));
7840            }
7841            // Shape ↔ target consistency — surfaces "HTTP wit without
7842            // :endpoint", "NATS wit with :endpoint set", etc. as named
7843            // build errors instead of silent renderer drops. Threaded
7844            // through the duplicate-edge diagnostic below (via
7845            // [`WitTarget::label`]) so the "which typed target arm did
7846            // the duplicate carry" question is answered by the typed
7847            // enum's variant discriminator, not by re-probing the raw
7848            // `Option<String>` payload fields.
7849            let target_view = c.target()?;
7850            // Contract identity: (de, para, wit, endpoint, subject, slot).
7851            // Two contracts that match on all six are the same typed edge
7852            // declared twice — author error, not a legitimate variant of
7853            // "same caller-callee pair, different payload" (e.g.
7854            // cart→catalog at /products vs /search), which keeps distinct
7855            // identity keys via the differing endpoint payloads.
7856            let key = c.identity();
7857            crate::render::insert_first_seen(&mut seen_contracts, key, || {
7858                let (de, para, wit) = c.edge_triple();
7859                AplicacaoError::ContratoDuplicate {
7860                    de,
7861                    para,
7862                    wit,
7863                    target: target_view.label(),
7864                }
7865            })?;
7866        }
7867
7868        // Cross-edge cycle axis on the `:contratos` slot — folded into
7869        // the per-slot gate so the two structural axes on `:contratos`
7870        // (per-entry shape + membership + dedup above; cross-edge sync-
7871        // cycle detection here) reach every consumer through one call.
7872        // Same discipline the sibling per-slot compound gate
7873        // [`MeshPolicy::validate`] (f03a154) established on `:politicas`
7874        // — one named per-slot gate that folds *both* per-axis and
7875        // cross-axis surfaces on the same slot onto one substrate
7876        // primitive — extended here onto `:contratos`, closing the last
7877        // per-slot-axis-family that lived split across `validate` (the
7878        // per-entry `validate_contratos` half here and the cross-edge
7879        // `detect_sync_cycles` call the sibling below at `validate`
7880        // dispatched separately).
7881        //
7882        // Runs after the per-entry cascade so a per-entry defect (empty
7883        // arm, unknown endpoint, self-loop, empty `:wit`, WIT-shape ↔
7884        // target inconsistency, whole-edge duplicate) surfaces first
7885        // through its narrower [`AplicacaoError`] arm before the cross-
7886        // edge cycle diagnostic. This matches the pre-lift ordering the
7887        // `validate`-side dispatch used verbatim (`self.validate_contratos()?
7888        // → self.detect_sync_cycles()?`) — the cycle detector was
7889        // already the second `:contratos`-axis gate in the dispatch,
7890        // just at the outer altitude; the fold moves it under the same
7891        // named per-slot gate without reshaping the diagnostic order.
7892        self.detect_sync_cycles()?;
7893
7894        Ok(())
7895    }
7896
7897    /// Reject `:entrada` values that are operationally meaningless,
7898    /// structurally malformed, or reference a Servico outside the
7899    /// graph.
7900    ///
7901    /// The `:entrada` slot is the Aplicacao's single external ingress
7902    /// (MESH-COMPOSITION §III.1): `:host` + `:port` become a K8s
7903    /// Gateway API v1 `Listener`, `:paths` become the paired
7904    /// `HTTPRoute`'s `matches[].path.value` entries, and `:para` names
7905    /// the member the route forwards to. Omitting the slot entirely is
7906    /// the internal-only-mesh partition — an Aplicacao with no external
7907    /// surface — so the `None` arm is a clean pass, not a refusal.
7908    ///
7909    /// Five axes are gated here, in the canonical order the paired
7910    /// diagnostics already encode (reference-resolution before value
7911    /// shape, per-axis emptiness before per-axis grammar):
7912    ///
7913    ///   - `:para` — DNS-1123 value shape, then membership against the
7914    ///     [`AplicacaoSpec::membro_names`] oracle;
7915    ///   - `:host` — emptiness, then the Gateway API hostname grammar;
7916    ///   - `:port` — the [`SERVICO_PORT_MIN`] structural floor;
7917    ///   - `:paths` — per-entry emptiness, leading-`/`, the Gateway API
7918    ///     path grammar, and set-not-multiset uniqueness.
7919    ///
7920    /// Lifted out of [`AplicacaoSpec::validate`]'s inline `if let
7921    /// Some(e) = self.entrada() { … }` block onto a named per-slot
7922    /// gate, the shape the three peer M3 mesh slots already carry
7923    /// ([`AplicacaoSpec::validate_membros`],
7924    /// [`AplicacaoSpec::validate_placement`],
7925    /// [`AplicacaoSpec::validate_politicas`]). Self-contained on
7926    /// `&self` — it resolves its own membership oracle through
7927    /// [`AplicacaoSpec::membro_names`] rather than borrowing one
7928    /// threaded down from `validate` — so a future consumer that
7929    /// re-validates *one* slot against a mutated spec (the M4 admission
7930    /// webhook re-checking `:entrada` after a gateway-host patch
7931    /// without re-walking the whole `:contratos` graph) reaches the
7932    /// axis through one call, exactly as `detect_sync_cycles` is
7933    /// already self-contained for the M4 per-edge policy resolver.
7934    fn validate_entrada(&self) -> Result<(), AplicacaoError> {
7935        let names = self.membro_names();
7936        if let Some(e) = self.entrada() {
7937            // Route the per-`:entrada` composite-reference read
7938            // through the lifted [`AplicacaoSpec::entrada`] accessor
7939            // rather than the raw `&self.entrada` field access — the
7940            // shape-and-membership gate's traversal head is now the
7941            // canonical read-side surface every per-Aplicacao entrada
7942            // consumer routes through, closing the fourth of four
7943            // open-coded outer-field accesses on the per-`:entrada`
7944            // outer-composite axis.
7945            //
7946            // Shape gate on `:entrada :para` runs ahead of the
7947            // membership lookup. Every `:membros :caixa` past
7948            // `validate_membro_caixa` is a valid DNS-1123 label
7949            // (3f9d7a0), so the `names` set structurally cannot
7950            // contain an empty / malformed string and the membership-
7951            // lookup diagnostic always misframed the root cause as
7952            // "this caixa is not in `:membros`". The shape gate
7953            // routes structurally-impossible-to-match inputs through
7954            // the narrower self-locating diagnostic, preserving the
7955            // legitimate "well-shaped phantom reference" arm — the
7956            // same trajectory the peer `:membros :caixa` (3f9d7a0),
7957            // `:placement :clusters` (6c8c00b), and `:contratos :de`
7958            // / `:para` (8d5af6b) axes already follow. This closes
7959            // the fourth and last Aplicacao-level Servico-name
7960            // reference axis on the canonical DNS-1123 floor.
7961            // Route the per-`:entrada :para` byte-string reads through
7962            // the lifted [`Entrada::destination`] accessor rather than
7963            // the raw `e.para` field access — the three
7964            // per-`AplicacaoSpec::validate` `:entrada :para` consumers
7965            // (shape-gate `validate_entrada_para` arg, membership
7966            // lookup, `EntradaMemberMissing` diagnostic carry) now key
7967            // off exactly one typed dispatch on the substrate
7968            // primitive, closing the last unlifted per-`:entrada :para`
7969            // raw-field-access axis on the M3 mesh-slot validator.
7970            // The `.destination().to_string()` at the diagnostic site
7971            // is byte-identical to `.para.clone()` — pinned by the
7972            // sibling `destination_returns_entrada_para_byte_equal` +
7973            // `destination_borrows_from_entrada_para_storage` accessor
7974            // tests — so a future rebrand of the underlying `:para`
7975            // storage (a lift from `String` to a typed
7976            // `ServicoName(String)` newtype, a per-Aplicacao interning
7977            // arena the M4 CR materializer authors, a
7978            // `smol_str::SmolStr` inline-buffer swap) flows through
7979            // the accessor's one body without a coordinated
7980            // per-consumer rewrite across the M3 mesh validator.
7981            validate_entrada_para(e.destination())?;
7982            if !names.contains(e.destination()) {
7983                return Err(AplicacaoError::EntradaMemberMissing {
7984                    para: e.destination().to_string(),
7985                });
7986            }
7987            // Route the per-`:entrada :host` byte-string reads through
7988            // the lifted [`Entrada::hostname`] accessor rather than
7989            // the raw `e.host` field access — the emptiness gate and
7990            // the shape-gate `validate_entrada_host` arg now key off
7991            // exactly one typed dispatch on the substrate primitive,
7992            // closing the last unlifted per-`:entrada :host` raw-
7993            // field-access axis on the M3 mesh-slot validator. Peer
7994            // of the sibling per-`:entrada :para` convergence above
7995            // and pinned by the existing
7996            // `hostname_returns_entrada_host_byte_equal` +
7997            // `hostnames_returns_singleton_of_hostname_accessor`
7998            // accessor tests, so any future
7999            // Gateway-API-shaped host renormalization (a wildcard-
8000            // label lift, a trailing-`.` FQDN substitution, an IDNA
8001            // Punycode round-trip the SNI fan-out overlay authors)
8002            // flows through the accessor's one body without a
8003            // coordinated per-consumer rewrite across the M3 mesh
8004            // validator.
8005            if e.hostname().is_empty() {
8006                return Err(AplicacaoError::EmptyEntradaHost);
8007            }
8008            // The `:host` lands verbatim as a K8s Gateway API v1
8009            // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
8010            // both apiserver-validated against the same restrictive
8011            // pattern: lowercase RFC 1123 DNS subdomain, optional
8012            // single leading wildcard label (`*.`), max length 253,
8013            // per-label max length 63, no IP literals, no scheme,
8014            // no port. Until this gate landed `validate()` only
8015            // refused the empty string (`EmptyEntradaHost`); a
8016            // structurally invalid hostname (`"https://example.com"`,
8017            // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
8018            // `"_underscored.example.com"`, `"FOO.example.com"`,
8019            // `"checkout.quero.cloud."`) silently passed validate
8020            // and the apiserver `field is invalid` error surfaced at
8021            // `kubectl apply` time, far from the source caixa.lisp.
8022            // Lifting the gate to caixa-build time mirrors the
8023            // `:entrada :paths` value-shape trajectory (eb3456d) and
8024            // closes the last unstructured `:entrada` axis.
8025            validate_entrada_host(e.hostname())?;
8026            // Structural-floor gate on `:entrada :port`: every
8027            // validated `Entrada::port` past this gate lies in
8028            // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
8029            // type-inferred ceiling closes the top edge, so no companion
8030            // upper-cap arm is needed here — unlike the peer capped-
8031            // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
8032            // `require_positive_bounded_u32` bracket covers both edges).
8033            // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
8034            // accept-set-floor const rather than the prior inline
8035            // `if e.port == 0` byte-check so a future rebrand of the
8036            // accept-set floor (a hypothetical unprivileged-only
8037            // migration lifting the floor to `1024`, a per-cluster
8038            // scoping the operator pins through a future
8039            // `:placement :port-floor` slot as the M4 typed-slot
8040            // trajectory adds it, the future
8041            // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
8042            // per-Aplicacao gateway resolver reaching for the same
8043            // floor) is a one-line edit on the canonical
8044            // [`SERVICO_PORT_MIN`] declaration, not a coordinated
8045            // rewrite across the emit site + the pin test + every
8046            // future per-target renderer the substrate adds.
8047            if e.port() < SERVICO_PORT_MIN {
8048                return Err(AplicacaoError::EntradaPortZero);
8049            }
8050            // Each `:entrada :paths` entry becomes a K8s Gateway API
8051            // HTTPRoute `matches[].path.value`. The Gateway API rejects
8052            // values that don't start with `/` for `type: PathPrefix`,
8053            // and an empty value is meaningless. Surface those as build
8054            // errors (MESH-COMPOSITION §III.3) rather than apply-time
8055            // failures. Empty `:paths` itself is fine — caixa-mesh
8056            // falls back to a single `/` catch-all.
8057            let mut seen = std::collections::HashSet::new();
8058            // Route the per-entry value-shape gate's traversal head
8059            // through the lifted [`Entrada::paths`] slice accessor
8060            // rather than the raw `&e.paths` field access — the
8061            // per-Aplicacao `:entrada :paths` validate loop now keys
8062            // off the canonical raw-slot surface every downstream
8063            // per-`:entrada` path-list consumer (the sibling
8064            // [`Entrada::resolved_paths`] fallback-applying resolver
8065            // internal reads, `feira app graph`'s per-Aplicacao entrada
8066            // summary line's `{:?}` Debug print) routes through, so any
8067            // future rebrand on the typed slot's raw-slot reader lands
8068            // at exactly one place. Same convergence discipline as the
8069            // sibling [`Placement::clusters`] (a6e18d7) reader-site
8070            // convergences on the peer M3 mesh-slot `Vec<String>`-carry
8071            // axis.
8072            for p in e.paths() {
8073                if p.is_empty() {
8074                    return Err(AplicacaoError::EntradaPathEmpty);
8075                }
8076                if !p.starts_with('/') {
8077                    return Err(AplicacaoError::EntradaPathNotAbsolute { path: p.clone() });
8078                }
8079                // Per-entry value-shape gate: the path lands verbatim
8080                // as a K8s Gateway API HTTPRoute `matches[].path.value`
8081                // (caixa-mesh/src/lib.rs:498), apiserver-validated
8082                // against `maxLength: 1024` + the Gateway API webhook's
8083                // path-grammar rules (no `//`, no `/./`, no `/../`, no
8084                // query/fragment separators, no whitespace, no control
8085                // characters, no non-ASCII bytes). Until this gate
8086                // landed `validate` only refused the empty string and
8087                // missing-leading-slash (eb3456d); a structurally
8088                // invalid path (`"/api?q=1"`, `"/api#frag"`,
8089                // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
8090                // 1025-byte URL-shaped slug) silently passed validate
8091                // and the failure surfaced at `kubectl apply` time as
8092                // a Gateway API webhook rejection, far from the source
8093                // caixa.lisp, with no field naming the offending
8094                // `:paths` entry. Lifting the gate to caixa-build time
8095                // mirrors the `:entrada :host` value-shape trajectory
8096                // (c7d05ec) on the sibling axis — every author surface
8097                // that emits a Gateway API field now matches the
8098                // apiserver's accepted set at validate time.
8099                validate_entrada_path(p)?;
8100                crate::render::insert_first_seen(&mut seen, p.as_str(), || {
8101                    AplicacaoError::EntradaPathDuplicate { path: p.clone() }
8102                })?;
8103            }
8104        }
8105
8106        Ok(())
8107    }
8108
8109    /// Reject `:membros` values that are operationally meaningless. The
8110    /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
8111    /// every entry names a Servico that participates in the Aplicacao,
8112    /// and the rendered programs.yaml fan-out emits one entry per
8113    /// `:membros`. Three authoring footguns are closed here:
8114    ///
8115    ///   - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
8116    ///     a `programs:` entry whose `name:` is the empty string, which
8117    ///     downstream `lareira-fleet-programs` rejects at template time
8118    ///     with a non-localized error;
8119    ///   - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
8120    ///     an empty semver constraint, so the failure surfaces far from
8121    ///     the source caixa.lisp;
8122    ///   - duplicate `:caixa` names — two entries with the same name
8123    ///     produce duplicate programs.yaml entries (one silently
8124    ///     overwrites the other in the cluster's HelmRelease values), and
8125    ///     contract membership lookups against `:contratos` collapse the
8126    ///     two onto one node, masking authoring mistakes.
8127    ///
8128    /// Same value-shape discipline as `:placement :clusters` (where empty
8129    /// + duplicate cluster names are rejected) and `:entrada :paths`
8130    /// (where empty + duplicate path entries are rejected). Lifting these
8131    /// invariants to the typed surface mirrors the MESH-COMPOSITION
8132    /// §III.3 promise that the `:membros` set — the load-bearing identity
8133    /// of the application graph — is well-formed by construction.
8134    fn validate_membros(&self) -> Result<(), AplicacaoError> {
8135        if self.membros().is_empty() {
8136            return Err(AplicacaoError::NoMembros);
8137        }
8138        let mut seen = std::collections::HashSet::new();
8139        for m in self.membros() {
8140            // Every emitted cluster artifact's `metadata.name` derives
8141            // from a `:membros :caixa` value verbatim — the rendered
8142            // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
8143            // the [`crate::LABEL_PROGRAM`] label value on every CNP
8144            // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
8145            // 272), the composed `CiliumNetworkPolicy` `metadata.name`
8146            // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
8147            // `metadata.name` when the member is the `:entrada :para`
8148            // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
8149            // schema enforces the DNS-1123 label rule on admission;
8150            // a structurally invalid member name (`"Cart"`, `"my_cart"`,
8151            // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
8152            // mistaken-identity slug) silently passes the prior empty-/
8153            // duplicate-only gate and the failure surfaces at `kubectl
8154            // apply` time as a `metadata.name: Invalid value` rejection,
8155            // far from the source caixa.lisp, with no field naming the
8156            // offending `:membros` entry. Lifting the gate to caixa-build
8157            // time mirrors the `:entrada :host` value-shape trajectory
8158            // (c7d05ec) on the peer axis — every author surface that
8159            // emits a K8s name now matches the apiserver's accepted set
8160            // at validate time.
8161            validate_membro_caixa(m.nome())?;
8162            // The author surface for `:versao` is the same Cargo-shaped
8163            // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
8164            // `"*"`) every `:deps` entry carries — and the lacre pipeline
8165            // resolves both axes through the same
8166            // [`crate::version::parse_requirement`] entry-point. The
8167            // shared [`crate::render::require_valid_versao_requirement`]
8168            // helper brackets the empty-first + parse cascade both peer
8169            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
8170            // [`crate::SupervisorSpec::validate`] on `:children :versao`)
8171            // route through, so drift between the three axes' accepted
8172            // requirement sets is structurally impossible and the parse-
8173            // side no-op the empty-first arm closes (semver's empty
8174            // parse yields an implicit `*`) lives in exactly one
8175            // predicate.
8176            crate::render::require_valid_versao_requirement(
8177                m.versao_requirement(),
8178                || AplicacaoError::MembroVersaoEmpty {
8179                    caixa: m.nome().to_string(),
8180                },
8181                |reason| AplicacaoError::MembroVersaoInvalid {
8182                    caixa: m.nome().to_string(),
8183                    versao: m.versao_requirement().to_string(),
8184                    reason,
8185                },
8186            )?;
8187            crate::render::insert_first_seen(&mut seen, m.nome(), || {
8188                AplicacaoError::MembroDuplicate {
8189                    caixa: m.nome().to_string(),
8190                }
8191            })?;
8192        }
8193        Ok(())
8194    }
8195
8196    /// Reject `:placement` values that are operationally meaningless or
8197    /// internally contradictory. Each strategy variant has the same
8198    /// invariants on `:clusters` (non-empty list, non-empty unique
8199    /// entries) — the §III.1 author surface is uniform on this axis,
8200    /// even though the *meaning* of the list differs by strategy
8201    /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
8202    /// shard pool).
8203    ///
8204    /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
8205    /// are the same authoring footgun closed for `:politicas` zero
8206    /// values and `:entrada` empty paths: the field is *declared* but
8207    /// carries no meaning, so downstream renderers either skip it
8208    /// silently (cluster-fanout drops the empty entry, no diagnostic)
8209    /// or apply it literally and fail at admission time. Lifting both
8210    /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
8211    /// violation is a build error" promise.
8212    ///
8213    /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
8214    /// is required exactly when `:estrategia Sharded` (hash-keyed
8215    /// distribution, Akka cluster-sharding convention, §II.4) and
8216    /// refused on `:estrategia Replicated`/`SingleNode` (where no
8217    /// hash-keyed routing axis consumes it). The partition closes the
8218    /// "I think I configured sharding" footgun where an author writes
8219    /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
8220    /// the typed slot's value silently vanishes at the renderer layer
8221    /// — every validated `Placement` past this call satisfies
8222    /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
8223    fn validate_placement(&self) -> Result<(), AplicacaoError> {
8224        // Every strategy needs at least one named cluster: `Replicated`
8225        // and `SingleNode` use the list as hosting/takeover candidates
8226        // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
8227        // §II.1), while `Sharded` uses it as the shard pool
8228        // (Akka cluster-sharding convention — §II.4). An empty list is
8229        // meaningless under any of the three.
8230        //
8231        // Route the paired pre-flight `.is_empty()` refusal probe and
8232        // the per-cluster validate loop's traversal head through the
8233        // lifted [`Placement::clusters`] slice-return accessor rather
8234        // than the raw `self.placement.clusters` field access — the
8235        // two production consumers of the per-`:placement` cluster-
8236        // pool `Vec`-carry now key off exactly one typed dispatch on
8237        // the substrate primitive, so any future rebrand on the axis
8238        // (a per-tenant cluster-pool overlay the operator pins through
8239        // a future `:placement :clusters-overrides` slot, a per-
8240        // Aplicacao dynamic cluster-pool derivation the future M5
8241        // adaptive-placement engine computes from `:affinity` weights)
8242        // migrates as a single caixa-core edit rather than a
8243        // coordinated rewrite of the paired arms — sibling of the
8244        // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
8245        // arm migration on the per-`:supervisor` static-child-list
8246        // `Vec`-carry axis.
8247        //
8248        // Route the per-`:placement` outer-composite reference read
8249        // through the lifted [`AplicacaoSpec::placement`] outer accessor
8250        // rather than the raw `&self.placement` field access — the
8251        // per-axis bracket-dispatch fan-out below (`p.clusters()`,
8252        // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
8253        // axis-level lifted accessor family) now routes through the
8254        // substrate-primitive typed dispatch at the outer composition
8255        // altitude, the same shape the peer caixa-mesh
8256        // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
8257        // and the sibling `feira app graph` per-Aplicacao print line
8258        // now key off after this accessor lift.
8259        let p = self.placement();
8260        if p.clusters().is_empty() {
8261            return Err(AplicacaoError::PlacementWithoutClusters {
8262                estrategia: p.estrategia(),
8263            });
8264        }
8265        let mut seen = std::collections::HashSet::new();
8266        for c in p.clusters() {
8267            // Per-entry value-shape gate: the cluster name lands in
8268            // every K8s context / `lareira-fleet-programs` aggregator
8269            // filter / future M4 CR materializer's per-cluster axis
8270            // a validated `:clusters` entry passes through, each
8271            // enforcing the DNS-1123 label rule on admission. Same
8272            // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
8273            // on the peer name axis — both axes' validated values
8274            // are guaranteed-accepted by the apiserver without
8275            // re-validation at any downstream renderer or admission
8276            // layer.
8277            validate_placement_cluster(c)?;
8278            crate::render::insert_first_seen(&mut seen, c.as_str(), || {
8279                AplicacaoError::PlacementClusterDuplicate { cluster: c.clone() }
8280            })?;
8281        }
8282        // Route the per-`:placement :affinity` per-hint value-shape
8283        // gate through the typed [`Placement::affinity`] accessor rather
8284        // than the raw `&self.placement.affinity` field access — the
8285        // sole open-coded field-access site on the per-`:placement`
8286        // M3-Adaptive-compression-hint axis the accessor lift now owns.
8287        // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
8288        // the accessor's `Option<&str>` return type;
8289        // [`validate_placement_affinity`]'s `&str` parameter accepts
8290        // the narrower borrow without a re-allocation, so the routing
8291        // change is byte-for-byte in the pass arm and remains
8292        // byte-for-byte in every failure diagnostic
8293        // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
8294        // String` field is populated inside
8295        // [`validate_placement_affinity`] via the peer `.to_string()`
8296        // path on the same borrowed slice). Peer of the sibling
8297        // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
8298        // routing through [`Placement::shard_key`] at the caixa-core
8299        // site above — extends the "read `:placement` optional-scalars
8300        // through the typed accessor" discipline to the second
8301        // `Option<String>`-shape slot on the M3 mesh-slot family.
8302        //
8303        // Per-hint value-shape gate: the `:affinity` value lands
8304        // verbatim in the M3 Adaptive compression overlay
8305        // (caixa-mesh's `placement.affinity` emission) and every
8306        // future M4 placement-engine routing axis keying off the
8307        // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
8308        // selector — each enforces the DNS-1123 label rule on
8309        // admission. Same typed-shape trajectory as `:placement
8310        // :clusters` (6c8c00b) on the sibling slot and the four
8311        // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
8312        // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
8313        // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
8314        // on the Aplicacao surface to land on the canonical
8315        // [`crate::render::is_dns_1123_label`] floor.
8316        if let Some(a) = p.affinity() {
8317            validate_placement_affinity(a)?;
8318        }
8319        match p.estrategia() {
8320            // Route the `Sharded`-arm shape-gate cascade through the
8321            // typed [`Placement::shard_key`] accessor rather than the
8322            // raw `&self.placement.shard_key` field access — one of the
8323            // two open-coded field-access sites on the per-`:placement`
8324            // Akka-cluster-sharding-key axis the accessor lift now
8325            // owns. The `Some(k)`-bound `k` narrows from `&String` to
8326            // `&str` under the accessor's `Option<&str>` return type;
8327            // `str::is_empty` and [`validate_placement_shard_key`]'s
8328            // `&str` parameter both accept the narrower borrow without
8329            // a re-allocation.
8330            PlacementStrategy::Sharded => match p.shard_key() {
8331                None => return Err(AplicacaoError::ShardedWithoutKey),
8332                Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
8333                // Per-axis value-shape gate on the Akka-cluster-sharding
8334                // `:shard-key` extractor expression. The shape gate runs
8335                // after the more self-locating `ShardedKeyEmpty` arm so
8336                // a `:shard-key ""` surfaces the narrower empty
8337                // diagnostic first; every non-empty `:shard-key` past
8338                // this call is guaranteed to be a printable-ASCII
8339                // single-token reference the future M4 Akka-style
8340                // cluster-sharding reconciler can hash without
8341                // re-validating at the runtime layer. Mirrors the
8342                // payload-axis shape gates on the peer `:contratos`
8343                // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
8344                // 63e18a0 / c4213a4) — each lifts the runtime parser's
8345                // intersection-floor to a caixa-build-time gate.
8346                Some(k) => validate_placement_shard_key(k)?,
8347            },
8348            // `:shard-key` is the Akka-cluster-sharding axis
8349            // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
8350            // across the cluster pool. `Replicated` (active-active across
8351            // every named cluster) and `SingleNode` (Erlang/OTP
8352            // distributed-app takeover/failover, §II.1) have no hash-keyed
8353            // routing axis to consume the slot; downstream renderers
8354            // (caixa-mesh's `placement.shardKey` overlay at
8355            // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
8356            // sharding reconciler) ignore `:shard-key` outside the
8357            // `Sharded` arm by construction. Until this gate landed an
8358            // author who wrote `:placement (:estrategia Replicated
8359            // :shard-key "tenantId")` (an off-by-one strategy typo, a
8360            // copy-paste from a Sharded sibling caixa, the "I think I
8361            // configured sharding" footgun) silently passed validate and
8362            // the typed slot's value vanished at the renderer layer with
8363            // no diagnostic — the canonical "declared-but-inert" footgun
8364            // the empty-:affinity / empty-shard-key / zero-:politicas /
8365            // empty-:contratos-target gates already close on every other
8366            // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
8367            // Lifting the rejection to a build-time gate closes the
8368            // Sharded ↔ non-Sharded partition over the typed
8369            // `:placement` slot: every validated `Placement` past this
8370            // call has `shard_key.is_some()` iff `estrategia ==
8371            // Sharded`, structurally — the future Akka reconciler can
8372            // reach for `placement.shard_key` knowing it's `Some` exactly
8373            // when the strategy consumes it, without re-deriving the
8374            // partition from inline strategy probes.
8375            PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
8376                // Route the non-`Sharded`-arm declared-but-inert refusal
8377                // through the typed [`Placement::shard_key`] accessor —
8378                // the second of the two open-coded field-access sites the
8379                // accessor lift now owns. The `Some(k)`-bound `k` narrows
8380                // from `&String` to `&str`; the `AplicacaoError::
8381                // ShardKeyOnNonSharded { shard_key: String }` diagnostic
8382                // materializes the owned `String` via `k.to_string()`
8383                // (peer to the sibling per-Membro `String`-carry sites
8384                // 4127bb6 routed through `m.nome().to_string()` /
8385                // `m.versao_requirement().to_string()`), so the whole
8386                // `Sharded` ↔ non-`Sharded` partition on the
8387                // `:shard-key` axis now flows through the same typed
8388                // dispatch as the sibling `Sharded`-arm shape gate.
8389                if let Some(k) = p.shard_key() {
8390                    return Err(AplicacaoError::ShardKeyOnNonSharded {
8391                        estrategia: p.estrategia(),
8392                        shard_key: k.to_string(),
8393                    });
8394                }
8395            }
8396        }
8397        Ok(())
8398    }
8399
8400    /// Reject `:politicas` values that are operationally meaningless.
8401    /// Each axis is optional — omitting it expresses "no policy on this
8402    /// axis". Carrying a *zero* value for a declared axis is the bug
8403    /// this function rejects: zero is either
8404    ///
8405    ///   - re-interpreted as "infinite" by downstream proxies (Envoy's
8406    ///     `RouteAction.timeout = 0s` disables the timeout entirely),
8407    ///     directly contradicting MESH-COMPOSITION §V CSE invariant
8408    ///     "every Aplicacao declares :politicas :timeout (no infinite
8409    ///     blocking)", or
8410    ///   - a renderer footgun (a 0-failure circuit breaker trips on the
8411    ///     first call; a 0-rate rate-limit denies every request).
8412    ///
8413    /// Lifting these "0 means the opposite of what you think" idioms to
8414    /// the typed Aplicacao surface as build errors mirrors the §III.3
8415    /// promise that contract drift, capability leaks, and cycles are all
8416    /// build errors — not runtime surprises.
8417    fn validate_politicas(&self) -> Result<(), AplicacaoError> {
8418        // Route the whole per-axis + cross-axis `:politicas` cascade
8419        // through the substrate primitive [`MeshPolicy::validate`],
8420        // which folds all six per-axis brackets (`:timeout`,
8421        // `:retries`, `:circuit-breaker :max-failures`,
8422        // `:circuit-breaker :window`, `:rate-limit` rate, `:rate-limit`
8423        // window-canonical-form) plus the compound cross-axis fold
8424        // [`MeshPolicy::first_cross_axis_violation`] into one
8425        // `Result<(), AplicacaoError>` return. The whole per-axis-
8426        // brackets + cross-axis-fold cascade collapses to one call, and
8427        // every future [`MeshPolicy`] consumer (the future M4
8428        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
8429        // admission webhook, the per-`:contratos`-edge `:politicas`
8430        // override MESH-COMPOSITION §III.2 #3 acknowledges — the last
8431        // of which resolves an *effective* per-edge [`MeshPolicy`] and
8432        // must emit *the same* diagnostic on the same input as `feira
8433        // build`) reaches through the same substrate-primitive dispatch
8434        // rather than re-inlining the four-per-axis + one-cross-axis
8435        // cascade in lockstep with this validate gate. Same trajectory
8436        // the peer per-kind compound entry gates
8437        // [`crate::render::require_aplicacao_view`] (7242d45 / 3aefefb),
8438        // [`crate::render::require_supervisor_view`] (8d8a5c3),
8439        // [`crate::render::require_v0_servico_shape`] (per-Caixa
8440        // layout axis) and the sibling compound cross-axis fold
8441        // [`MeshPolicy::first_cross_axis_violation`] (90a6f87) carry —
8442        // extended here onto the per-slot compound entry gate that
8443        // folds both per-axis + cross-axis surfaces on the M3
8444        // mesh-slot family.
8445        self.politicas().validate()
8446    }
8447
8448    /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
8449    /// A synchronous edge is any contract whose typed [`WitTarget`] is
8450    /// `Http`, `Store`, or `Capability` — the caller blocks on the
8451    /// callee, so a cycle would deadlock at runtime. Pub-sub edges
8452    /// (`WitTarget::PubSub`) are skipped: an event publisher does not
8453    /// block on its subscribers, so they can never close a sync loop.
8454    ///
8455    /// Iterative DFS with three-coloring; the reported cycle is the
8456    /// path of caixa names traversed from the back-edge target around
8457    /// to itself, in declaration order. Adjacency lists and DFS roots
8458    /// are visited in `BTreeMap` key order so the diagnostic is
8459    /// deterministic across runs.
8460    ///
8461    /// Now the cross-edge axis of the per-slot compound gate
8462    /// [`AplicacaoSpec::validate_contratos`] — invoked at the tail of
8463    /// the per-entry cascade rather than at the outer
8464    /// [`AplicacaoSpec::validate`] dispatch, so both structural axes on
8465    /// `:contratos` (per-entry shape + membership + dedup; cross-edge
8466    /// sync-cycle) reach every consumer through one call. Kept
8467    /// standalone (rather than inlined) so consumers that want only the
8468    /// cross-edge axis (the M4 per-edge policy resolver
8469    /// MESH-COMPOSITION §III.2 #3 acknowledges, whose per-edge patch
8470    /// mutates one `:contratos` entry and needs to re-probe *just* the
8471    /// cycle invariant against the post-patch adjacency without
8472    /// re-running the per-entry shape/membership/dedup cascade the
8473    /// per-entry-only [M4 admission] fast path already covered) still
8474    /// have a self-contained entry point on the cycle axis.
8475    fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
8476        use std::collections::{BTreeMap, BTreeSet};
8477
8478        #[derive(Clone, Copy, PartialEq, Eq)]
8479        enum Mark {
8480            White,
8481            Gray,
8482            Black,
8483        }
8484
8485        let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
8486        for m in self.membros() {
8487            adj.entry(m.nome()).or_default();
8488        }
8489        for c in self.contratos() {
8490            // target() was already called by validate(); re-running here
8491            // keeps detect_sync_cycles self-contained for callers that
8492            // reuse it (M4 per-edge policy resolver) without revalidating.
8493            //
8494            // The pub-sub-arm check routes through the lifted
8495            // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
8496            // arm-discriminator predicate rather than a raw `matches!(…,
8497            // WitTarget::PubSub { .. })` on the variant so a future
8498            // rebrand on the axis (an M4 per-edge WIT registry split of
8499            // [`WitTarget::PubSub`] into shape-specific peers, a
8500            // per-consumer rename that the accept-set already carries)
8501            // reaches this call site through the derive rather than a
8502            // scattered per-arm `matches!` rewrite — same
8503            // `IsVariant`-derived-arm-discriminator discipline the
8504            // peer closed-set typed enums ([`crate::CaixaKind`] via
8505            // f5bba80, [`PlacementStrategy`] via 766ec63,
8506            // [`crate::supervisor::RestartStrategy`] +
8507            // [`crate::supervisor::RestartPolicy`],
8508            // [`crate::upgrade::UpgradeInstruction`] via 915a934)
8509            // already route through on the substrate's other typed-enum
8510            // arm-discriminator axes.
8511            if c.target()?.is_pubsub() {
8512                continue;
8513            }
8514            adj.entry(c.source()).or_default().insert(c.destination());
8515        }
8516
8517        let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
8518        let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
8519
8520        // Stable DFS root order — BTreeMap iteration is sorted by key.
8521        let roots: Vec<&str> = adj.keys().copied().collect();
8522
8523        // Frame: (node, sorted-neighbours snapshot, next-edge index).
8524        for root in roots {
8525            if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
8526                continue;
8527            }
8528            let root_neighbors: Vec<&str> = adj
8529                .get(root)
8530                .map(|s| s.iter().copied().collect())
8531                .unwrap_or_default();
8532            let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
8533            color.insert(root, Mark::Gray);
8534
8535            loop {
8536                // Read+advance the top frame in one borrow scope so we
8537                // can later mutate the stack (push/pop) without holding
8538                // a borrow across.
8539                let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
8540                    let node = top.0;
8541                    if top.2 >= top.1.len() {
8542                        (node, None)
8543                    } else {
8544                        let nxt = top.1[top.2];
8545                        top.2 += 1;
8546                        (node, Some(nxt))
8547                    }
8548                });
8549                let Some((node, nxt_opt)) = step else { break };
8550                let Some(nxt) = nxt_opt else {
8551                    color.insert(node, Mark::Black);
8552                    stack.pop();
8553                    continue;
8554                };
8555                let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
8556                match nxt_color {
8557                    Mark::Gray => {
8558                        // Reconstruct the cycle from `node` back through
8559                        // the parent chain to `nxt`, then close.
8560                        let mut cycle = Vec::new();
8561                        let mut cur = node;
8562                        cycle.push(cur.to_string());
8563                        while cur != nxt {
8564                            match parent.get(cur).copied() {
8565                                Some(p) => {
8566                                    cur = p;
8567                                    cycle.push(cur.to_string());
8568                                }
8569                                None => break,
8570                            }
8571                        }
8572                        cycle.reverse();
8573                        cycle.push(nxt.to_string());
8574                        return Err(AplicacaoError::ContratoCycle { cycle });
8575                    }
8576                    Mark::White => {
8577                        parent.insert(nxt, node);
8578                        color.insert(nxt, Mark::Gray);
8579                        let nxt_neighbors: Vec<&str> = adj
8580                            .get(nxt)
8581                            .map(|s| s.iter().copied().collect())
8582                            .unwrap_or_default();
8583                        stack.push((nxt, nxt_neighbors, 0));
8584                    }
8585                    Mark::Black => {}
8586                }
8587            }
8588        }
8589        Ok(())
8590    }
8591
8592    /// Substrate-canonical destination-facing TCP port every emitted
8593    /// per-Aplicacao artifact must key `destination`-shaped port axes
8594    /// off. Returns the typed `:entrada :port` scalar when this
8595    /// Aplicacao's `:entrada` block names `destination` under its
8596    /// `:para` axis (the destination Servico *is* the ingress apex, so
8597    /// the substrate honors the author-declared listener port
8598    /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
8599    /// fallback otherwise (every non-apex destination — the internal
8600    /// mesh Servicos `:contratos` reach across, the future per-edge
8601    /// policy resolver's per-destination probe targets, the
8602    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
8603    /// L4 port resolver — reads the same substrate-canonical port floor
8604    /// by construction).
8605    ///
8606    /// Prior to this lift the "if :entrada matches this destination use
8607    /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
8608    /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
8609    /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
8610    /// prior to this lift), with no typed method on the substrate primitive
8611    /// that named the rule. A future per-destination port axis addition
8612    /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
8613    /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
8614    /// per-Servico listener ports land, a per-cluster override the operator
8615    /// pins through a future `:placement :default-port` slot — would have
8616    /// to be threaded through every renderer's inline cascade in lockstep
8617    /// or one consumer would silently disagree on which port a given
8618    /// destination Servico's ingress lands at. Lifting the rule to a
8619    /// typed method on the substrate primitive means the M4 CR
8620    /// materializer, the future per-edge policy resolver, and every
8621    /// downstream test-fixture navigator reach for exactly one typed
8622    /// dispatch — the resolver's accept-set moves as a unit on any
8623    /// future axis addition.
8624    ///
8625    /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
8626    /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
8627    /// the typed primitive, thin projections at each consumer"
8628    /// discipline lifts on the sibling `:contratos` payload / `:politicas
8629    /// :rate-limit` unit-suffix axes; extends the discipline onto the
8630    /// destination-facing port-resolution axis every per-Aplicacao
8631    /// L4-fallback renderer consumes.
8632    #[must_use]
8633    pub fn port_for_destination(&self, destination: &str) -> u16 {
8634        // Route the per-`:entrada` composite-reference read through
8635        // the lifted [`AplicacaoSpec::entrada`] accessor rather than
8636        // the raw `self.entrada.as_ref()` field access — the
8637        // per-destination L4-port fallback resolver's composite-
8638        // projection seed is now the canonical read-side surface
8639        // every per-Aplicacao entrada consumer routes through, peer
8640        // of the sibling `validate` per-`:entrada` shape-and-
8641        // membership gate migration on the same outer-composite
8642        // axis.
8643        // Route the per-`:entrada` apex-destination membership probe
8644        // through the lifted [`Entrada::destination`] accessor rather
8645        // than the raw `e.para == destination` field access — the last
8646        // un-lifted `.para` production-code read site on the per-
8647        // `:entrada` `:para` axis, sibling to the four caixa-core
8648        // consumer sites the peer 15ddd8c converge already routed
8649        // through the accessor (the three
8650        // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
8651        // membership gate sites: the `validate_entrada_para` DNS-1123
8652        // shape gate, the per-`:membros` membership lookup, and the
8653        // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
8654        // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
8655        // `entrada.para`-projection converge at
8656        // caixa-core/src/render.rs (the `gateway_api_http_route_name`
8657        // route-name projection site). Prior to this converge the
8658        // `port_for_destination` resolver was the solitary consumer
8659        // bypassing the typed dispatch on the `.para` axis — the two
8660        // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
8661        // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
8662        // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
8663        // reach through the same accessor family compose with this
8664        // resolver at the emit boundary via the apex-identity
8665        // invariant `spec.port_for_destination(entrada.destination())
8666        // == entrada.port` the sibling
8667        // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
8668        // pin pins across four permutations. A future extension of the
8669        // `:entrada :para` axis to a richer author surface (a per-
8670        // cluster alias overlay the operator pins through a future
8671        // `:placement`-scoped slot, a namespace-qualified rewrite the
8672        // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
8673        // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
8674        // §III.2 acknowledges) that lands on the accessor would silently
8675        // disagree between this resolver and the two `caixa-mesh` emit
8676        // sites — an author-declared `:para "cart"` value the accessor
8677        // rewrote to `"cart-v2"` under a future canary arm would leave
8678        // the resolver's membership arm falling through to
8679        // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
8680        // `.para`) while the peer emit-site consumers landed on the
8681        // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
8682        // silently disagreed on which destination port a given typed
8683        // `:entrada` resolves to at cluster-apply time. Pinned by the
8684        // drift-detection test
8685        // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
8686        // below.
8687        self.entrada()
8688            .filter(|e| e.destination() == destination)
8689            .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
8690    }
8691}
8692
8693/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
8694/// entry may name the Aplicacao's own `:nome`.
8695///
8696/// An Aplicacao that lists itself as a member is a degenerate self-edge in
8697/// the typed graph — the application graph is a DAG rooted at the Aplicacao
8698/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
8699/// Servicos that compose the app; an Aplicacao is never its own constituent),
8700/// and the lacre pipeline's closure-resolution would otherwise be handed a
8701/// node that is its own parent: a one-node cycle it either rejects far from
8702/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
8703/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
8704/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
8705/// label + lacre closure root), a member whose `:caixa` equals the
8706/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
8707/// peer.
8708///
8709/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
8710/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
8711/// gate `validate_upgrade_from_against_versao` and the supervision-tree
8712/// self-parent gate `crate::supervisor::validate_no_self_supervision`
8713/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
8714/// not a tree/mesh edge" discipline, here on the second typed-graph axis
8715/// (the Aplicacao :membros set; the supervision-tree :children list was the
8716/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
8717/// every validated Supervisor's children are distinct from its `:nome`,
8718/// every validated Aplicacao's membros are distinct from its `:nome`. The
8719/// transitive consequence is that `:entrada :para` and `:contratos`
8720/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
8721/// name the Aplicacao itself, without re-deriving the partition.
8722pub fn validate_no_self_membership(
8723    membros: &[Membro],
8724    parent_nome: &str,
8725) -> Result<(), AplicacaoError> {
8726    for m in membros {
8727        if m.nome() == parent_nome {
8728            return Err(AplicacaoError::MembroIsSelfAplicacao {
8729                caixa: parent_nome.to_string(),
8730            });
8731        }
8732    }
8733    Ok(())
8734}
8735
8736#[derive(Debug, Error, PartialEq, Eq)]
8737pub enum AplicacaoError {
8738    #[error("Aplicacao must declare at least one :membros entry")]
8739    NoMembros,
8740    #[error(
8741        ":membros entry has empty :caixa (every member must name a Servico; \
8742         omit the entry instead of carrying an empty name)"
8743    )]
8744    MembroCaixaEmpty,
8745    #[error(
8746        ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
8747         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
8748         name / label value the member name lands in; use a lowercase \
8749         alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
8750    )]
8751    MembroCaixaInvalid { caixa: String, reason: String },
8752    #[error(
8753        ":membros entry {caixa:?} has empty :versao (every member must pin a \
8754         semver constraint that resolves through the lacre pipeline)"
8755    )]
8756    MembroVersaoEmpty { caixa: String },
8757    #[error(
8758        ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
8759         requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
8760         `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
8761         carries; the lacre pipeline resolves both through the same parser)"
8762    )]
8763    MembroVersaoInvalid {
8764        caixa: String,
8765        versao: String,
8766        reason: String,
8767    },
8768    #[error(
8769        ":membros entry {caixa:?} appears more than once (the graph node set \
8770         is a set, not a multiset; duplicate members produce duplicate \
8771         programs.yaml entries and ambiguous :contratos membership lookups)"
8772    )]
8773    MembroDuplicate { caixa: String },
8774    #[error(
8775        "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
8776         never its own constituent Servico (the application graph is a DAG rooted \
8777         at the Aplicacao; :membros names the *other* caixas that compose the \
8778         app, not the app itself). Since every :nome is a globally-unique \
8779         substrate identity, a member naming the Aplicacao's own :nome is a \
8780         one-node lacre-closure recursion, not a coincidentally-named peer; \
8781         drop the self-referential :membros entry or rename it to the actual \
8782         constituent caixa."
8783    )]
8784    MembroIsSelfAplicacao { caixa: String },
8785    #[error(
8786        "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
8787         caixa declared in :membros; omit the contract or fill the {slot} field with a \
8788         member name)"
8789    )]
8790    ContratoCaixaEmpty { slot: &'static str },
8791    #[error(
8792        "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
8793         :contratos {slot} value names a member of :membros, which is itself a \
8794         DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
8795         object the member name lands in — Service, Pod, identity-based Cilium \
8796         selector; use a lowercase alphanumeric + hyphen identifier like \
8797         `\"checkout\"` or `\"cart-v2\"`)"
8798    )]
8799    ContratoCaixaInvalid {
8800        slot: &'static str,
8801        caixa: String,
8802        reason: String,
8803    },
8804    #[error("contrato references caixa {caixa:?} not declared in :membros")]
8805    ContratoMemberMissing { caixa: String },
8806    #[error(
8807        "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
8808         entry is an inter-Servico contract whose :de and :para must name distinct \
8809         :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
8810         the contract, or point :para at the member it actually calls)"
8811    )]
8812    ContratoSelfLoop { caixa: String, wit: String },
8813    #[error("contrato {de:?} → {para:?} has empty :wit")]
8814    EmptyWit { de: String, para: String },
8815    #[error(
8816        "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
8817         {reason} (the substrate dispatches `:wit` values on the canonical \
8818         lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
8819         `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
8820         demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
8821         kebab-case identifier per segment)"
8822    )]
8823    ContratoWitInvalid {
8824        de: String,
8825        para: String,
8826        wit: String,
8827        reason: String,
8828    },
8829    #[error(
8830        ":entrada :para is empty (every :entrada must route to a caixa declared in \
8831         :membros; fill the :para field with a member name)"
8832    )]
8833    EntradaParaEmpty,
8834    #[error(
8835        ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
8836         :entrada :para value names a member of :membros, which is itself a DNS-1123 \
8837         label per the K8s apiserver's `metadata.name` rule on every object the \
8838         member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
8839         Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
8840         `\"checkout\"` or `\"cart-v2\"`)"
8841    )]
8842    EntradaParaInvalid { para: String, reason: String },
8843    #[error(":entrada routes to caixa {para:?} not declared in :membros")]
8844    EntradaMemberMissing { para: String },
8845    #[error(":entrada must declare a non-empty :host")]
8846    EmptyEntradaHost,
8847    #[error(
8848        ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
8849         (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
8850         `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
8851         like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
8852    )]
8853    EntradaHostInvalid { host: String, reason: String },
8854    #[error(":entrada :port must be in 1..=65535, got 0")]
8855    EntradaPortZero,
8856    #[error(":entrada :paths entry is empty (use the empty list to match all)")]
8857    EntradaPathEmpty,
8858    #[error(
8859        ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
8860    )]
8861    EntradaPathNotAbsolute { path: String },
8862    #[error(
8863        ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
8864         value: {reason} (the K8s apiserver enforces the same shape on \
8865         `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
8866         single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
8867         requires percent-encoding `%XX` for non-ASCII and whitespace)"
8868    )]
8869    EntradaPathInvalid { path: String, reason: String },
8870    #[error(":entrada :paths entry {path:?} appears more than once")]
8871    EntradaPathDuplicate { path: String },
8872    #[error(
8873        ":placement {estrategia} requires at least one :clusters entry \
8874         (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
8875    )]
8876    PlacementWithoutClusters { estrategia: PlacementStrategy },
8877    #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
8878    PlacementClusterEmpty,
8879    #[error(
8880        ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
8881         (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
8882         in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
8883         future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
8884         — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
8885         identifier like `\"rio\"` or `\"mar-east\"`)"
8886    )]
8887    PlacementClusterInvalid { cluster: String, reason: String },
8888    #[error(":placement :clusters entry {cluster:?} appears more than once")]
8889    PlacementClusterDuplicate { cluster: String },
8890    #[error(
8891        ":placement :affinity must be non-empty when set (omit :affinity to express \
8892         `no placement hint`)"
8893    )]
8894    PlacementAffinityEmpty,
8895    #[error(
8896        ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
8897         (placement hints land verbatim in the M3 Adaptive compression overlay's \
8898         `placement.affinity` field and in every future M4 placement-engine routing \
8899         axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
8900         selector — both enforce the DNS-1123 label rule on admission; use a \
8901         lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
8902         `\"low-latency\"`, or `\"anti-affinity\"`)"
8903    )]
8904    PlacementAffinityInvalid { affinity: String, reason: String },
8905    #[error(":placement Sharded requires :shard-key")]
8906    ShardedWithoutKey,
8907    #[error(
8908        ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
8909         hashes every entity onto the same shard, defeating sharding entirely)"
8910    )]
8911    ShardedKeyEmpty,
8912    #[error(
8913        ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
8914         entity-id extractor expression: {reason} (the future M4 Akka-style \
8915         cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
8916         as a single-token property reference and hashes the extracted entity ID \
8917         to compute shard placement; use a printable-ASCII extractor expression \
8918         like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
8919         `\"${{tenant}}\"`)"
8920    )]
8921    ShardKeyInvalid { shard_key: String, reason: String },
8922    #[error(
8923        ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
8924         Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
8925         convention); :estrategia Replicated runs every cluster active-active and \
8926         :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
8927         distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
8928         to :estrategia Sharded if hash-keyed routing is the intent"
8929    )]
8930    ShardKeyOnNonSharded {
8931        estrategia: PlacementStrategy,
8932        shard_key: String,
8933    },
8934    #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
8935    ContratoMissingTarget {
8936        de: String,
8937        para: String,
8938        wit: String,
8939        expected: &'static str,
8940    },
8941    #[error(
8942        "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
8943         expected `:{expected}` only"
8944    )]
8945    ContratoWrongTarget {
8946        de: String,
8947        para: String,
8948        wit: String,
8949        expected: &'static str,
8950    },
8951    #[error(
8952        "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
8953         like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
8954         that matches no traffic and silently drops every request)"
8955    )]
8956    ContratoEndpointEmpty { de: String, para: String },
8957    #[error(
8958        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
8959         (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
8960         :entrada :paths)"
8961    )]
8962    ContratoEndpointNotAbsolute {
8963        de: String,
8964        para: String,
8965        endpoint: String,
8966    },
8967    #[error(
8968        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
8969         Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
8970         emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
8971         caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
8972         shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
8973         like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
8974         and whitespace)"
8975    )]
8976    ContratoEndpointInvalid {
8977        de: String,
8978        para: String,
8979        endpoint: String,
8980        reason: String,
8981    },
8982    #[error(
8983        "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
8984         subject is a no-op subscribe; omit :subject only if the WIT world is not \
8985         pub-sub-shaped)"
8986    )]
8987    ContratoSubjectEmpty { de: String, para: String },
8988    #[error(
8989        "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
8990         NATS subject: {reason} (the NATS server's subject parser enforces the \
8991         same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
8992         single-token and `>` multi-token wildcards — at publish/subscribe time; \
8993         use a token-by-token form like `\"checkout.events.charge.failed\"` or \
8994         `\"orders.*.completed\"` — a malformed subject silently drops every \
8995         message at runtime far from the source caixa.lisp)"
8996    )]
8997    ContratoSubjectInvalid {
8998        de: String,
8999        para: String,
9000        subject: String,
9001        reason: String,
9002    },
9003    #[error(
9004        "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
9005         addresses the bucket root, defeating the per-key isolation the slot exists \
9006         for; omit :slot only if the WIT world is not store-shaped)"
9007    )]
9008    ContratoSlotEmpty { de: String, para: String },
9009    #[error(
9010        "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
9011         WASI keyvalue store slot template: {reason} (the substrate enforces \
9012         the printable-ASCII intersection-floor every kv backend admits — \
9013         use a single-token path / template expression like `\"checkout/$orderId\"`, \
9014         `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
9015         percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
9016         slot either gets rejected on write by strict backends or silently \
9017         corrupts the next read on permissive ones, far from the source caixa.lisp)"
9018    )]
9019    ContratoSlotInvalid {
9020        de: String,
9021        para: String,
9022        slot: String,
9023        reason: String,
9024    },
9025    #[error(
9026        "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
9027         or an event-sourced indirection (MESH-COMPOSITION §III.3)",
9028        cycle.join(" → ")
9029    )]
9030    ContratoCycle { cycle: Vec<String> },
9031    #[error(
9032        ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
9033         than once (the typed graph edges are a set, not a multiset; duplicate \
9034         contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
9035         values that K8s admission rejects far from the source caixa.lisp)"
9036    )]
9037    ContratoDuplicate {
9038        de: String,
9039        para: String,
9040        wit: String,
9041        target: String,
9042    },
9043    #[error(
9044        ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
9045         contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
9046         express `no per-call deadline on this axis`"
9047    )]
9048    PolicyTimeoutZero,
9049    #[error(
9050        ":politicas :retries must be > 0 when set; omit :retries to express \
9051         `no retries on transient failure`"
9052    )]
9053    PolicyRetriesZero,
9054    #[error(
9055        ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
9056         (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
9057         retry policy into a thundering-herd amplification vector on transient \
9058         failure (one caller request fans out to `(retries+1)^depth` server-side \
9059         calls across the synchronous-:contratos subgraph), exactly the failure \
9060         mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
9061         Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
9062         or omit :retries to disable retries entirely"
9063    )]
9064    PolicyRetriesExceedsCap { retries: u32 },
9065    #[error(
9066        ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
9067         breaker trips on the first call); omit :circuit-breaker to disable it"
9068    )]
9069    PolicyBreakerZeroFailures,
9070    #[error(
9071        ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
9072         mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
9073         above this cap turns the typed breaker policy into a no-op: the trip \
9074         threshold is structurally so high that no realistic failures-per-:window \
9075         traffic shape can reach it, so the breaker never trips and every typed-slot \
9076         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
9077         Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
9078         structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
9079         Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
9080         omit :circuit-breaker to disable the breaker entirely"
9081    )]
9082    PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
9083    #[error(
9084        ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
9085         tracks no failures); omit :circuit-breaker to disable it"
9086    )]
9087    PolicyBreakerZeroWindow,
9088    #[error(
9089        ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
9090         request); omit :rate-limit to disable rate limiting"
9091    )]
9092    PolicyRateLimitZero,
9093    #[error(
9094        ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
9095         (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
9096         rate-limit policy into a no-op limiter: the token-bucket capacity is \
9097         structurally so high that no realistic per-edge traffic shape can drain it, \
9098         so the limiter never trips and every typed-slot consumer (the future \
9099         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9100         local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
9101         that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
9102         Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
9103         Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
9104         Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
9105         to disable rate limiting entirely"
9106    )]
9107    PolicyRateLimitExceedsCap { rate: u32 },
9108    #[error(
9109        ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
9110         the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
9111         rate-limit codec round-trips losslessly; got {window:?} which renders to a \
9112         non-round-trippable form (omit :rate-limit to disable, or pick one of the \
9113         three canonical windows)"
9114    )]
9115    PolicyRateLimitWindowNotCanonical { window: Duration },
9116    #[error(
9117        ":politicas :timeout must be an integer number of milliseconds — the canonical \
9118         authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
9119         duration codec round-trips losslessly; got {timeout:?} which carries a \
9120         sub-millisecond residue that either truncates to a different `Duration` on \
9121         re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
9122         to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
9123         zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
9124         (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
9125    )]
9126    PolicyTimeoutNotCanonical { timeout: Duration },
9127    #[error(
9128        ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
9129         (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
9130         per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
9131         overlays carry a deadline so long no realistic synchronous-:contratos \
9132         traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
9133         CSE invariant degenerates to enforcement only at the per-Servico \
9134         `:limits :wall-clock` layer — far above the per-edge granularity the typed \
9135         `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
9136         (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
9137         ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
9138         maxes out at the same `3600s` ceiling) or omit :timeout to express \
9139         `no per-call deadline on this axis` (the synchronous-call deadline then \
9140         relies entirely on the per-Servico `:limits :wall-clock` axis)"
9141    )]
9142    PolicyTimeoutExceedsCap { timeout: Duration },
9143    #[error(
9144        ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
9145         the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
9146         the shared duration codec round-trips losslessly; got {window:?} which carries a \
9147         sub-millisecond residue that either truncates to a different `Duration` on \
9148         re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
9149         Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
9150    )]
9151    PolicyBreakerWindowNotCanonical { window: Duration },
9152    #[error(
9153        ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
9154         (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
9155         rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
9156         is structurally so long that transient failures are never forgotten, the breaker \
9157         trips once and stays tripped for the lifetime of the component, and every typed-slot \
9158         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9159         outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
9160         Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
9161         default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
9162         the breaker entirely"
9163    )]
9164    PolicyBreakerWindowExceedsCap { window: Duration },
9165    #[error(
9166        ":politicas :circuit-breaker :window ({window:?}) is shorter than :politicas \
9167         :timeout ({timeout:?}) — the rolling failure-observation interval closes before \
9168         a single timing-out call can be declared failed, so the dominant failure mode \
9169         the breaker exists to catch is structurally never counted: a call dispatched at \
9170         t=0 is only reported failed at t={timeout:?}, by which point the window that was \
9171         open at dispatch has already rolled, and every typed-slot consumer (the future \
9172         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9173         outlier_detection.interval paired against the per-route request timeout) emits a \
9174         breaker that cannot trip on timeouts however high the call volume. Pin :window \
9175         at or above :timeout (Hystrix defaults 10s rolling window against a 1s execution \
9176         timeout — a 10× ratio; Envoy / resilience4j production playbooks recommend the \
9177         same shape), lower :timeout, or omit one of the two axes"
9178    )]
9179    PolicyBreakerWindowBelowTimeout { window: Duration, timeout: Duration },
9180    #[error(
9181        ":politicas :rate-limit ({rate} per {rl_window:?}) starves :politicas \
9182         :circuit-breaker so :max-failures ({max_failures}) cannot be reached inside \
9183         :window ({cb_window:?}) — the token-bucket dispatches at most \
9184         `rate × cb_window / rl_window` calls per rolling breaker window, which is \
9185         structurally below the trip threshold, so the breaker cannot trip even under \
9186         100% failure and every typed-slot consumer (the future \
9187         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9188         outlier_detection.consecutive_5xx paired against \
9189         local_rate_limit.token_bucket.max_tokens) emits a protection that is \
9190         structurally never enforced. Raise :rate, shorten :rate-limit :window, lower \
9191         :max-failures, lengthen :circuit-breaker :window, or omit one of the two axes"
9192    )]
9193    PolicyBreakerCannotTripUnderRateLimit {
9194        rate: u32,
9195        rl_window: Duration,
9196        max_failures: u32,
9197        cb_window: Duration,
9198    },
9199    #[error(
9200        ":politicas :retries ({retries}) plus the initial attempt saturates :politicas \
9201         :circuit-breaker :max-failures ({max_failures}) mid-retry — one client's failing \
9202         attempts alone accumulate {retries}+1 failures, which reaches the trip threshold \
9203         at or before the last retry, so the breaker opens with declared retries still \
9204         unused and every typed-slot consumer (the future CiliumClusterwideEnvoyConfig \
9205         per-:politicas overlay, Envoy's retry_policy.num_retries paired against \
9206         outlier_detection.consecutive_5xx) emits a retry policy the substrate \
9207         structurally truncates. Pin :max-failures strictly above :retries (Hystrix / \
9208         Envoy / resilience4j production playbooks recommend the breaker's trip \
9209         threshold be observably larger than any single client's retry budget so the \
9210         breaker distinguishes one persistently-failing client from sustained \
9211         multi-client failure), lower :retries, or omit one of the two axes"
9212    )]
9213    PolicyBreakerTripsBeforeRetriesExhausted { retries: u32, max_failures: u32 },
9214    #[error(
9215        ":politicas :rate-limit ({rate} per window) cannot admit :politicas :retries \
9216         ({retries}) plus the initial attempt — one client's declared retry sequence is \
9217         {retries}+1 attempts, each of which consumes one token from the local rate-limit \
9218         bucket, but the bucket admits at most {rate} tokens per refill window, so the \
9219         retry policy is silently truncated by the same rate limiter it feeds through and \
9220         every typed-slot consumer (the future CiliumClusterwideEnvoyConfig per-:politicas \
9221         overlay, Envoy's retry_policy.num_retries paired against \
9222         local_rate_limit.token_bucket.max_tokens) emits a retry policy the substrate \
9223         structurally throttles. Raise :rate strictly above :retries (Envoy / Istio / \
9224         resilience4j / AWS App Mesh production playbooks recommend the local rate-limit \
9225         bucket capacity be observably larger than any single client's retry budget so the \
9226         limiter distinguishes one client's declared retries from sustained multi-client \
9227         load), lower :retries, or omit one of the two axes"
9228    )]
9229    PolicyRateLimitCannotAdmitRetryBurst { retries: u32, rate: u32 },
9230}
9231
9232// The `AplicacaoError::EntradaHostInvalid { host, reason }` variant's
9233// ctor `entrada_host_invalid` is folded onto the sibling
9234// [`aplicacao_field_reason_ctors!`] macro below alongside the six peer
9235// `{ <field>: String, reason: String }` variants
9236// (`MembroCaixaInvalid` / `EntradaParaInvalid` / `EntradaPathInvalid` /
9237// `PlacementClusterInvalid` / `PlacementAffinityInvalid` /
9238// `ShardKeyInvalid`), so every variant on the uniform two-slot
9239// `{ <field>: String, reason: String }` envelope on [`AplicacaoError`]
9240// reads through one substrate-primitive family rather than one macro
9241// closing six sites plus a hand-written seventh ctor closing the
9242// paired site alone. Prior separate-ctor rationale (17dd504) migrates
9243// verbatim to the macro's outer doc block.
9244
9245// Fold the seven `AplicacaoError::Contrato{Wrong,Missing}Target { de, para,
9246// wit, expected }` wire-up sites at [`WitContract::target`] onto one
9247// substrate-primitive family per typed variant — the paired sibling on
9248// [`AplicacaoError`] of the four `LayoutError` constructor families
9249// [`layout_violation_ctors!`] (131ca0d, 16 variants on `{ caixa, issue }`),
9250// [`layout_slot_kind_ctors!`] (0419438, 4 variants on
9251// `{ caixa, kind, slots }`), [`LayoutError::missing_entry`] (1b09f9d,
9252// 1 variant on `{ kind, path }`), and [`layout_nome_only_ctors!`] (3fe3dd7,
9253// 6 variants on `<Variant>(String)`) each carry on the sibling layout-side
9254// envelope. Every one of the seven wire-up sites in [`WitContract::target`]
9255// (four `ContratoWrongTarget` arms on the payload-field-mismatch axis —
9256// HTTP with subject/slot, PubSub with endpoint/slot, Store with
9257// endpoint/subject, Capability with any payload; three
9258// `ContratoMissingTarget` arms on the payload-field-absent axis — HTTP
9259// without `:endpoint`, PubSub without `:subject`, Store without `:slot`)
9260// opened the identical six-line
9261// `AplicacaoError::Contrato<Wrong|Missing>Target { de, para, wit, expected:
9262// WitTarget::<label> }` struct-literal against the local `edge()` closure
9263// returning `(de, para, wit) = self.edge_triple()` — the exact "same block
9264// re-inlined at every consumer" shape the PRIME DIRECTIVE names as a bug,
9265// on the same altitude the peer four `LayoutError` constructor families
9266// each closed on their sibling envelopes.
9267//
9268// The macro below generates one `#[must_use]` inherent constructor per
9269// variant of shape `fn <ctor>(edge: (String, String, String), expected:
9270// &'static str) -> AplicacaoError`, collapsing the seven sites onto one
9271// dispatch per arm: `return
9272// Err(AplicacaoError::contrato_wrong_target(edge(), <label>));` / `.ok_or_else(||
9273// AplicacaoError::contrato_missing_target(edge(), <label>))?`, byte-equal to
9274// the pre-lift struct-literal on the same edge fixture. The uniform four-
9275// field construction (`de, para, wit` triple-destructure onto same-named
9276// fields + `expected` verbatim) is spelled once — inside the macro —
9277// rather than at every wire-up site. `#[must_use]` fires a compile warning
9278// at any wire-up that mistakenly discards the constructed error.
9279//
9280// Every future consumer that wants to construct one of these two variants
9281// outside [`WitContract::target`] (a deferred
9282// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
9283// admission validator raising wrong-target / missing-target diagnostics
9284// on unrecognized shapes, a future `feira validate --contratos` per-caixa
9285// admission verb, a per-`WitContract` payload-axis pre-emitter probing
9286// the [`WitTarget`] arm against the declared `:endpoint`/`:subject`/`:slot`
9287// slots) reaches the variant through one call rather than re-inlining the
9288// six-line struct-literal block in lockstep with the seven in-crate
9289// wire-up sites.
9290macro_rules! contrato_target_ctors {
9291    ($($ctor:ident => $variant:ident),* $(,)?) => {
9292        impl AplicacaoError {
9293            $(
9294                #[doc = concat!(
9295                    "Construct an [`AplicacaoError::",
9296                    stringify!($variant),
9297                    "`] naming the offending edge `(de, para, wit)` triple ",
9298                    "under the given `expected` payload-field-name label. ",
9299                    "Folds the uniform `{ de, para, wit, expected }` four-",
9300                    "slot struct-literal onto one substrate primitive so ",
9301                    "every [`WitContract::target`] wire-up on this variant ",
9302                    "reads through one dispatch rather than the pre-lift ",
9303                    "six-line open-coded block. The `edge` triple threads ",
9304                    "verbatim from [`WitContract::edge_triple`] via the ",
9305                    "local `edge()` closure at the call site."
9306                )]
9307                #[must_use]
9308                pub fn $ctor(edge: (String, String, String), expected: &'static str) -> Self {
9309                    let (de, para, wit) = edge;
9310                    Self::$variant { de, para, wit, expected }
9311                }
9312            )*
9313        }
9314    };
9315}
9316
9317contrato_target_ctors! {
9318    contrato_wrong_target => ContratoWrongTarget,
9319    contrato_missing_target => ContratoMissingTarget,
9320}
9321
9322// Fold the four `AplicacaoError::{EmptyWit, ContratoEndpointEmpty,
9323// ContratoSubjectEmpty, ContratoSlotEmpty} { de, para }` wire-up sites
9324// onto one substrate-primitive family per typed variant — the paired
9325// `{ de: String, para: String }` two-slot sibling on [`AplicacaoError`]
9326// of the peer four-slot [`contrato_target_ctors!`] (14b81d5,
9327// `{ de, para, wit, expected }` on `ContratoWrongTarget` /
9328// `ContratoMissingTarget`) and of the two-slot
9329// [`AplicacaoError::entrada_host_invalid`] (17dd504, `{ host, reason }`)
9330// on the sibling per-`:entrada :host` envelope. Every one of the four
9331// wire-up sites — three under [`WitContract::target`] (the empty
9332// [`WitTarget::Http`] `:endpoint`, empty [`WitTarget::PubSub`]
9333// `:subject`, empty [`WitTarget::Store`] `:slot`) and one under
9334// [`AplicacaoSpec::validate`] (the empty `:contratos :wit` field the
9335// value-shape gate fires ahead of) — opened the identical two-line
9336// `let (de, para) = <contract>.edge_pair(); return Err(
9337// AplicacaoError::<Variant> { de, para });` block against the local
9338// [`WitContract::edge_pair`] composite-projection accessor, the exact
9339// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE
9340// names as a bug, on the same altitude the peer [`contrato_target_ctors!`]
9341// and [`AplicacaoError::entrada_host_invalid`] each closed on their
9342// sibling envelopes.
9343//
9344// The macro below generates one `#[must_use]` inherent constructor per
9345// variant of shape `fn <ctor>(edge: (String, String)) -> AplicacaoError`,
9346// collapsing the four sites onto one dispatch per arm:
9347// `return Err(AplicacaoError::<ctor>(<contract>.edge_pair()));`, byte-
9348// equal to the pre-lift struct-literal on the same edge pair. The
9349// uniform two-field construction (`de, para` pair-destructure onto
9350// same-named fields) is spelled once — inside the macro — rather than
9351// at every wire-up site. `#[must_use]` fires a compile warning at any
9352// wire-up that mistakenly discards the constructed error.
9353//
9354// Every future consumer that wants to construct one of these four
9355// variants outside the two in-crate wire-up sites (a deferred
9356// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
9357// admission validator raising empty-payload / empty-`:wit` diagnostics,
9358// a future `feira validate --contratos` per-caixa admission verb, an
9359// M4 typed WIT-registry-driven per-arm pre-emitter probing the
9360// [`WitContract`] payload slot against a canonical per-arm requirement
9361// table) reaches the variant through one call rather than re-inlining
9362// the two-line pair-destructure block in lockstep with the four
9363// in-crate wire-up sites.
9364macro_rules! contrato_empty_pair_ctors {
9365    ($($ctor:ident => $variant:ident),* $(,)?) => {
9366        impl AplicacaoError {
9367            $(
9368                #[doc = concat!(
9369                    "Construct an [`AplicacaoError::",
9370                    stringify!($variant),
9371                    "`] naming the offending edge `(de, para)` pair. ",
9372                    "Folds the uniform `{ de, para }` two-slot struct-",
9373                    "literal onto one substrate primitive so every ",
9374                    "wire-up on this variant reads through one dispatch ",
9375                    "rather than the pre-lift two-line open-coded ",
9376                    "`let (de, para) = <contract>.edge_pair(); return ",
9377                    "Err(<Variant> { de, para });` block. The `edge` ",
9378                    "pair threads verbatim from [`WitContract::edge_pair`] ",
9379                    "at the call site."
9380                )]
9381                #[must_use]
9382                pub fn $ctor(edge: (String, String)) -> Self {
9383                    let (de, para) = edge;
9384                    Self::$variant { de, para }
9385                }
9386            )*
9387        }
9388    };
9389}
9390
9391contrato_empty_pair_ctors! {
9392    empty_wit => EmptyWit,
9393    contrato_endpoint_empty => ContratoEndpointEmpty,
9394    contrato_subject_empty => ContratoSubjectEmpty,
9395    contrato_slot_empty => ContratoSlotEmpty,
9396}
9397
9398// Fold the seven `AplicacaoError::{MembroCaixa, EntradaPara, EntradaHost,
9399// EntradaPath, PlacementCluster, PlacementAffinity, ShardKey}Invalid
9400// { <field>: <val>.to_string(), reason: <expr> }` wire-up sites onto one
9401// substrate-primitive family per typed variant — the paired
9402// `{ <field>: String, reason: String }` two-slot sibling on
9403// [`AplicacaoError`] of the peer four-slot [`contrato_target_ctors!`]
9404// (14b81d5, `{ de, para, wit, expected }` on `ContratoWrongTarget` /
9405// `ContratoMissingTarget`) and the peer two-slot
9406// [`contrato_empty_pair_ctors!`] (8580068, `{ de, para }` on `EmptyWit` /
9407// `ContratoEndpointEmpty` / `ContratoSubjectEmpty` / `ContratoSlotEmpty`)
9408// on the sibling per-`:contratos` envelopes, plus the peer four-family
9409// `LayoutError` ctor set ([`layout_violation_ctors!`] 131ca0d — 16
9410// variants on `{ caixa, issue }`, [`layout_slot_kind_ctors!`] 0419438 —
9411// 4 variants on `{ caixa, kind, slots }`, [`LayoutError::missing_entry`]
9412// 1b09f9d — 1 variant on `{ kind, path }`, [`layout_nome_only_ctors!`]
9413// 3fe3dd7 — 6 variants on `<Variant>(String)`) each carry on the
9414// sibling layout-side envelope.
9415//
9416// Every one of the seven wire-up sites — six under the per-axis
9417// `validate_*` wrappers around [`crate::render::require_valid_dns_1123_label`]
9418// (`validate_membro_caixa` on `MembroCaixaInvalid`, `validate_entrada_para`
9419// on `EntradaParaInvalid`, `validate_placement_cluster` on
9420// `PlacementClusterInvalid`, `validate_placement_affinity` on
9421// `PlacementAffinityInvalid`) plus [`crate::render::is_gateway_api_http_path`]
9422// (`validate_entrada_path` on `EntradaPathInvalid`), and two under
9423// [`validate_placement_shard_key`] (the length-cap arm and the per-byte
9424// printable-ASCII arm on `ShardKeyInvalid`) — plus the fourteen wire-up
9425// sites at [`validate_entrada_host`] (17dd504 already folded onto the
9426// pre-macro standalone `entrada_host_invalid` ctor, now converged onto
9427// the macro-generated ctor of the same name), opened the identical
9428// four-line `AplicacaoError::<Variant>Invalid
9429// { <field>: <val>.to_string(), reason: <expr> }` struct-literal against
9430// the local `<field>: &str` argument — the exact "same block re-inlined
9431// at every consumer" shape the PRIME DIRECTIVE names as a bug, on the
9432// same altitude the peer three `AplicacaoError` constructor families
9433// and the four peer `LayoutError` constructor families each closed on
9434// their sibling envelopes.
9435//
9436// The macro below generates one `#[must_use]` inherent constructor per
9437// variant of shape `fn <ctor>(<field>: &str, reason: impl Into<String>)
9438// -> AplicacaoError`, collapsing every site onto one dispatch per arm:
9439// `return Err(AplicacaoError::<ctor>(<val>, <reason>));` /
9440// `|reason| AplicacaoError::<ctor>(<val>, reason)`, byte-equal to the
9441// pre-lift struct-literal on the same `(<field>, reason)` pair. The
9442// uniform two-field construction (`<field>: <val>.to_string()`,
9443// `reason: reason.into()`) is spelled once — inside the macro — rather
9444// than at every wire-up site. The `reason: impl Into<String>` bound
9445// accepts both `&str` literals (with or without a trailing
9446// `.to_string()` at the caller) and `format!(…)` outputs verbatim so no
9447// wire-up site changes its per-arm diagnostic shape at the lift.
9448// `#[must_use]` fires a compile warning at any wire-up that mistakenly
9449// discards the constructed error rather than routing it through
9450// `return Err(…)` / `.map_err(…)` / a closure return.
9451//
9452// Every future consumer that wants to construct one of these seven
9453// variants outside the current in-crate wire-up sites (the deferred
9454// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-slot
9455// admission validators, a future `feira validate --<axis>` per-caixa
9456// admission verb, a per-`Certificate` SAN pre-emitter for cert-manager
9457// on `:entrada :host`, an M4 typed placement-engine per-cluster /
9458// per-affinity / per-shard-key pre-emitter, an M4 typed Gateway API
9459// per-path pre-emitter) reaches the variant through one call rather
9460// than re-inlining the four-line struct-literal block in lockstep with
9461// the current in-crate wire-up sites.
9462macro_rules! aplicacao_field_reason_ctors {
9463    ($($ctor:ident => $variant:ident { $field:ident }),* $(,)?) => {
9464        impl AplicacaoError {
9465            $(
9466                #[doc = concat!(
9467                    "Construct an [`AplicacaoError::",
9468                    stringify!($variant),
9469                    "`] naming the offending `",
9470                    stringify!($field),
9471                    "` under the given `reason`. Folds the uniform ",
9472                    "`{ ",
9473                    stringify!($field),
9474                    ": ",
9475                    stringify!($field),
9476                    ".to_string(), reason: reason.into() }` two-slot ",
9477                    "construction onto one substrate primitive so every ",
9478                    "wire-up on this variant reads through one dispatch ",
9479                    "rather than the pre-lift four-line struct-literal ",
9480                    "block. `reason` accepts both `&str` literals and ",
9481                    "`format!(…)` outputs through the `impl Into<String>` ",
9482                    "bound."
9483                )]
9484                #[must_use]
9485                pub fn $ctor($field: &str, reason: impl Into<String>) -> Self {
9486                    Self::$variant {
9487                        $field: $field.to_string(),
9488                        reason: reason.into(),
9489                    }
9490                }
9491            )*
9492        }
9493    };
9494}
9495
9496aplicacao_field_reason_ctors! {
9497    membro_caixa_invalid => MembroCaixaInvalid { caixa },
9498    entrada_para_invalid => EntradaParaInvalid { para },
9499    entrada_host_invalid => EntradaHostInvalid { host },
9500    entrada_path_invalid => EntradaPathInvalid { path },
9501    placement_cluster_invalid => PlacementClusterInvalid { cluster },
9502    placement_affinity_invalid => PlacementAffinityInvalid { affinity },
9503    shard_key_invalid => ShardKeyInvalid { shard_key },
9504}
9505
9506// Fold the three `AplicacaoError::Contrato{Endpoint,Subject,Slot}Invalid
9507// { de, para, <field>: <val>.to_string(), reason }` wire-up sites at
9508// [`WitContract::target`] onto one substrate-primitive family per typed
9509// variant — the paired `{ de: String, para: String, <field>: String,
9510// reason: String }` four-slot sibling on [`AplicacaoError`] of the peer
9511// four-slot [`contrato_target_ctors!`] (14b81d5, `{ de, para, wit,
9512// expected }` on `ContratoWrongTarget` / `ContratoMissingTarget`), the
9513// peer two-slot [`contrato_empty_pair_ctors!`] (8580068, `{ de, para }`
9514// on `EmptyWit` / `ContratoEndpointEmpty` / `ContratoSubjectEmpty` /
9515// `ContratoSlotEmpty`), and the peer two-slot
9516// [`aplicacao_field_reason_ctors!`] (981060b, `{ <field>: String,
9517// reason: String }` on `MembroCaixaInvalid` / `EntradaParaInvalid` /
9518// `EntradaHostInvalid` / `EntradaPathInvalid` / `PlacementClusterInvalid`
9519// / `PlacementAffinityInvalid` / `ShardKeyInvalid`) each carry on the
9520// sibling `AplicacaoError` envelopes, plus the peer four-family
9521// `LayoutError` ctor set on the sibling layout-side envelope.
9522//
9523// Every one of the three wire-up sites — three per-payload-axis value-
9524// shape gates inside [`WitContract::target`] (the HTTP arm's
9525// [`crate::render::is_gateway_api_http_path`] failure on `:endpoint`,
9526// the pub-sub arm's [`crate::render::is_nats_subject`] failure on
9527// `:subject`, the store arm's [`crate::render::is_wasi_keyvalue_slot`]
9528// failure on `:slot`) — opened the identical five-line
9529// `let (de, para) = self.edge_pair();
9530// return Err(AplicacaoError::Contrato<Field>Invalid { de, para,
9531// <field>: <val>.to_string(), reason });` block against the local
9532// [`WitContract::edge_pair`] composite-projection accessor and the
9533// per-arm `<val>: &str` argument — the exact "same block re-inlined at
9534// every consumer" shape the PRIME DIRECTIVE names as a bug, on the same
9535// altitude the peer three `AplicacaoError` constructor families and the
9536// four peer `LayoutError` constructor families each closed on their
9537// sibling envelopes.
9538//
9539// The macro below generates one `#[must_use]` inherent constructor per
9540// variant of shape `fn <ctor>(edge: (String, String), <field>: &str,
9541// reason: impl Into<String>) -> AplicacaoError`, collapsing the three
9542// sites onto one dispatch per arm:
9543// `return Err(AplicacaoError::<ctor>(self.edge_pair(), <val>, reason));`,
9544// byte-equal to the pre-lift struct-literal on the same
9545// `(edge_pair, <val>, reason)` triple. The uniform four-field
9546// construction (`de, para` pair-destructure onto same-named fields +
9547// `<field>: <val>.to_string()` + `reason: reason.into()`) is spelled
9548// once — inside the macro — rather than at every wire-up site. The
9549// `reason: impl Into<String>` bound accepts both `&str` literals and
9550// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
9551// diagnostic shape at the lift, matching the peer
9552// [`aplicacao_field_reason_ctors!`] bound on the sibling two-slot
9553// envelope. `#[must_use]` fires a compile warning at any wire-up that
9554// mistakenly discards the constructed error.
9555//
9556// Every future consumer that wants to construct one of these three
9557// variants outside [`WitContract::target`] (a deferred
9558// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
9559// admission validator raising per-payload value-shape diagnostics on
9560// unrecognized `:endpoint` / `:subject` / `:slot` shapes, a future
9561// `feira validate --contratos` per-caixa admission verb, an M4 typed
9562// WIT-registry-driven per-arm pre-emitter probing each declared
9563// `:endpoint` / `:subject` / `:slot` payload against a canonical
9564// per-arm shape gate, a per-`Certificate` SAN pre-emitter for
9565// cert-manager on the `:endpoint` axis, an M4 typed Cilium L7 rule
9566// pre-emitter probing each `:endpoint` against the same shared
9567// HTTPPathMatch grammar) reaches the variant through one call rather
9568// than re-inlining the five-line pair-destructure + struct-literal
9569// block in lockstep with the three in-crate wire-up sites.
9570macro_rules! contrato_pair_value_reason_ctors {
9571    ($($ctor:ident => $variant:ident { $field:ident }),* $(,)?) => {
9572        impl AplicacaoError {
9573            $(
9574                #[doc = concat!(
9575                    "Construct an [`AplicacaoError::",
9576                    stringify!($variant),
9577                    "`] naming the offending edge `(de, para)` pair, the ",
9578                    "per-payload `",
9579                    stringify!($field),
9580                    "` value, and the parser-shaped `reason`. Folds the ",
9581                    "uniform `{ de, para, ",
9582                    stringify!($field),
9583                    ": ",
9584                    stringify!($field),
9585                    ".to_string(), reason: reason.into() }` four-slot ",
9586                    "construction onto one substrate primitive so every ",
9587                    "wire-up on this variant reads through one dispatch ",
9588                    "rather than the pre-lift five-line pair-destructure ",
9589                    "+ struct-literal block. The `edge` pair threads ",
9590                    "verbatim from [`WitContract::edge_pair`] at the ",
9591                    "call site; `reason` accepts both `&str` literals ",
9592                    "and `format!(…)` outputs through the `impl ",
9593                    "Into<String>` bound."
9594                )]
9595                #[must_use]
9596                pub fn $ctor(edge: (String, String), $field: &str, reason: impl Into<String>) -> Self {
9597                    let (de, para) = edge;
9598                    Self::$variant {
9599                        de,
9600                        para,
9601                        $field: $field.to_string(),
9602                        reason: reason.into(),
9603                    }
9604                }
9605            )*
9606        }
9607    };
9608}
9609
9610contrato_pair_value_reason_ctors! {
9611    contrato_endpoint_invalid => ContratoEndpointInvalid { endpoint },
9612    contrato_subject_invalid => ContratoSubjectInvalid { subject },
9613    contrato_slot_invalid => ContratoSlotInvalid { slot },
9614}
9615
9616#[cfg(test)]
9617mod tests {
9618    use super::*;
9619
9620    fn membro(name: &str, ver: &str) -> Membro {
9621        Membro {
9622            caixa: name.into(),
9623            versao: ver.into(),
9624        }
9625    }
9626
9627    fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
9628        WitContract {
9629            de: de.into(),
9630            para: para.into(),
9631            wit: "wasi:http/proxy".into(),
9632            endpoint: Some(ep.into()),
9633            subject: None,
9634            slot: None,
9635        }
9636    }
9637
9638    fn three_member_spec() -> AplicacaoSpec {
9639        AplicacaoSpec {
9640            membros: vec![
9641                membro("catalog", "^0.1"),
9642                membro("cart", "^0.1"),
9643                membro("payment", "^0.2"),
9644            ],
9645            contratos: vec![
9646                contract_http("cart", "catalog", "/products/:id"),
9647                contract_http("cart", "payment", "/charge"),
9648            ],
9649            politicas: MeshPolicy {
9650                timeout: Some(Duration::from_secs(30)),
9651                retries: Some(3),
9652                mtls_required: Some(true),
9653                ..Default::default()
9654            },
9655            placement: Placement {
9656                estrategia: PlacementStrategy::Replicated,
9657                clusters: vec!["rio".into(), "mar".into()],
9658                affinity: Some("data-locality".into()),
9659                shard_key: None,
9660            },
9661            entrada: Some(Entrada {
9662                host: "checkout.quero.cloud".into(),
9663                para: "cart".into(),
9664                paths: vec!["/api/cart".into(), "/api/products".into()],
9665                port: 8080,
9666            }),
9667        }
9668    }
9669
9670    #[test]
9671    fn happy_path_validates() {
9672        three_member_spec().validate().unwrap();
9673    }
9674
9675    #[test]
9676    fn rejects_empty_membros() {
9677        let mut s = three_member_spec();
9678        s.membros = vec![];
9679        assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
9680    }
9681
9682    #[test]
9683    fn rejects_empty_membro_caixa() {
9684        // A `:caixa ""` entry has no name to render into programs.yaml
9685        // and no caixa.lisp to resolve at lacre time.
9686        let mut s = three_member_spec();
9687        s.membros[1].caixa = String::new();
9688        assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
9689    }
9690
9691    #[test]
9692    fn rejects_empty_membro_versao() {
9693        // A `:versao ""` entry can't pin a semver constraint, so the
9694        // lacre pipeline fails far from the source.
9695        let mut s = three_member_spec();
9696        s.membros[2].versao = String::new();
9697        let err = s.validate().unwrap_err();
9698        assert!(
9699            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
9700            "got {err:?}"
9701        );
9702    }
9703
9704    #[test]
9705    fn rejects_duplicate_membro_caixa() {
9706        // Two `:membros` entries with the same `:caixa` collapse to one
9707        // node in the membership HashSet, which masks `:contratos`
9708        // membership errors and produces duplicate programs.yaml entries.
9709        let mut s = three_member_spec();
9710        s.membros.push(membro("cart", "^0.2"));
9711        let err = s.validate().unwrap_err();
9712        assert!(
9713            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
9714            "got {err:?}"
9715        );
9716    }
9717
9718    #[test]
9719    fn rejects_invalid_membro_versao_requirement() {
9720        // The fail-before-pass-after pin: a non-empty but malformed
9721        // semver requirement (`"^bad-version"`) silently passed
9722        // `validate()` on every pre-gate codebase because the prior
9723        // shape only refused the empty string. The parse failure
9724        // surfaced far downstream at lacre-resolve time with a
9725        // `semver::Error` that didn't name which `:membros` entry
9726        // carried the typo. The new gate moves the check to caixa-build
9727        // time at the source caixa.lisp.
9728        let mut s = three_member_spec();
9729        s.membros[2].versao = "^bad-version".into();
9730        let err = s.validate().unwrap_err();
9731        assert!(
9732            matches!(
9733                err,
9734                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
9735                    if caixa == "payment" && versao == "^bad-version"
9736            ),
9737            "got {err:?}"
9738        );
9739    }
9740
9741    #[test]
9742    fn rejects_membro_versao_with_double_caret_typo() {
9743        // `"^^0.1"` is the canonical doubled-caret typo — looks like a
9744        // Cargo-shaped requirement on first glance but fails the parser
9745        // because semver doesn't accept stacked operators. Pin this
9746        // adjacent-shape footgun explicitly so a future relaxation that
9747        // accepts "looks-canonical-but-isn't" forms surfaces here.
9748        let mut s = three_member_spec();
9749        s.membros[0].versao = "^^0.1".into();
9750        let err = s.validate().unwrap_err();
9751        assert!(
9752            matches!(
9753                err,
9754                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
9755                    if caixa == "catalog" && versao == "^^0.1"
9756            ),
9757            "got {err:?}"
9758        );
9759    }
9760
9761    #[test]
9762    fn rejects_membro_versao_with_v_prefixed_tag() {
9763        // `"v0.1"` is the canonical "git-tag-shape leaking into the
9764        // semver requirement slot" typo — an author copies the
9765        // publish-side git-tag string verbatim into `:versao`, but
9766        // Cargo's semver parser rejects the leading `v` (only digits +
9767        // canonical operators are valid in the major-version
9768        // position). The gate's diagnostic names which member entry
9769        // carried the v-prefix so the fix is one edit, not a grep
9770        // through every member's `:versao`. (Note: bare `x`-glob
9771        // shorthands like `^0.1.x` are *accepted* by the semver crate
9772        // as an `*` wildcard on the patch axis — they're a Cargo-side
9773        // valid shape, not a typo, so the gate intentionally lets them
9774        // through.)
9775        let mut s = three_member_spec();
9776        s.membros[1].versao = "v0.1".into();
9777        let err = s.validate().unwrap_err();
9778        assert!(
9779            matches!(
9780                err,
9781                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
9782                    if caixa == "cart" && versao == "v0.1"
9783            ),
9784            "got {err:?}"
9785        );
9786    }
9787
9788    #[test]
9789    fn accepts_canonical_membro_versao_forms() {
9790        // The four Cargo-shaped requirement forms `:deps :versao`
9791        // already accepts via `crate::parse_requirement` must pass the
9792        // membros gate without re-validating at the resolver layer.
9793        // Pin every leg so a future tightening of the canonical set
9794        // surfaces here as a test failure.
9795        for form in [
9796            "^0.1",      // caret — minor-range pin (the most common shape)
9797            "~0.1.2",    // tilde — patch-range pin
9798            "0.1.0",     // exact — single-version pin
9799            "*",         // wildcard — explicitly any-version (semver::VersionReq::STAR)
9800            ">=0.1, <2", // multi-range — comma-separated comparators
9801        ] {
9802            let mut s = three_member_spec();
9803            for m in &mut s.membros {
9804                m.versao = form.into();
9805            }
9806            s.validate()
9807                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
9808        }
9809    }
9810
9811    #[test]
9812    fn membro_versao_empty_takes_precedence_over_invalid() {
9813        // Order pin: the existing `MembroVersaoEmpty` diagnostic
9814        // (which doesn't try to parse) fires before the new
9815        // `MembroVersaoInvalid` parse-side diagnostic, so an empty
9816        // `:versao` keeps its narrower error message — `parse_requirement`
9817        // would also reject `""`, but the empty-string arm is the more
9818        // self-locating diagnostic for the author.
9819        let mut s = three_member_spec();
9820        s.membros[1].versao = String::new();
9821        let err = s.validate().unwrap_err();
9822        assert!(
9823            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
9824            "got {err:?}"
9825        );
9826    }
9827
9828    #[test]
9829    fn membro_versao_invalid_fires_before_duplicate_check() {
9830        // Order pin: a malformed requirement on a non-duplicate entry
9831        // surfaces *its own* diagnostic (which names the offending
9832        // `:versao` string), even when a later entry would otherwise
9833        // collapse onto an earlier name. The per-entry shape gate runs
9834        // inline before the duplicate-key insert, parallel to
9835        // `membros_validation_runs_before_contratos_membership_check`
9836        // and `duplicate_contrato_gate_runs_after_target_shape_check`.
9837        let mut s = three_member_spec();
9838        s.membros[0].versao = "^bad".into();
9839        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
9840        let err = s.validate().unwrap_err();
9841        assert!(
9842            matches!(
9843                err,
9844                AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
9845            ),
9846            "got {err:?}"
9847        );
9848    }
9849
9850    #[test]
9851    fn membro_versao_invalid_diagnostic_carries_offending_versao() {
9852        // The diagnostic-shape pin: the error names the offending
9853        // `:versao` value verbatim so the author can grep their
9854        // caixa.lisp without re-running the build, and carries a
9855        // non-empty `reason` from `semver::VersionReq::parse` so the
9856        // parser's own wording flows through to the diagnostic.
9857        let mut s = three_member_spec();
9858        s.membros[2].versao = "not-a-req".into();
9859        let err = s.validate().unwrap_err();
9860        let AplicacaoError::MembroVersaoInvalid {
9861            caixa,
9862            versao,
9863            reason,
9864        } = err
9865        else {
9866            panic!("expected MembroVersaoInvalid, got other variant");
9867        };
9868        assert_eq!(caixa, "payment");
9869        assert_eq!(versao, "not-a-req");
9870        assert!(
9871            !reason.is_empty(),
9872            "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
9873        );
9874    }
9875
9876    #[test]
9877    fn membro_versao_invalid_runs_before_contratos_check() {
9878        // A malformed `:versao` on any member must surface its own
9879        // diagnostic (which names *which* member to fix) before any
9880        // `:contratos` membership lookup raises `ContratoMemberMissing`.
9881        // The `:contratos` gate runs after `validate_membros`, so this
9882        // is structurally guaranteed — pin it explicitly so a future
9883        // refactor that reorders the gates surfaces here.
9884        let mut s = three_member_spec();
9885        s.membros[1].versao = "^^0.1".into();
9886        // Add a contrato whose `:para` doesn't exist — would normally
9887        // raise ContratoMemberMissing at the membership lookup, but
9888        // the membros gate must fire first.
9889        s.contratos
9890            .push(contract_http("cart", "phantom", "/never-reached"));
9891        let err = s.validate().unwrap_err();
9892        assert!(
9893            matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
9894            "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
9895        );
9896    }
9897
9898    #[test]
9899    fn membros_validation_runs_before_contratos_membership_check() {
9900        // If `:membros` carries a duplicate, the membership-collapse
9901        // would silently accept a `:contratos :para "phantom"` so long
9902        // as some entry hashes to "phantom". Pinning order: the
9903        // duplicate-membros error fires first, regardless of whether
9904        // contratos reference real members.
9905        let mut s = three_member_spec();
9906        s.membros = vec![
9907            membro("cart", "^0.1"),
9908            membro("cart", "^0.2"),
9909            membro("catalog", "^0.1"),
9910            membro("payment", "^0.1"),
9911        ];
9912        let err = s.validate().unwrap_err();
9913        assert!(
9914            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
9915            "got {err:?}"
9916        );
9917    }
9918
9919    #[test]
9920    fn distinct_membros_validate() {
9921        // Pin the happy-path: every `:membros` entry has a non-empty
9922        // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
9923        // The fixture already satisfies this; this test makes the
9924        // invariant explicit so a future refactor of the fixture can't
9925        // silently break the guarantee.
9926        three_member_spec().validate().unwrap();
9927    }
9928
9929    // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
9930
9931    #[test]
9932    fn rejects_membro_caixa_with_uppercase() {
9933        // The canonical "I copied the Servico's display name verbatim"
9934        // typo — caixa names are lowercase per K8s DNS-1123 label rule,
9935        // but author tools often round-trip a TitleCase or CamelCase
9936        // identifier from an ADR or a sketch. Pin the diagnostic names
9937        // the offending name and suggests the lower-cased fix in one
9938        // edit, mirroring the `rejects_entrada_host_with_uppercase`
9939        // gate's shape (c7d05ec).
9940        let mut s = three_member_spec();
9941        s.membros[1].caixa = "Cart".into();
9942        let err = s.validate().unwrap_err();
9943        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
9944            panic!("expected MembroCaixaInvalid, got other variant");
9945        };
9946        assert_eq!(caixa, "Cart");
9947        assert!(
9948            reason.contains("uppercase"),
9949            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
9950        );
9951        assert!(
9952            reason.contains("\"cart\""),
9953            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
9954        );
9955    }
9956
9957    #[test]
9958    fn rejects_membro_caixa_with_underscore() {
9959        // The canonical "I'm thinking of a Python module / Postgres
9960        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
9961        // label schema. K8s rejects `metadata.name: my_cart` at admission
9962        // time with an opaque `field is invalid` (no source-citing
9963        // diagnostic). The gate moves it to caixa-build time.
9964        let mut s = three_member_spec();
9965        s.membros[0].caixa = "my_cart".into();
9966        let err = s.validate().unwrap_err();
9967        assert!(
9968            matches!(
9969                err,
9970                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
9971                    if caixa == "my_cart" && reason.contains('_')
9972            ),
9973            "got {err:?}"
9974        );
9975    }
9976
9977    #[test]
9978    fn rejects_membro_caixa_with_dot() {
9979        // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
9980        // subdomain — even though K8s `metadata.name` itself accepts
9981        // dots (DNS-1123 subdomain rule), this string also lands as a
9982        // K8s Service name (DNS-1035 label — no dots) and as a label
9983        // value on identity-based Cilium selectors. The strictest floor
9984        // among the use sites wins. The "I want to namespace my member
9985        // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
9986        let mut s = three_member_spec();
9987        s.membros[2].caixa = "team.cart".into();
9988        let err = s.validate().unwrap_err();
9989        assert!(
9990            matches!(
9991                err,
9992                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
9993                    if caixa == "team.cart" && reason.contains('.')
9994            ),
9995            "got {err:?}"
9996        );
9997    }
9998
9999    #[test]
10000    fn rejects_membro_caixa_with_leading_hyphen() {
10001        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
10002        // with an alphanumeric. The K8s apiserver rejects `-cart`
10003        // outright; the renderer would emit a `metadata.name: "-cart"`
10004        // that fails admission far from the source caixa.lisp.
10005        let mut s = three_member_spec();
10006        s.membros[0].caixa = "-cart".into();
10007        let err = s.validate().unwrap_err();
10008        assert!(
10009            matches!(
10010                err,
10011                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
10012                    if caixa == "-cart" && reason.contains("start and end")
10013            ),
10014            "got {err:?}"
10015        );
10016    }
10017
10018    #[test]
10019    fn rejects_membro_caixa_with_trailing_hyphen() {
10020        // The symmetric arm of the boundary rule. Pin separately so
10021        // both ends of the label are covered against a future relaxation
10022        // that only checks one boundary.
10023        let mut s = three_member_spec();
10024        s.membros[1].caixa = "cart-".into();
10025        let err = s.validate().unwrap_err();
10026        assert!(
10027            matches!(
10028                err,
10029                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
10030                    if caixa == "cart-"
10031            ),
10032            "got {err:?}"
10033        );
10034    }
10035
10036    #[test]
10037    fn rejects_membro_caixa_with_unicode() {
10038        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
10039        // (`xn--…`) by the author before it reaches K8s. The byte-by-
10040        // byte ASCII validity check rejects multi-byte UTF-8 sequences
10041        // by the first byte that fails the `[a-z0-9-]` predicate.
10042        let mut s = three_member_spec();
10043        s.membros[2].caixa = "café".into();
10044        let err = s.validate().unwrap_err();
10045        assert!(
10046            matches!(
10047                err,
10048                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
10049                    if caixa == "café"
10050            ),
10051            "got {err:?}"
10052        );
10053    }
10054
10055    #[test]
10056    fn rejects_membro_caixa_with_whitespace() {
10057        // Whitespace is the canonical "I pasted from a sketch / doc"
10058        // footgun. The apiserver rejects every `metadata.name` value
10059        // carrying whitespace; pin the gate fires at the right boundary.
10060        let mut s = three_member_spec();
10061        s.membros[0].caixa = "my cart".into();
10062        let err = s.validate().unwrap_err();
10063        assert!(
10064            matches!(
10065                err,
10066                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
10067                    if caixa == "my cart"
10068            ),
10069            "got {err:?}"
10070        );
10071    }
10072
10073    #[test]
10074    fn rejects_membro_caixa_too_long() {
10075        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
10076        // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
10077        // exactly. The gate's reason names both the cap and the actual
10078        // length so the author can shorten in one edit.
10079        let mut s = three_member_spec();
10080        let too_long = "a".repeat(64);
10081        s.membros[1].caixa = too_long.clone();
10082        let err = s.validate().unwrap_err();
10083        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
10084            panic!("expected MembroCaixaInvalid");
10085        };
10086        assert_eq!(caixa, too_long);
10087        assert!(
10088            reason.contains("63") && reason.contains("64"),
10089            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
10090        );
10091    }
10092
10093    #[test]
10094    fn membro_caixa_max_length_validates() {
10095        // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
10096        // so a future tightening (e.g. dropping to 62) surfaces here as
10097        // a regression, mirroring `entrada_host_max_length_validates`
10098        // (c7d05ec).
10099        let mut s = three_member_spec();
10100        s.membros[2].caixa = "a".repeat(63);
10101        s.entrada.as_mut().unwrap().para = "a".repeat(63);
10102        // remove contratos referencing the renamed member; they'd
10103        // raise ContratoMemberMissing otherwise
10104        s.contratos
10105            .retain(|c| c.de != "payment" && c.para != "payment");
10106        s.validate().unwrap();
10107    }
10108
10109    #[test]
10110    fn accepts_canonical_membro_caixa_forms() {
10111        // The DNS-1123 label shapes a caixa author is realistically
10112        // going to write: single-word lowercase, hyphen-joined, ending
10113        // in a digit-suffixed version (`cart-v2`), starting with a
10114        // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
10115        // DNS-1035 which requires a letter at position 0), single-
10116        // character (`a` — boundary). Pin every leg so a future
10117        // tightening that bans (e.g.) digit-start identifiers surfaces
10118        // here.
10119        for form in [
10120            "checkout",
10121            "cart",
10122            "cart-v2",
10123            "a",
10124            "c0",
10125            "3rd-party-shim",
10126            "x-1-2-3-4",
10127        ] {
10128            let mut s = three_member_spec();
10129            // Renaming a member also requires updating downstream refs;
10130            // drop everything else and rebuild a minimal spec around
10131            // just the one renamed member.
10132            s.membros = vec![membro(form, "^0.1")];
10133            s.contratos = vec![];
10134            s.entrada = None;
10135            s.validate()
10136                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
10137        }
10138    }
10139
10140    #[test]
10141    fn membro_caixa_empty_takes_precedence_over_invalid() {
10142        // Order pin: the existing `MembroCaixaEmpty` diagnostic
10143        // (which doesn't try to parse) fires before the new
10144        // `MembroCaixaInvalid` parse-side diagnostic, so an empty
10145        // `:caixa` keeps its narrower error message — the new gate
10146        // would also reject `""`, but the empty-string arm is the more
10147        // self-locating diagnostic for the author. Mirrors the
10148        // `entrada_host_empty_takes_precedence_over_invalid` pin
10149        // (c7d05ec).
10150        let mut s = three_member_spec();
10151        s.membros[1].caixa = String::new();
10152        let err = s.validate().unwrap_err();
10153        assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
10154    }
10155
10156    #[test]
10157    fn membro_caixa_invalid_fires_before_versao_check() {
10158        // Order pin: an invalid-shape `:caixa` surfaces *its own*
10159        // diagnostic (which names the offending caixa name), even when
10160        // the same entry's `:versao` is also empty/invalid. The shape
10161        // gate runs first because the diagnostic is more self-locating —
10162        // an empty/invalid `:versao` on an invalid-shape caixa name is
10163        // a downstream-fix-after-the-caixa-rename concern.
10164        let mut s = three_member_spec();
10165        s.membros[1].caixa = "Cart".into();
10166        s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
10167        let err = s.validate().unwrap_err();
10168        assert!(
10169            matches!(
10170                err,
10171                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
10172            ),
10173            "got {err:?}"
10174        );
10175    }
10176
10177    #[test]
10178    fn membro_caixa_invalid_fires_before_duplicate_check() {
10179        // Order pin: a malformed-shape `:caixa` on an earlier entry
10180        // surfaces *its own* diagnostic, even when a later entry would
10181        // otherwise collapse onto a duplicate name. The per-entry shape
10182        // gate runs inline before the duplicate-key insert, parallel
10183        // to `membro_versao_invalid_fires_before_duplicate_check`.
10184        let mut s = three_member_spec();
10185        s.membros[0].caixa = "Catalog".into();
10186        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
10187        let err = s.validate().unwrap_err();
10188        assert!(
10189            matches!(
10190                err,
10191                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
10192            ),
10193            "got {err:?}"
10194        );
10195    }
10196
10197    #[test]
10198    fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
10199        // The diagnostic-shape pin: the error names the offending
10200        // `:caixa` value verbatim so the author can grep their
10201        // caixa.lisp without re-running the build, and carries a
10202        // non-empty `reason` naming the specific violation. Same
10203        // shape every typed-shape gate enshrines (c7d05ec's
10204        // `entrada_host_diagnostic_carries_offending_host`,
10205        // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
10206        let mut s = three_member_spec();
10207        s.membros[2].caixa = "BAD_NAME".into();
10208        let err = s.validate().unwrap_err();
10209        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
10210            panic!("expected MembroCaixaInvalid");
10211        };
10212        assert_eq!(caixa, "BAD_NAME");
10213        assert!(
10214            !reason.is_empty(),
10215            "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
10216        );
10217    }
10218
10219    #[test]
10220    fn rejects_contrato_with_unknown_de() {
10221        let mut s = three_member_spec();
10222        s.contratos.push(contract_http("phantom", "catalog", "/x"));
10223        let err = s.validate().unwrap_err();
10224        assert!(
10225            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
10226        );
10227    }
10228
10229    #[test]
10230    fn rejects_contrato_with_unknown_para() {
10231        let mut s = three_member_spec();
10232        s.contratos.push(contract_http("cart", "phantom", "/x"));
10233        let err = s.validate().unwrap_err();
10234        assert!(
10235            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
10236        );
10237    }
10238
10239    #[test]
10240    fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
10241        // The read-path pin: the phantom-`:de` refusal arm's
10242        // `ContratoMemberMissing.caixa` carrier must be observed through
10243        // the lifted [`WitContract::source`] accessor, not the raw
10244        // `.de.clone()` field-access `String`-carry. Peer of the sibling
10245        // per-`:contratos` self-loop arm's `.source().to_string()` /
10246        // `.world_ref().to_string()` `String`-carry sites the earlier
10247        // convergence lifted onto the same accessor pair. A future
10248        // silent detour that reintroduced the raw `.de.clone()` at the
10249        // wrap envelope while the shape-gate and membership lookup
10250        // routed through the accessor would surface here as a byte-equal
10251        // miss between the fired diagnostic's `caixa:` field and the
10252        // offending edge's `.source()` — pinning the accessor as the
10253        // sole read path across the phantom-name refusal arm's arg +
10254        // wrap-envelope emit surface.
10255        let mut s = three_member_spec();
10256        let phantom = contract_http("phantom", "catalog", "/x");
10257        s.contratos.push(phantom.clone());
10258        let err = s.validate().unwrap_err();
10259        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
10260            panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
10261        };
10262        assert_eq!(
10263            caixa,
10264            phantom.source(),
10265            "ContratoMemberMissing.caixa on the phantom-:de arm must \
10266             byte-equal WitContract::source — the wrap envelope must \
10267             route through the lifted accessor rather than the raw \
10268             .de.clone() field-access String-carry"
10269        );
10270    }
10271
10272    #[test]
10273    fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
10274        // The symmetric read-path pin on the `:para` phantom-name
10275        // refusal arm — same shape as the sibling `:de` pin above but
10276        // on the callee-Servico axis. Pins the wrap envelope's
10277        // `caixa:` field is observed through the lifted
10278        // [`WitContract::destination`] accessor, not the raw
10279        // `.para.clone()` field-access `String`-carry.
10280        let mut s = three_member_spec();
10281        let phantom = contract_http("cart", "phantom", "/x");
10282        s.contratos.push(phantom.clone());
10283        let err = s.validate().unwrap_err();
10284        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
10285            panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
10286        };
10287        assert_eq!(
10288            caixa,
10289            phantom.destination(),
10290            "ContratoMemberMissing.caixa on the phantom-:para arm must \
10291             byte-equal WitContract::destination — the wrap envelope \
10292             must route through the lifted accessor rather than the raw \
10293             .para.clone() field-access String-carry"
10294        );
10295    }
10296
10297    #[test]
10298    fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
10299        // The read-path pin on the `:de` DNS-1123-malformed shape-gate
10300        // refusal arm — the `validate_contrato_caixa` arg must be
10301        // observed through the lifted [`WitContract::source`] accessor,
10302        // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
10303        // value routes through the shared
10304        // [`crate::render::require_valid_dns_1123_label`] floor with the
10305        // accessor-projected value; the fired
10306        // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
10307        // the offending edge's `.source()`, pinning that the arg + the
10308        // downstream `caixa: caixa.to_string()` wrap route through the
10309        // same accessor's read path.
10310        let mut s = three_member_spec();
10311        let malformed = contract_http("BAD_NAME", "catalog", "/x");
10312        s.contratos.push(malformed.clone());
10313        let err = s.validate().unwrap_err();
10314        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
10315            panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
10316        };
10317        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
10318        assert_eq!(
10319            caixa,
10320            malformed.source(),
10321            "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
10322             byte-equal WitContract::source — the shape-gate arg + wrap \
10323             envelope must route through the lifted accessor rather \
10324             than the raw &c.de &String-borrow"
10325        );
10326    }
10327
10328    #[test]
10329    fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
10330        // Symmetric arm to the sibling `:de` malformed-shape pin above,
10331        // on the `:para` axis. Pins the shape-gate arg + wrap envelope
10332        // route through the lifted [`WitContract::destination`]
10333        // accessor. `:para` runs after the `:de` shape gate in the
10334        // canonical edge-direction order, so the `:de` value must be
10335        // well-shaped for the `:para` gate to fire — the `cart` :de is
10336        // canonical.
10337        let mut s = three_member_spec();
10338        let malformed = contract_http("cart", "BAD_NAME", "/x");
10339        s.contratos.push(malformed.clone());
10340        let err = s.validate().unwrap_err();
10341        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
10342            panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
10343        };
10344        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
10345        assert_eq!(
10346            caixa,
10347            malformed.destination(),
10348            "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
10349             byte-equal WitContract::destination — the shape-gate arg + \
10350             wrap envelope must route through the lifted accessor \
10351             rather than the raw &c.para &String-borrow"
10352        );
10353    }
10354
10355    // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
10356
10357    #[test]
10358    fn rejects_contrato_de_empty() {
10359        // `:de ""` previously fell through to `ContratoMemberMissing`
10360        // (with `caixa: ""`) because the validated `:membros :caixa`
10361        // set never contains the empty string. The narrower
10362        // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
10363        // the offending slot.
10364        let mut s = three_member_spec();
10365        s.contratos.push(contract_http("", "catalog", "/x"));
10366        let err = s.validate().unwrap_err();
10367        assert_eq!(
10368            err,
10369            AplicacaoError::ContratoCaixaEmpty {
10370                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
10371            },
10372            "got {err:?}"
10373        );
10374    }
10375
10376    #[test]
10377    fn rejects_contrato_para_empty() {
10378        // Symmetric arm to `:de ""` — `:para ""` previously fell
10379        // through to `ContratoMemberMissing { caixa: "" }`.
10380        let mut s = three_member_spec();
10381        s.contratos.push(contract_http("cart", "", "/x"));
10382        let err = s.validate().unwrap_err();
10383        assert_eq!(
10384            err,
10385            AplicacaoError::ContratoCaixaEmpty {
10386                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
10387            },
10388            "got {err:?}"
10389        );
10390    }
10391
10392    #[test]
10393    fn rejects_contrato_de_with_uppercase() {
10394        // The canonical "I copied the Servico's TitleCase display
10395        // name from an ADR" typo. Until this gate landed `:de "Cart"`
10396        // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
10397        // as "this caixa isn't in `:membros`" when the root cause is
10398        // "this `:de` value's shape can never legitimately match a
10399        // validated member (DNS-1123 labels are lowercase)". The
10400        // narrower diagnostic names the offending slot, the value
10401        // verbatim, and the parser-shaped reason.
10402        let mut s = three_member_spec();
10403        s.contratos.push(contract_http("Cart", "catalog", "/x"));
10404        let err = s.validate().unwrap_err();
10405        let AplicacaoError::ContratoCaixaInvalid {
10406            slot,
10407            caixa,
10408            reason,
10409        } = err
10410        else {
10411            panic!("expected ContratoCaixaInvalid, got other variant");
10412        };
10413        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
10414        assert_eq!(caixa, "Cart");
10415        assert!(
10416            reason.contains("uppercase"),
10417            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
10418        );
10419    }
10420
10421    #[test]
10422    fn rejects_contrato_para_with_underscore() {
10423        // The canonical "I'm thinking of a Python module" leak —
10424        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
10425        // Pin the `:para` axis surfaces the same diagnostic shape as
10426        // the `:de` axis on the underscore violation.
10427        let mut s = three_member_spec();
10428        s.contratos.push(contract_http("cart", "my_catalog", "/x"));
10429        let err = s.validate().unwrap_err();
10430        assert!(
10431            matches!(
10432                err,
10433                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
10434                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
10435            ),
10436            "got {err:?}"
10437        );
10438    }
10439
10440    #[test]
10441    fn rejects_contrato_de_with_dot() {
10442        // A `:contratos :de` value is a single DNS-1123 *label*, not
10443        // a subdomain — mirroring the `:membros :caixa` floor. The
10444        // strictest floor among the use sites wins.
10445        let mut s = three_member_spec();
10446        s.contratos
10447            .push(contract_http("team.cart", "catalog", "/x"));
10448        let err = s.validate().unwrap_err();
10449        assert!(
10450            matches!(
10451                err,
10452                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
10453                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
10454            ),
10455            "got {err:?}"
10456        );
10457    }
10458
10459    #[test]
10460    fn rejects_contrato_para_with_unicode() {
10461        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
10462        // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
10463        // validity check rejects multi-byte UTF-8 by the first
10464        // non-`[a-z0-9-]` byte.
10465        let mut s = three_member_spec();
10466        s.contratos.push(contract_http("cart", "café", "/x"));
10467        let err = s.validate().unwrap_err();
10468        assert!(
10469            matches!(
10470                err,
10471                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
10472                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
10473            ),
10474            "got {err:?}"
10475        );
10476    }
10477
10478    #[test]
10479    fn rejects_contrato_de_with_leading_hyphen() {
10480        // DNS-1123 boundary rule: labels must start and end with an
10481        // alphanumeric. K8s rejects `-cart` outright; the narrower
10482        // shape diagnostic now names the violation at caixa-build
10483        // time rather than the misframed membership-lookup arm.
10484        let mut s = three_member_spec();
10485        s.contratos.push(contract_http("-cart", "catalog", "/x"));
10486        let err = s.validate().unwrap_err();
10487        assert!(
10488            matches!(
10489                err,
10490                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
10491                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
10492            ),
10493            "got {err:?}"
10494        );
10495    }
10496
10497    #[test]
10498    fn contrato_de_empty_takes_precedence_over_invalid() {
10499        // Order pin: the `ContratoCaixaEmpty` arm fires before the
10500        // `ContratoCaixaInvalid` parse-side arm — same empty-first
10501        // cascade `validate_membro_caixa` / `validate_placement_cluster`
10502        // / `validate_entrada_host` already establish on their peer
10503        // name axes. The empty string is a structurally distinct
10504        // authoring footgun (the author left the field blank, vs.
10505        // typed a malformed value), so it gets its own diagnostic.
10506        let mut s = three_member_spec();
10507        s.contratos.push(contract_http("", "catalog", "/x"));
10508        let err = s.validate().unwrap_err();
10509        assert_eq!(
10510            err,
10511            AplicacaoError::ContratoCaixaEmpty {
10512                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
10513            }
10514        );
10515    }
10516
10517    #[test]
10518    fn contrato_de_shape_fires_before_para_shape() {
10519        // Per-axis order pin: within one `:contratos` entry, the `:de`
10520        // shape gate fires before the `:para` shape gate — same
10521        // edge-direction order the existing `ContratoMemberMissing` /
10522        // `ContratoSelfLoop` / target-dispatch checks use, so the
10523        // diagnostic for a contract with both `:de` and `:para`
10524        // malformed is stable. Authors fixing the surfaced `:de`
10525        // first will see `:para`'s diagnostic on re-run.
10526        let mut s = three_member_spec();
10527        s.contratos.push(contract_http("Cart", "Catalog", "/x"));
10528        let err = s.validate().unwrap_err();
10529        assert!(
10530            matches!(
10531                err,
10532                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
10533                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
10534            ),
10535            "got {err:?}"
10536        );
10537    }
10538
10539    #[test]
10540    fn contrato_shape_fires_before_membership_lookup() {
10541        // The load-bearing pin: an invalid-shape `:de` surfaces its
10542        // *own* diagnostic, not the misframed `ContratoMemberMissing`.
10543        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
10544        // an invalid-shape `:de` could never legitimately match any
10545        // member — the prior `ContratoMemberMissing` diagnostic was
10546        // a structural impossibility framed as a graph-membership
10547        // failure. The shape gate now routes every such input through
10548        // the narrower self-locating diagnostic.
10549        let mut s = three_member_spec();
10550        s.contratos.push(contract_http("Cart", "catalog", "/x"));
10551        let err = s.validate().unwrap_err();
10552        assert!(
10553            matches!(
10554                err,
10555                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
10556            ),
10557            "got {err:?}"
10558        );
10559        // And the symmetric case: an invalid-shape `:para` surfaces
10560        // its own diagnostic too, even when `:de` is well-shaped.
10561        let mut s = three_member_spec();
10562        s.contratos.push(contract_http("cart", "Catalog", "/x"));
10563        let err = s.validate().unwrap_err();
10564        assert!(
10565            matches!(
10566                err,
10567                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
10568            ),
10569            "got {err:?}"
10570        );
10571    }
10572
10573    #[test]
10574    fn contrato_shape_fires_before_self_edge_check() {
10575        // A `:de "Cart" :para "Cart"` entry is two distinct authoring
10576        // bugs: the shape violation (uppercase) and the self-edge
10577        // violation. The narrower per-axis shape diagnostic surfaces
10578        // first because fixing the shape may reveal that the author
10579        // also meant to point `:para` at a different member — the
10580        // self-edge framing is only useful once both endpoints have
10581        // valid shape.
10582        let mut s = three_member_spec();
10583        s.contratos.push(contract_http("Cart", "Cart", "/x"));
10584        let err = s.validate().unwrap_err();
10585        assert!(
10586            matches!(
10587                err,
10588                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
10589                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
10590            ),
10591            "got {err:?}"
10592        );
10593    }
10594
10595    #[test]
10596    fn contrato_well_shaped_phantom_still_raises_member_missing() {
10597        // Strict-improvement pin: a well-shaped `:de` that simply
10598        // isn't in `:membros` (a phantom reference — author meant
10599        // to add the member but didn't, or renamed and missed an
10600        // update) still surfaces `ContratoMemberMissing`, unchanged.
10601        // The shape gate only intercepts inputs that could never
10602        // legitimately match a validated member; legitimately-shaped
10603        // phantom references remain on the graph-membership axis.
10604        let mut s = three_member_spec();
10605        s.contratos
10606            .push(contract_http("phantom-shim", "catalog", "/x"));
10607        let err = s.validate().unwrap_err();
10608        assert!(
10609            matches!(
10610                err,
10611                AplicacaoError::ContratoMemberMissing { ref caixa }
10612                    if caixa == "phantom-shim"
10613            ),
10614            "got {err:?}"
10615        );
10616    }
10617
10618    #[test]
10619    fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
10620        // The diagnostic-shape pin: the error names the offending
10621        // slot (`:de` or `:para`) verbatim and the offending value
10622        // verbatim plus a non-empty parser-shaped reason, so the
10623        // author can grep their caixa.lisp for `:de "<name>"` /
10624        // `:para "<name>"` and fix it in one edit. Same diagnostic
10625        // shape as `MembroCaixaInvalid` (3f9d7a0) and
10626        // `PlacementClusterInvalid` (6c8c00b).
10627        let mut s = three_member_spec();
10628        s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
10629        let err = s.validate().unwrap_err();
10630        let AplicacaoError::ContratoCaixaInvalid {
10631            slot,
10632            caixa,
10633            reason,
10634        } = err
10635        else {
10636            panic!("expected ContratoCaixaInvalid, got {err:?}");
10637        };
10638        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
10639        assert_eq!(caixa, "BAD_NAME");
10640        assert!(
10641            !reason.is_empty(),
10642            "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
10643        );
10644    }
10645
10646    #[test]
10647    fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
10648        // Scalar-value pin: the two author-facing kebab-case labels the
10649        // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
10650        // admits on the `:contratos` per-entry endpoint-shape axis,
10651        // one arm per typed sub-slot. Mirrors the peer scalar-value
10652        // pin the sibling top-level M2 / M3 / Supervisor
10653        // author-facing-label consts carry
10654        // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
10655        // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
10656        // slot itself), so every altitude of the typed-slot algebra
10657        // shares the same "one canonical byte-string per arm"
10658        // discipline. A future rebrand (`:de` → `:from` matching the
10659        // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
10660        // sibling, `:para` → `:to` matching the same, or
10661        // `:de`/`:para` → `:source`/`:target` matching the WIT
10662        // world's `import`/`export` half-vocabulary) lands as an
10663        // edit to exactly one const, and every consumer that reaches
10664        // for the label picks it up at build time rather than at
10665        // runtime as a downstream `ContratoCaixaEmpty` /
10666        // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
10667        // diagnostic mismatch far from the rename's commit.
10668        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
10669        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
10670    }
10671
10672    #[test]
10673    fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
10674        // Production-through-const pin: the two per-axis labels the
10675        // per-`:contratos` entry endpoint-shape gate at
10676        // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
10677        // argument to [`validate_contrato_caixa`] route through the
10678        // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
10679        // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
10680        // future rebrand that reaches the const but not the gate (or
10681        // vice versa) surfaces here at build time rather than at
10682        // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
10683        // `slot: <stale-kebab-case>` diagnostic far from the rename's
10684        // commit. Mirror of the peer
10685        // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
10686        // pin (882f498) on the sibling M3 top-level slot axis.
10687        let mut s = three_member_spec();
10688        s.contratos.push(contract_http("", "catalog", "/x"));
10689        assert_eq!(
10690            s.validate().unwrap_err(),
10691            AplicacaoError::ContratoCaixaEmpty {
10692                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
10693            }
10694        );
10695        let mut s = three_member_spec();
10696        s.contratos.push(contract_http("cart", "", "/x"));
10697        assert_eq!(
10698            s.validate().unwrap_err(),
10699            AplicacaoError::ContratoCaixaEmpty {
10700                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
10701            }
10702        );
10703    }
10704
10705    #[test]
10706    fn accepts_canonical_contrato_caixa_forms() {
10707        // The DNS-1123 label shapes a caixa author is realistically
10708        // going to write on a `:contratos :de` / `:para`. Pin every
10709        // leg so a future tightening that bans (e.g.) digit-start
10710        // identifiers surfaces here, mirroring
10711        // `accepts_canonical_membro_caixa_forms` on the peer name
10712        // axis.
10713        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
10714            let mut s = three_member_spec();
10715            s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
10716            s.contratos = vec![contract_http("checkout", form, "/x")];
10717            s.entrada = None;
10718            s.validate().unwrap_or_else(|e| {
10719                panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
10720            });
10721
10722            let mut s = three_member_spec();
10723            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
10724            s.contratos = vec![contract_http(form, "catalog", "/x")];
10725            s.entrada = None;
10726            s.validate().unwrap_or_else(|e| {
10727                panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
10728            });
10729        }
10730    }
10731
10732    #[test]
10733    fn rejects_empty_wit() {
10734        let mut s = three_member_spec();
10735        s.contratos.push(WitContract {
10736            de: "cart".into(),
10737            para: "catalog".into(),
10738            wit: String::new(),
10739            endpoint: None,
10740            subject: None,
10741            slot: None,
10742        });
10743        let err = s.validate().unwrap_err();
10744        assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
10745    }
10746
10747    #[test]
10748    fn rejects_entrada_to_unknown_member() {
10749        let mut s = three_member_spec();
10750        s.entrada.as_mut().unwrap().para = "phantom".into();
10751        assert!(matches!(
10752            s.validate().unwrap_err(),
10753            AplicacaoError::EntradaMemberMissing { .. }
10754        ));
10755    }
10756
10757    // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
10758
10759    #[test]
10760    fn rejects_entrada_para_empty() {
10761        // `:para ""` previously fell through to
10762        // `EntradaMemberMissing { para: "" }` because the validated
10763        // `:membros :caixa` set never contains the empty string. The
10764        // narrower `EntradaParaEmpty` diagnostic now names the
10765        // offending slot directly — same empty-first cascade
10766        // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
10767        // `ContratoCaixaEmpty` establish on the peer name axes.
10768        let mut s = three_member_spec();
10769        s.entrada.as_mut().unwrap().para = String::new();
10770        let err = s.validate().unwrap_err();
10771        assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
10772    }
10773
10774    #[test]
10775    fn rejects_entrada_para_with_uppercase() {
10776        // The canonical "I copied the Servico's TitleCase display
10777        // name from an ADR" typo. Until this gate landed `:para "Cart"`
10778        // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
10779        // as "this caixa isn't in `:membros`" when the root cause is
10780        // "this `:para` value's shape can never legitimately match a
10781        // validated member (DNS-1123 labels are lowercase)". The
10782        // narrower diagnostic names the value verbatim plus the
10783        // parser-shaped reason.
10784        let mut s = three_member_spec();
10785        s.entrada.as_mut().unwrap().para = "Cart".into();
10786        let err = s.validate().unwrap_err();
10787        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
10788            panic!("expected EntradaParaInvalid, got other variant");
10789        };
10790        assert_eq!(para, "Cart");
10791        assert!(
10792            reason.contains("uppercase"),
10793            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
10794        );
10795    }
10796
10797    #[test]
10798    fn rejects_entrada_para_with_underscore() {
10799        // The canonical "I'm thinking of a Python module" leak —
10800        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
10801        let mut s = three_member_spec();
10802        s.entrada.as_mut().unwrap().para = "my_cart".into();
10803        let err = s.validate().unwrap_err();
10804        assert!(
10805            matches!(
10806                err,
10807                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
10808                    if para == "my_cart" && reason.contains('_')
10809            ),
10810            "got {err:?}"
10811        );
10812    }
10813
10814    #[test]
10815    fn rejects_entrada_para_with_dot() {
10816        // An `:entrada :para` value is a single DNS-1123 *label*, not
10817        // a subdomain — mirroring the `:membros :caixa` floor. The
10818        // strictest floor among the use sites wins.
10819        let mut s = three_member_spec();
10820        s.entrada.as_mut().unwrap().para = "team.cart".into();
10821        let err = s.validate().unwrap_err();
10822        assert!(
10823            matches!(
10824                err,
10825                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
10826                    if para == "team.cart" && reason.contains('.')
10827            ),
10828            "got {err:?}"
10829        );
10830    }
10831
10832    #[test]
10833    fn rejects_entrada_para_with_unicode() {
10834        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
10835        // (`xn--…`) before it reaches K8s.
10836        let mut s = three_member_spec();
10837        s.entrada.as_mut().unwrap().para = "café".into();
10838        let err = s.validate().unwrap_err();
10839        assert!(
10840            matches!(
10841                err,
10842                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
10843            ),
10844            "got {err:?}"
10845        );
10846    }
10847
10848    #[test]
10849    fn rejects_entrada_para_with_leading_hyphen() {
10850        // DNS-1123 boundary rule: labels must start and end with an
10851        // alphanumeric. K8s rejects `-cart` outright.
10852        let mut s = three_member_spec();
10853        s.entrada.as_mut().unwrap().para = "-cart".into();
10854        let err = s.validate().unwrap_err();
10855        assert!(
10856            matches!(
10857                err,
10858                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
10859                    if para == "-cart" && reason.contains("start and end")
10860            ),
10861            "got {err:?}"
10862        );
10863    }
10864
10865    #[test]
10866    fn rejects_entrada_para_with_trailing_hyphen() {
10867        // Symmetric boundary arm.
10868        let mut s = three_member_spec();
10869        s.entrada.as_mut().unwrap().para = "cart-".into();
10870        let err = s.validate().unwrap_err();
10871        assert!(
10872            matches!(
10873                err,
10874                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
10875                    if para == "cart-" && reason.contains("start and end")
10876            ),
10877            "got {err:?}"
10878        );
10879    }
10880
10881    #[test]
10882    fn rejects_entrada_para_too_long() {
10883        // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
10884        // bytes per label. K8s rejects longer names at admission on
10885        // every `metadata.name` axis.
10886        let mut s = three_member_spec();
10887        s.entrada.as_mut().unwrap().para = "a".repeat(64);
10888        let err = s.validate().unwrap_err();
10889        assert!(
10890            matches!(
10891                err,
10892                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
10893                    if para.len() == 64 && reason.contains("max length")
10894            ),
10895            "got {err:?}"
10896        );
10897    }
10898
10899    #[test]
10900    fn entrada_para_empty_takes_precedence_over_invalid() {
10901        // Order pin: the `EntradaParaEmpty` arm fires before the
10902        // `EntradaParaInvalid` parse-side arm — same empty-first
10903        // cascade `validate_membro_caixa` / `validate_placement_cluster`
10904        // / `validate_contrato_caixa` already establish.
10905        let mut s = three_member_spec();
10906        s.entrada.as_mut().unwrap().para = String::new();
10907        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
10908    }
10909
10910    #[test]
10911    fn entrada_para_shape_fires_before_membership_lookup() {
10912        // The load-bearing pin: an invalid-shape `:para` surfaces its
10913        // *own* diagnostic, not the misframed `EntradaMemberMissing`.
10914        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
10915        // an invalid-shape `:para` could never legitimately match any
10916        // member — the prior `EntradaMemberMissing` diagnostic framed
10917        // a structural impossibility as a graph-membership failure.
10918        let mut s = three_member_spec();
10919        s.entrada.as_mut().unwrap().para = "Cart".into();
10920        let err = s.validate().unwrap_err();
10921        assert!(
10922            matches!(
10923                err,
10924                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
10925            ),
10926            "got {err:?}"
10927        );
10928    }
10929
10930    #[test]
10931    fn entrada_para_shape_fires_before_host_gate() {
10932        // Per-`:entrada` order pin: the `:para` shape gate fires
10933        // before the `:host` gate, mirroring the existing
10934        // `entrada_host_member_missing_takes_precedence_over_host_invalid`
10935        // ordering where the member-lookup arm preceded the host gate.
10936        // The shape gate slots ahead of that, so a malformed `:para`
10937        // surfaces its own diagnostic even when `:host` is also wrong.
10938        let mut s = three_member_spec();
10939        let e = s.entrada.as_mut().unwrap();
10940        e.para = "Cart".into();
10941        e.host = "BAD HOST".into();
10942        let err = s.validate().unwrap_err();
10943        assert!(
10944            matches!(
10945                err,
10946                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
10947            ),
10948            "got {err:?}"
10949        );
10950    }
10951
10952    #[test]
10953    fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
10954        // Strict-improvement pin: a well-shaped `:para` that simply
10955        // isn't in `:membros` (a phantom reference — author meant to
10956        // add the member but didn't, or renamed and missed an
10957        // update) still surfaces `EntradaMemberMissing`, unchanged.
10958        // The shape gate only intercepts inputs that could never
10959        // legitimately match a validated member.
10960        let mut s = three_member_spec();
10961        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
10962        let err = s.validate().unwrap_err();
10963        assert!(
10964            matches!(
10965                err,
10966                AplicacaoError::EntradaMemberMissing { ref para }
10967                    if para == "phantom-shim"
10968            ),
10969            "got {err:?}"
10970        );
10971    }
10972
10973    #[test]
10974    fn entrada_para_invalid_diagnostic_carries_offending_para() {
10975        // The diagnostic-shape pin: the error names the offending
10976        // `:para` value verbatim plus a non-empty parser-shaped
10977        // reason, so the author can grep their caixa.lisp for
10978        // `:para "<name>"` and fix it in one edit. Same diagnostic
10979        // shape as `MembroCaixaInvalid` (3f9d7a0),
10980        // `PlacementClusterInvalid` (6c8c00b), and
10981        // `ContratoCaixaInvalid` (8d5af6b).
10982        let mut s = three_member_spec();
10983        s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
10984        let err = s.validate().unwrap_err();
10985        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
10986            panic!("expected EntradaParaInvalid, got {err:?}");
10987        };
10988        assert_eq!(para, "BAD_NAME");
10989        assert!(
10990            !reason.is_empty(),
10991            "EntradaParaInvalid `reason` must carry a parser-shaped wording"
10992        );
10993    }
10994
10995    #[test]
10996    fn accepts_canonical_entrada_para_forms() {
10997        // Positive-control sweep covering the DNS-1123 label shapes a
10998        // caixa author is realistically going to write on `:entrada
10999        // :para`. Pin every leg so a future tightening that bans
11000        // (e.g.) digit-start identifiers surfaces here, mirroring
11001        // `accepts_canonical_membro_caixa_forms` and
11002        // `accepts_canonical_contrato_caixa_forms` on the peer name
11003        // axes.
11004        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
11005            let mut s = three_member_spec();
11006            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
11007            s.contratos = vec![contract_http(form, "catalog", "/x")];
11008            s.entrada = Some(Entrada {
11009                host: "checkout.quero.cloud".into(),
11010                para: form.into(),
11011                paths: vec!["/api".into()],
11012                port: 8080,
11013            });
11014            s.validate().unwrap_or_else(|e| {
11015                panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
11016            });
11017        }
11018    }
11019
11020    #[test]
11021    fn rejects_replicated_without_clusters() {
11022        let mut s = three_member_spec();
11023        s.placement.clusters = vec![];
11024        assert!(matches!(
11025            s.validate().unwrap_err(),
11026            AplicacaoError::PlacementWithoutClusters { .. }
11027        ));
11028    }
11029
11030    #[test]
11031    fn rejects_sharded_without_key() {
11032        let mut s = three_member_spec();
11033        s.placement.estrategia = PlacementStrategy::Sharded;
11034        s.placement.shard_key = None;
11035        s.placement.clusters = vec!["rio".into()];
11036        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
11037    }
11038
11039    #[test]
11040    fn sharded_with_key_validates() {
11041        let mut s = three_member_spec();
11042        s.placement.estrategia = PlacementStrategy::Sharded;
11043        s.placement.shard_key = Some("$tenantId".into());
11044        s.validate().unwrap();
11045    }
11046
11047    #[test]
11048    fn round_trip_via_json_preserves_shape() {
11049        let s = three_member_spec();
11050        let json = serde_json::to_string(&s.membros).unwrap();
11051        let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
11052        assert_eq!(back, s.membros);
11053
11054        let json = serde_json::to_string(&s.contratos).unwrap();
11055        let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
11056        assert_eq!(back, s.contratos);
11057
11058        let json = serde_json::to_string(&s.placement).unwrap();
11059        let back: Placement = serde_json::from_str(&json).unwrap();
11060        assert_eq!(back, s.placement);
11061
11062        let json = serde_json::to_string(&s.entrada).unwrap();
11063        let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
11064        assert_eq!(back, s.entrada);
11065    }
11066
11067    #[test]
11068    fn rate_limit_round_trip_seconds() {
11069        let policy = MeshPolicy {
11070            rate_limit: Some(RateLimit {
11071                rate: 100,
11072                window: Duration::from_secs(1),
11073            }),
11074            ..Default::default()
11075        };
11076        let json = serde_json::to_string(&policy).unwrap();
11077        assert!(json.contains("\"100/s\""));
11078        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
11079        assert_eq!(back.rate_limit.unwrap().rate, 100);
11080        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
11081    }
11082
11083    #[test]
11084    fn rate_limit_round_trip_minutes() {
11085        let policy = MeshPolicy {
11086            rate_limit: Some(RateLimit {
11087                rate: 5000,
11088                window: Duration::from_secs(60),
11089            }),
11090            ..Default::default()
11091        };
11092        let json = serde_json::to_string(&policy).unwrap();
11093        assert!(json.contains("\"5000/m\""));
11094    }
11095
11096    #[test]
11097    fn circuit_breaker_round_trip() {
11098        let policy = MeshPolicy {
11099            circuit_breaker: Some(CircuitBreaker {
11100                max_failures: 5,
11101                window: Duration::from_secs(60),
11102            }),
11103            ..Default::default()
11104        };
11105        let json = serde_json::to_string(&policy).unwrap();
11106        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
11107        assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
11108        assert_eq!(
11109            back.circuit_breaker.unwrap().window,
11110            Duration::from_secs(60)
11111        );
11112    }
11113
11114    #[test]
11115    fn rejects_http_contrato_without_endpoint() {
11116        let mut s = three_member_spec();
11117        s.contratos.push(WitContract {
11118            de: "cart".into(),
11119            para: "catalog".into(),
11120            wit: "wasi:http/proxy".into(),
11121            endpoint: None,
11122            subject: None,
11123            slot: None,
11124        });
11125        let err = s.validate().unwrap_err();
11126        assert!(matches!(
11127            err,
11128            AplicacaoError::ContratoMissingTarget {
11129                expected: WitTarget::HTTP_FIELD_NAME,
11130                ..
11131            }
11132        ));
11133    }
11134
11135    #[test]
11136    fn rejects_http_contrato_with_subject() {
11137        let mut s = three_member_spec();
11138        s.contratos.push(WitContract {
11139            de: "cart".into(),
11140            para: "catalog".into(),
11141            wit: "wasi:http/proxy".into(),
11142            endpoint: Some("/x".into()),
11143            subject: Some("not.allowed.here".into()),
11144            slot: None,
11145        });
11146        let err = s.validate().unwrap_err();
11147        assert!(matches!(
11148            err,
11149            AplicacaoError::ContratoWrongTarget {
11150                expected: WitTarget::HTTP_FIELD_NAME,
11151                ..
11152            }
11153        ));
11154    }
11155
11156    #[test]
11157    fn rejects_pubsub_contrato_without_subject() {
11158        let mut s = three_member_spec();
11159        s.contratos.push(WitContract {
11160            de: "cart".into(),
11161            para: "catalog".into(),
11162            wit: "nats:pub-sub".into(),
11163            endpoint: None,
11164            subject: None,
11165            slot: None,
11166        });
11167        let err = s.validate().unwrap_err();
11168        assert!(matches!(
11169            err,
11170            AplicacaoError::ContratoMissingTarget {
11171                expected: WitTarget::PUBSUB_FIELD_NAME,
11172                ..
11173            }
11174        ));
11175    }
11176
11177    #[test]
11178    fn rejects_pubsub_contrato_with_endpoint() {
11179        let mut s = three_member_spec();
11180        s.contratos.push(WitContract {
11181            de: "cart".into(),
11182            para: "catalog".into(),
11183            wit: "kafka:topic".into(),
11184            endpoint: Some("/wrong".into()),
11185            subject: Some("topic.x".into()),
11186            slot: None,
11187        });
11188        let err = s.validate().unwrap_err();
11189        assert!(matches!(
11190            err,
11191            AplicacaoError::ContratoWrongTarget {
11192                expected: WitTarget::PUBSUB_FIELD_NAME,
11193                ..
11194            }
11195        ));
11196    }
11197
11198    #[test]
11199    fn rejects_store_contrato_without_slot() {
11200        let mut s = three_member_spec();
11201        s.contratos.push(WitContract {
11202            de: "cart".into(),
11203            para: "catalog".into(),
11204            wit: "wasi:keyvalue/store".into(),
11205            endpoint: None,
11206            subject: None,
11207            slot: None,
11208        });
11209        let err = s.validate().unwrap_err();
11210        assert!(matches!(
11211            err,
11212            AplicacaoError::ContratoMissingTarget {
11213                expected: WitTarget::STORE_FIELD_NAME,
11214                ..
11215            }
11216        ));
11217    }
11218
11219    // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
11220
11221    #[test]
11222    fn rejects_http_contrato_with_empty_endpoint() {
11223        // `Some("")` for an HTTP endpoint passes the presence check
11224        // (target() previously returned WitTarget::Http { endpoint: "" })
11225        // but renders as a `path: ""` Cilium L7 rule that matches no
11226        // traffic. Same value-shape footgun closed for :entrada :paths
11227        // entries (eb3456d).
11228        let mut s = three_member_spec();
11229        s.contratos.push(WitContract {
11230            de: "cart".into(),
11231            para: "catalog".into(),
11232            wit: "wasi:http/proxy".into(),
11233            endpoint: Some(String::new()),
11234            subject: None,
11235            slot: None,
11236        });
11237        let err = s.validate().unwrap_err();
11238        assert!(
11239            matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
11240                if de == "cart" && para == "catalog"),
11241            "got {err:?}"
11242        );
11243    }
11244
11245    #[test]
11246    fn rejects_http_contrato_with_relative_endpoint() {
11247        // Cilium L7 :path + Gateway API PathPrefix both require a
11248        // leading `/`. Same shape required of :entrada :paths
11249        // (eb3456d). Lifted into target() so every consumer of the
11250        // typed WitTarget view inherits the guarantee.
11251        let mut s = three_member_spec();
11252        s.contratos.push(WitContract {
11253            de: "cart".into(),
11254            para: "catalog".into(),
11255            wit: "wasi:http/proxy".into(),
11256            endpoint: Some("products/:id".into()),
11257            subject: None,
11258            slot: None,
11259        });
11260        let err = s.validate().unwrap_err();
11261        assert!(
11262            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
11263                if endpoint == "products/:id"),
11264            "got {err:?}"
11265        );
11266    }
11267
11268    #[test]
11269    fn rejects_pubsub_contrato_with_empty_subject() {
11270        // NATS / Kafka publish without a subject is a no-op subscribe;
11271        // never the author's intent. Same empty-string rejection as
11272        // :membros :caixa, :placement :clusters entries, :entrada
11273        // :paths entries — every value carried by every typed slot is
11274        // value-shape-checked at validate().
11275        let mut s = three_member_spec();
11276        s.contratos.push(WitContract {
11277            de: "cart".into(),
11278            para: "catalog".into(),
11279            wit: "nats:pub-sub".into(),
11280            endpoint: None,
11281            subject: Some(String::new()),
11282            slot: None,
11283        });
11284        let err = s.validate().unwrap_err();
11285        assert!(
11286            matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
11287                if de == "cart" && para == "catalog"),
11288            "got {err:?}"
11289        );
11290    }
11291
11292    #[test]
11293    fn rejects_store_contrato_with_empty_slot() {
11294        // An empty slot template addresses the bucket root, defeating
11295        // the per-key isolation the slot exists for — a footgun on
11296        // `wasi:keyvalue/store` whose closest analog is the empty
11297        // shard-key rejected on :placement Sharded (c7c7799).
11298        let mut s = three_member_spec();
11299        s.contratos.push(WitContract {
11300            de: "cart".into(),
11301            para: "catalog".into(),
11302            wit: "wasi:keyvalue/store".into(),
11303            endpoint: None,
11304            subject: None,
11305            slot: Some(String::new()),
11306        });
11307        let err = s.validate().unwrap_err();
11308        assert!(
11309            matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
11310                if de == "cart" && para == "catalog"),
11311            "got {err:?}"
11312        );
11313    }
11314
11315    #[test]
11316    fn http_contrato_root_endpoint_validates() {
11317        // Pin the boundary case: a single-`/` endpoint is the catch-all
11318        // form the Gateway HTTPRoute renderer falls back to when
11319        // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
11320        // must remain a valid contrato endpoint too.
11321        let mut s = three_member_spec();
11322        s.contratos.push(contract_http("cart", "catalog", "/"));
11323        s.validate().unwrap();
11324    }
11325
11326    // ── :contratos :endpoint value-shape gate ────────────────────────────
11327    //
11328    // Mirrors the `:entrada :paths` value-shape suite on the peer
11329    // HTTP-path axis. Until this gate landed `WitContract::target()`
11330    // only refused the empty string + the missing-leading-`/` form
11331    // (c4213a4); a structurally invalid endpoint passed validate and
11332    // landed verbatim as a Cilium L7 `path:` rule
11333    // (caixa-mesh/src/lib.rs:311) that either silently dropped all
11334    // traffic or was rejected at apply time by Cilium policy admission.
11335    // Every authoring footgun the K8s Gateway API webhook / Cilium
11336    // policy validator would catch on admission now becomes a caixa-
11337    // build-time `ContratoEndpointInvalid` with the offending
11338    // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
11339    // shape as `EntradaPathInvalid` on the sibling axis; same shared
11340    // predicate (`crate::render::is_gateway_api_http_path`) ensures
11341    // drift between the two axes' rule enforcement is a build error
11342    // at the predicate.
11343
11344    fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
11345        // Fresh spec per call so the would-be-duplicate edge
11346        // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
11347        // `three_member_spec`'s pre-existing
11348        // `(cart, catalog, …, /products/:id)` entry — only the
11349        // endpoint payload differs.
11350        let mut s = three_member_spec();
11351        s.contratos.push(contract_http("cart", "catalog", ep));
11352        s.validate().unwrap_err()
11353    }
11354
11355    #[test]
11356    fn rejects_http_contrato_endpoint_with_query() {
11357        // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
11358        // silently rendered as a Cilium L7 `path: "/charge?token=X"`
11359        // rule the L7 matcher would never satisfy.
11360        let err = contrato_endpoint_err("/charge?token=X");
11361        assert!(
11362            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
11363                if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
11364            "got {err:?}"
11365        );
11366    }
11367
11368    #[test]
11369    fn rejects_http_contrato_endpoint_with_fragment() {
11370        let err = contrato_endpoint_err("/charge#frag");
11371        assert!(
11372            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
11373                if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
11374            "got {err:?}"
11375        );
11376    }
11377
11378    #[test]
11379    fn rejects_http_contrato_endpoint_with_whitespace() {
11380        let err = contrato_endpoint_err("/foo bar");
11381        assert!(
11382            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
11383                if endpoint == "/foo bar" && reason.contains("whitespace")),
11384            "got {err:?}"
11385        );
11386    }
11387
11388    #[test]
11389    fn rejects_http_contrato_endpoint_with_control_char() {
11390        let err = contrato_endpoint_err("/api/\x01bar");
11391        assert!(
11392            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
11393                if endpoint == "/api/\x01bar" && reason.contains("control character")),
11394            "got {err:?}"
11395        );
11396    }
11397
11398    #[test]
11399    fn rejects_http_contrato_endpoint_with_non_ascii() {
11400        let err = contrato_endpoint_err("/api/café");
11401        assert!(
11402            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
11403                if endpoint == "/api/café" && reason.contains("non-ASCII")),
11404            "got {err:?}"
11405        );
11406    }
11407
11408    #[test]
11409    fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
11410        let err = contrato_endpoint_err("/api//cart");
11411        assert!(
11412            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
11413                if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
11414            "got {err:?}"
11415        );
11416    }
11417
11418    #[test]
11419    fn rejects_http_contrato_endpoint_with_dot_segment() {
11420        let err = contrato_endpoint_err("/api/./cart");
11421        assert!(
11422            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
11423                if endpoint == "/api/./cart" && reason.contains("`.` segment")),
11424            "got {err:?}"
11425        );
11426    }
11427
11428    #[test]
11429    fn rejects_http_contrato_endpoint_with_parent_segment() {
11430        // Path-traversal in a contrato endpoint is the canonical
11431        // "L7 rule that the workload's HTTP server's path-resolution
11432        // logic interprets differently than the policy enforcer"
11433        // footgun. Rejected outright at validate time.
11434        let err = contrato_endpoint_err("/api/../etc");
11435        assert!(
11436            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
11437                if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
11438            "got {err:?}"
11439        );
11440    }
11441
11442    #[test]
11443    fn rejects_http_contrato_endpoint_too_long() {
11444        // 1025-byte endpoint — one over the Gateway API
11445        // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
11446        // path matcher has no inherent length limit but the policy
11447        // CR itself rides through the K8s apiserver, which enforces
11448        // ConfigMap-shaped limits; sharing the Gateway API cap is the
11449        // conservative floor.
11450        let big = format!("/api/{}", "a".repeat(1020));
11451        assert_eq!(big.len(), 1025);
11452        let err = contrato_endpoint_err(&big);
11453        assert!(
11454            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
11455                if endpoint == &big && reason.contains("max length of 1024")),
11456            "got {err:?}"
11457        );
11458    }
11459
11460    #[test]
11461    fn http_contrato_endpoint_max_length_validates() {
11462        // 1024-byte endpoint — exactly the cap. Boundary pin: drift
11463        // in the cap surfaces here and at
11464        // `rejects_http_contrato_endpoint_too_long` simultaneously,
11465        // mirroring `entrada_path_max_length_validates` on the peer
11466        // axis.
11467        let big = format!("/api/{}", "a".repeat(1019));
11468        assert_eq!(big.len(), 1024);
11469        let mut s = three_member_spec();
11470        s.contratos.push(contract_http("cart", "catalog", &big));
11471        s.validate().unwrap();
11472    }
11473
11474    #[test]
11475    fn http_contrato_endpoint_accepts_canonical_forms() {
11476        // Positive-set sweep: every canonical HTTP-path shape the
11477        // sibling `:entrada :paths` axis accepts (the bare-root `/`,
11478        // plain paths, hidden-file-style `.config` segments distinct
11479        // from the `.` segment, digit-bearing segments, the canonical
11480        // route-template `:param` form, trailing-slash form,
11481        // percent-encoded segments, the `/foo..bar` interior-`..`-
11482        // substring forms that are NOT `..` segments) must remain a
11483        // valid contrato endpoint too. Drift between this list and
11484        // the entrada path positive sweep surfaces at the shared
11485        // `is_gateway_api_http_path` substrate-side suite — one
11486        // source of truth. Uses a fresh `(payment, catalog)` edge so
11487        // none of the swept endpoints collide with the pre-existing
11488        // `(cart, catalog, /products/:id)` / `(cart, payment,
11489        // /charge)` entries in `three_member_spec`.
11490        for ep in [
11491            "/",
11492            "/charge",
11493            "/v1/charge",
11494            "/api/.config",
11495            "/products/:id",
11496            "/api/cart/",
11497            "/api/caf%C3%A9",
11498            "/foo..bar",
11499            "/...",
11500        ] {
11501            let mut s = three_member_spec();
11502            s.contratos.push(contract_http("payment", "catalog", ep));
11503            s.validate()
11504                .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
11505        }
11506    }
11507
11508    #[test]
11509    fn contrato_endpoint_empty_takes_precedence_over_invalid() {
11510        // Ordering pin: `ContratoEndpointEmpty` is the more self-
11511        // locating diagnostic on `""` and must lead — the value-
11512        // shape gate is only reached after the empty-check fires.
11513        // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
11514        // on the peer axis.
11515        let mut s = three_member_spec();
11516        s.contratos.push(WitContract {
11517            de: "cart".into(),
11518            para: "catalog".into(),
11519            wit: "wasi:http/proxy".into(),
11520            endpoint: Some(String::new()),
11521            subject: None,
11522            slot: None,
11523        });
11524        let err = s.validate().unwrap_err();
11525        assert!(
11526            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
11527            "got {err:?}"
11528        );
11529    }
11530
11531    #[test]
11532    fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
11533        // Ordering pin: an endpoint without a leading `/` surfaces the
11534        // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
11535        // value-shape gate is only consulted on endpoints that already
11536        // satisfy the absolute-prefix invariant. Mirrors
11537        // `entrada_path_not_absolute_takes_precedence_over_invalid`.
11538        let err = contrato_endpoint_err("bad path");
11539        assert!(
11540            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
11541                if endpoint == "bad path"),
11542            "got {err:?}"
11543        );
11544    }
11545
11546    #[test]
11547    fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
11548        // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
11549        // `:para` + a non-empty reason flow through verbatim so the
11550        // author can grep their caixa.lisp for the offending contrato
11551        // block and fix it in one edit. Same shape as
11552        // `entrada_path_diagnostic_carries_offending_path`.
11553        let err = contrato_endpoint_err("/api?q=1");
11554        match err {
11555            AplicacaoError::ContratoEndpointInvalid {
11556                de,
11557                para,
11558                endpoint,
11559                reason,
11560            } => {
11561                assert_eq!(de, "cart");
11562                assert_eq!(para, "catalog");
11563                assert_eq!(endpoint, "/api?q=1");
11564                assert!(!reason.is_empty(), "reason field must be non-empty");
11565            }
11566            other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
11567        }
11568    }
11569
11570    #[test]
11571    fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
11572        // The compounding theorem: every &str inside a WitTarget
11573        // returned by target() is non-empty (and absolute, for Http).
11574        // Renderers downstream of typed_view() can rely on this
11575        // without re-checking — the type system carries the proof.
11576        let http = contract_http("cart", "catalog", "/x");
11577        match http.target().unwrap() {
11578            WitTarget::Http { endpoint } => {
11579                assert!(!endpoint.is_empty());
11580                assert!(endpoint.starts_with('/'));
11581            }
11582            other => panic!("expected Http, got {other:?}"),
11583        }
11584        let nats = WitContract {
11585            de: "a".into(),
11586            para: "b".into(),
11587            wit: "nats:pub-sub".into(),
11588            endpoint: None,
11589            subject: Some("topic.x".into()),
11590            slot: None,
11591        };
11592        match nats.target().unwrap() {
11593            WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
11594            other => panic!("expected PubSub, got {other:?}"),
11595        }
11596        let kv = WitContract {
11597            de: "a".into(),
11598            para: "b".into(),
11599            wit: "wasi:keyvalue/store".into(),
11600            endpoint: None,
11601            subject: None,
11602            slot: Some("checkout/$orderId".into()),
11603        };
11604        match kv.target().unwrap() {
11605            WitTarget::Store { slot } => assert!(!slot.is_empty()),
11606            other => panic!("expected Store, got {other:?}"),
11607        }
11608    }
11609
11610    #[test]
11611    fn target_diagnostic_names_offending_endpoint_value() {
11612        // When the malformed endpoint string is non-trivial, the
11613        // diagnostic carries the actual value back to the author —
11614        // not a generic "endpoint malformed" error.
11615        let bad = WitContract {
11616            de: "src".into(),
11617            para: "dst".into(),
11618            wit: "wasi:http/proxy".into(),
11619            endpoint: Some("api/v1/charge".into()),
11620            subject: None,
11621            slot: None,
11622        };
11623        match bad.target().unwrap_err() {
11624            AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
11625                assert_eq!(de, "src");
11626                assert_eq!(para, "dst");
11627                assert_eq!(endpoint, "api/v1/charge");
11628            }
11629            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
11630        }
11631    }
11632
11633    #[test]
11634    fn rejects_unknown_wit_with_target_set() {
11635        let mut s = three_member_spec();
11636        s.contratos.push(WitContract {
11637            de: "cart".into(),
11638            para: "catalog".into(),
11639            wit: "custom:exchange".into(),
11640            endpoint: Some("/leaked".into()),
11641            subject: None,
11642            slot: None,
11643        });
11644        let err = s.validate().unwrap_err();
11645        assert!(matches!(
11646            err,
11647            AplicacaoError::ContratoWrongTarget {
11648                expected: WitTarget::CAPABILITY_EXPECTED,
11649                ..
11650            }
11651        ));
11652    }
11653
11654    #[test]
11655    fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
11656        // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
11657        // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
11658        // fourth arm of the same "which payload field name goes in the
11659        // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
11660        // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
11661        // consts cover on the peer HTTP / PubSub / Store arms
11662        // (`wit_target_field_name_pins_per_variant`). Until this lift
11663        // landed the byte-string sat twice — once inline in the
11664        // [`WitContract::target`] Capability-arm rejection at the
11665        // production dispatch, once in `rejects_unknown_wit_with_target_set`
11666        // pinning against the same literal — with no compile-time link
11667        // between them. Same "one canonical declaration, next to the
11668        // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
11669        // lift established for the payload-less arm's human-readable
11670        // label axis; this test is the shape peer of
11671        // `wit_target_label_pins_per_variant`'s Capability-arm assertion
11672        // pair (routes-through-const + scalar-value pin) on the
11673        // wrong-target diagnostic-scalar axis.
11674        //
11675        // Fail-before-pass-after was verified locally by mutating the
11676        // const declaration to `"capability"` — the scalar-value pin
11677        // below fires (`"capability" != "none"`) and the routes-through
11678        // assertion below still holds (production and const walk in
11679        // lockstep), which is the correct behavior: a rename on the
11680        // const drifts here first, not at a downstream consumer.
11681        assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
11682
11683        let mut s = three_member_spec();
11684        s.contratos.push(WitContract {
11685            de: "cart".into(),
11686            para: "catalog".into(),
11687            wit: "custom:exchange".into(),
11688            endpoint: Some("/leaked".into()),
11689            subject: None,
11690            slot: None,
11691        });
11692        match s.validate().unwrap_err() {
11693            AplicacaoError::ContratoWrongTarget { expected, .. } => {
11694                assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
11695            }
11696            other => panic!("expected ContratoWrongTarget, got {other:?}"),
11697        }
11698    }
11699
11700    #[test]
11701    fn unknown_wit_capability_only_validates() {
11702        let mut s = three_member_spec();
11703        s.contratos.push(WitContract {
11704            de: "cart".into(),
11705            para: "catalog".into(),
11706            // A WIT world we haven't yet shaped — accept it as a typed
11707            // capability edge so authors aren't blocked while the WIT
11708            // registry catches up. No payload field may be carried.
11709            wit: "custom:exchange".into(),
11710            endpoint: None,
11711            subject: None,
11712            slot: None,
11713        });
11714        s.validate().unwrap();
11715        let added = s.contratos.last().unwrap();
11716        assert_eq!(added.target().unwrap(), WitTarget::Capability);
11717    }
11718
11719    #[test]
11720    fn target_typed_view_round_trips_each_shape() {
11721        let http = contract_http("cart", "catalog", "/products/:id");
11722        assert_eq!(
11723            http.target().unwrap(),
11724            WitTarget::Http {
11725                endpoint: "/products/:id"
11726            }
11727        );
11728        let nats = WitContract {
11729            de: "a".into(),
11730            para: "b".into(),
11731            wit: "nats:pub-sub".into(),
11732            endpoint: None,
11733            subject: Some("topic.x".into()),
11734            slot: None,
11735        };
11736        assert_eq!(
11737            nats.target().unwrap(),
11738            WitTarget::PubSub { subject: "topic.x" }
11739        );
11740        let kv = WitContract {
11741            de: "a".into(),
11742            para: "b".into(),
11743            wit: "wasi:keyvalue/store".into(),
11744            endpoint: None,
11745            subject: None,
11746            slot: Some("checkout/$orderId".into()),
11747        };
11748        assert_eq!(
11749            kv.target().unwrap(),
11750            WitTarget::Store {
11751                slot: "checkout/$orderId"
11752            }
11753        );
11754    }
11755
11756    #[test]
11757    fn wit_contract_kind_predicates() {
11758        let http = contract_http("a", "b", "/x");
11759        assert!(http.is_http());
11760        assert!(!http.is_pubsub());
11761        assert!(!http.is_store());
11762        assert!(!http.is_capability());
11763
11764        let nats = WitContract {
11765            de: "a".into(),
11766            para: "b".into(),
11767            wit: "nats:pub-sub".into(),
11768            endpoint: None,
11769            subject: Some("topic.x".into()),
11770            slot: None,
11771        };
11772        assert!(nats.is_pubsub());
11773        assert!(!nats.is_http());
11774        assert!(!nats.is_capability());
11775
11776        let kv = WitContract {
11777            de: "a".into(),
11778            para: "b".into(),
11779            wit: "wasi:keyvalue/store".into(),
11780            endpoint: None,
11781            subject: None,
11782            slot: Some("checkout/$orderId".into()),
11783        };
11784        assert!(kv.is_store());
11785        assert!(!kv.is_http());
11786        assert!(!kv.is_capability());
11787
11788        // Fourth arm on the paired closed-set predicate family: the
11789        // payload-less capability edge that projects to the payload-
11790        // less [`WitTarget::Capability`] arm under [`WitContract::target`].
11791        // Extends the 3-arm predicate sweep this test opened to cover
11792        // the closed 4-way partition [`WitContract::is_capability`]
11793        // closes on the pre-projection WIT-shape axis, matched with the
11794        // sibling post-projection [`WitTarget`]-side `IsVariant`-derived
11795        // 4-arm predicate set.
11796        let cap = WitContract {
11797            de: "a".into(),
11798            para: "b".into(),
11799            wit: "custom:capability-only".into(),
11800            endpoint: None,
11801            subject: None,
11802            slot: None,
11803        };
11804        assert!(cap.is_capability());
11805        assert!(!cap.is_http());
11806        assert!(!cap.is_pubsub());
11807        assert!(!cap.is_store());
11808    }
11809
11810    // ── :contratos :wit value-shape gate ─────────────────────────────────
11811    //
11812    // Mirrors the `:contratos :endpoint` value-shape suite on the peer
11813    // dispatch-discriminator axis. Until this gate landed
11814    // `WitContract::target()` accepted any non-empty string and
11815    // silently demoted unrecognized shapes to a capability-only L4
11816    // edge — the canonical "I thought I had L7 HTTP routing, got
11817    // L4-only" footgun. Every authoring footgun the WIT registry's
11818    // own grammar rejects (uppercase, hyphen-for-colon typo,
11819    // whitespace, empty package, doubled `@`, …) now becomes a
11820    // caixa-build-time `ContratoWitInvalid` with the offending
11821    // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
11822    // as `ContratoEndpointInvalid` on the sibling axis; same shared
11823    // predicate (`crate::render::is_wit_world_ref`) ensures drift
11824    // between any two axes' rule enforcement is a build error at the
11825    // predicate, not piecemeal across renderers.
11826
11827    fn contrato_wit_err(wit: &str) -> AplicacaoError {
11828        // Fresh spec per call so the new contract doesn't collide on
11829        // identity with `three_member_spec`'s pre-existing entries.
11830        // The new edge uses `(payment, catalog)` — a pair the fixture
11831        // doesn't already declare — with no payload field set, so the
11832        // wit-shape gate fires before any payload-shape arm.
11833        let mut s = three_member_spec();
11834        s.contratos.push(WitContract {
11835            de: "payment".into(),
11836            para: "catalog".into(),
11837            wit: wit.into(),
11838            endpoint: None,
11839            subject: None,
11840            slot: None,
11841        });
11842        s.validate().unwrap_err()
11843    }
11844
11845    #[test]
11846    fn rejects_wit_with_uppercase_namespace() {
11847        // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
11848        // didn't match the lowercase `wasi:http/` prefix is_http() keys
11849        // off, so the dispatch fell through to the capability arm and
11850        // the contract silently rendered as an L4-only Cilium edge.
11851        // The new gate surfaces the uppercase typo at validate time
11852        // with the offending `:wit` named.
11853        let err = contrato_wit_err("WASI:http/proxy");
11854        assert!(
11855            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11856                if wit == "WASI:http/proxy" && reason.contains("lowercase")),
11857            "got {err:?}"
11858        );
11859    }
11860
11861    #[test]
11862    fn rejects_wit_with_hyphen_for_colon_typo() {
11863        // The canonical "I forgot the `:` separator" typo — pre-gate
11864        // this passed as Capability silently, so the renderer emitted
11865        // an L4-only policy where the author expected L7 HTTP rules.
11866        let err = contrato_wit_err("wasi-http/proxy");
11867        assert!(
11868            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11869                if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
11870            "got {err:?}"
11871        );
11872    }
11873
11874    #[test]
11875    fn rejects_wit_with_multiple_colons() {
11876        // Doubled `:` — the namespace/package split has nowhere to
11877        // anchor, so the dispatch silently demotes to Capability.
11878        let err = contrato_wit_err("wasi:http:proxy");
11879        assert!(
11880            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11881                if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
11882            "got {err:?}"
11883        );
11884    }
11885
11886    #[test]
11887    fn rejects_wit_with_empty_package() {
11888        // `wasi:` — namespace alone with no package. Pre-gate this
11889        // failed neither the is_http nor is_pubsub nor is_store
11890        // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
11891        // a bare `wasi:`), so it silently demoted to Capability.
11892        let err = contrato_wit_err("wasi:");
11893        assert!(
11894            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11895                if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
11896            "got {err:?}"
11897        );
11898    }
11899
11900    #[test]
11901    fn rejects_wit_with_underscore() {
11902        // Underscore — WIT identifiers are kebab-case, same rule
11903        // DNS-1123 enforces on its peer axes. The diagnostic carries
11904        // the explicit "use `-` instead" remediation.
11905        let err = contrato_wit_err("wasi:http_proxy");
11906        assert!(
11907            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11908                if wit == "wasi:http_proxy" && reason.contains('_')),
11909            "got {err:?}"
11910        );
11911    }
11912
11913    #[test]
11914    fn rejects_wit_with_whitespace() {
11915        // Whitespace mid-token — the prefix check matches but the
11916        // package-and-onward parse silently demoted to Capability.
11917        let err = contrato_wit_err("wasi:http proxy");
11918        assert!(
11919            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11920                if wit == "wasi:http proxy" && reason.contains("whitespace")),
11921            "got {err:?}"
11922        );
11923    }
11924
11925    #[test]
11926    fn rejects_wit_with_non_ascii() {
11927        // Un-percent-encoded non-ASCII byte — the canonical "I copied
11928        // the package name from a doc with smart quotes / accented
11929        // characters" footgun.
11930        let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
11931        assert!(
11932            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11933                if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
11934            "got {err:?}"
11935        );
11936    }
11937
11938    #[test]
11939    fn rejects_wit_with_consecutive_hyphens() {
11940        // `pub--sub` — WIT identifiers join words with single hyphens.
11941        let err = contrato_wit_err("nats:pub--sub");
11942        assert!(
11943            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11944                if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
11945            "got {err:?}"
11946        );
11947    }
11948
11949    #[test]
11950    fn rejects_wit_with_trailing_at_no_version() {
11951        // `wasi:http/proxy@` — the version-suffix author started to
11952        // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
11953        // parser would reject this; surface it at validate time.
11954        let err = contrato_wit_err("wasi:http/proxy@");
11955        assert!(
11956            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11957                if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
11958            "got {err:?}"
11959        );
11960    }
11961
11962    #[test]
11963    fn rejects_wit_too_long() {
11964        // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
11965        // The legitimate-shape arms all pass (lowercase, single `:`,
11966        // kebab-case identifiers); only the cap arm fires. Surfaces
11967        // the paste-from-binary / accidental-multi-line-blob landing
11968        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
11969        // on the peer axis.
11970        let big = format!("wasi:{}", "a".repeat(124));
11971        assert_eq!(big.len(), 129);
11972        let err = contrato_wit_err(&big);
11973        assert!(
11974            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11975                if wit == &big && reason.contains("max length of 128")),
11976            "got {err:?}"
11977        );
11978    }
11979
11980    #[test]
11981    fn wit_max_length_validates() {
11982        // 128-byte WIT reference — exactly the cap. Boundary pin:
11983        // drift in the cap surfaces here and at `rejects_wit_too_long`
11984        // simultaneously, mirroring
11985        // `http_contrato_endpoint_max_length_validates` on the peer
11986        // axis.
11987        let big = format!("wasi:{}", "a".repeat(123));
11988        assert_eq!(big.len(), 128);
11989        let mut s = three_member_spec();
11990        s.contratos.push(WitContract {
11991            de: "payment".into(),
11992            para: "catalog".into(),
11993            wit: big,
11994            endpoint: None,
11995            subject: None,
11996            slot: None,
11997        });
11998        s.validate().unwrap();
11999    }
12000
12001    #[test]
12002    fn wit_accepts_canonical_forms_at_aplicacao_layer() {
12003        // Positive-set sweep through the AplicacaoSpec::validate
12004        // surface (rather than the substrate-side predicate directly)
12005        // — pins every shape the existing test fixtures + the
12006        // checkout-aplicacao example carry, so the gate's accept-set
12007        // matches the substrate's emit-set. Drift between this list
12008        // and `render::tests::wit_world_ref_accepts_canonical_forms`
12009        // surfaces at the substrate layer's positive sweep — one
12010        // source of truth for the rule.
12011        for wit in [
12012            "wasi:http/proxy",
12013            "wasi:keyvalue/store",
12014            "nats:pub-sub",
12015            "kafka:topic",
12016            "custom:exchange",
12017            "pleme:cap/audit",
12018            "wasi:http/proxy@0.2.0",
12019        ] {
12020            // Payload field paired to the dispatched WIT shape so the
12021            // shape-↔-target arm doesn't fire instead of the wit-shape
12022            // arm we're exercising. Routes off the same
12023            // `wit_shape_is_http` / `wit_shape_is_pubsub` /
12024            // `wit_shape_is_store` free functions the production
12025            // `WitContract::is_http` / `is_pubsub` / `is_store`
12026            // methods delegate to (both consult the lifted
12027            // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
12028            // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
12029            // future prefix addition to the routing accept-set
12030            // reaches this test's payload-dispatch arm by
12031            // construction — no per-test-site drift can hide a
12032            // shape-→-target-slot mismatch that would silently
12033            // demote a canonical `:wit` value to the
12034            // `(None, None, None)` capability-only arm and let the
12035            // `AplicacaoSpec::validate` positive sweep pass on a
12036            // shape it should exercise as HTTP / pub-sub / store.
12037            let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
12038                (Some("/x".into()), None, None)
12039            } else if wit_shape_is_pubsub(wit) {
12040                (None, Some("topic.x".into()), None)
12041            } else if wit_shape_is_store(wit) {
12042                (None, None, Some("bucket/$key".into()))
12043            } else {
12044                (None, None, None)
12045            };
12046            let mut s = three_member_spec();
12047            s.contratos.push(WitContract {
12048                de: "payment".into(),
12049                para: "catalog".into(),
12050                wit: wit.into(),
12051                endpoint,
12052                subject,
12053                slot,
12054            });
12055            s.validate()
12056                .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
12057        }
12058    }
12059
12060    #[test]
12061    fn wit_shape_predicates_accept_canonical_prefix_set() {
12062        // Positive-set sweep pinning every prefix in
12063        // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
12064        // WIT_STORE_SHAPE_PREFIXES against the three free-function
12065        // dispatch predicates. The six prefixes are the load-bearing
12066        // routing keys the substrate's WIT-shape dispatch consults
12067        // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
12068        // key/value-store-slot admission); any drift between the
12069        // free-function accept-set and this list surfaces here
12070        // rather than at apply time as a silent
12071        // shape-→-capability-only demotion.
12072        assert!(wit_shape_is_http("wasi:http/proxy"));
12073        assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
12074        assert!(wit_shape_is_http("http:incoming"));
12075
12076        assert!(wit_shape_is_pubsub("nats:pub-sub"));
12077        assert!(wit_shape_is_pubsub("kafka:topic"));
12078
12079        assert!(wit_shape_is_store("wasi:keyvalue/store"));
12080        assert!(wit_shape_is_store("kv:cache/session"));
12081    }
12082
12083    #[test]
12084    fn wit_shape_predicates_reject_uncanonical_forms() {
12085        // Negative-set pin: the six canonical prefixes are
12086        // lowercase-only (mirrors the `is_wit_world_ref` substrate
12087        // predicate's lowercase invariant — see its docstring on the
12088        // "I thought I had L7 HTTP routing, got L4-only" footgun).
12089        // The empty string, an uppercase-prefixed form, a hyphen-
12090        // instead-of-colon typo, and a bare kebab identifier all miss
12091        // every shape arm — reachable-by-construction only via the
12092        // `is_wit_world_ref` gate that admission-checks the `:wit`
12093        // value first, but pinned here so any future
12094        // free-function change (e.g. a case-insensitive
12095        // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
12096        // this unit level.
12097        for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
12098            assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
12099            assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
12100            assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
12101        }
12102    }
12103
12104    #[test]
12105    fn wit_shape_predicates_partition_canonical_set() {
12106        // Every canonical prefix routes to exactly one shape arm —
12107        // the three prefix sets are pairwise disjoint. Pins the
12108        // routing property [`WitContract::target`] relies on: an
12109        // `is_http()` return of `true` guarantees `is_pubsub()` and
12110        // `is_store()` return `false`, so the shape-→-target-slot
12111        // dispatch (endpoint vs subject vs slot) is unambiguous.
12112        // Drift (e.g. a future `"kv:"` moved into the HTTP set
12113        // without removal from the store set) would silently route
12114        // one prefix to two arms and the first-matching-arm order
12115        // becomes load-bearing — this pin surfaces it as a build
12116        // error instead.
12117        for prefix in WIT_HTTP_SHAPE_PREFIXES {
12118            let sample = format!("{prefix}x");
12119            assert!(wit_shape_is_http(&sample));
12120            assert!(!wit_shape_is_pubsub(&sample));
12121            assert!(!wit_shape_is_store(&sample));
12122        }
12123        for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
12124            let sample = format!("{prefix}x");
12125            assert!(!wit_shape_is_http(&sample));
12126            assert!(wit_shape_is_pubsub(&sample));
12127            assert!(!wit_shape_is_store(&sample));
12128        }
12129        for prefix in WIT_STORE_SHAPE_PREFIXES {
12130            let sample = format!("{prefix}x");
12131            assert!(!wit_shape_is_http(&sample));
12132            assert!(!wit_shape_is_pubsub(&sample));
12133            assert!(wit_shape_is_store(&sample));
12134        }
12135    }
12136
12137    #[test]
12138    fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
12139        // Positive pin: [`wit_shape_matches`] is exactly the
12140        // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
12141        // parameterized on the accept-set. Two-prefix accept-set,
12142        // one-prefix accept-set, and empty accept-set (which must
12143        // reject everything, including the empty string — an empty
12144        // `any()` fold returns `false`) all pinned so a future
12145        // reimplementation that swaps `starts_with` for `contains`,
12146        // `==`, or a case-folded comparator surfaces at unit-test
12147        // time.
12148        let two = &["wasi:http/", "http:"];
12149        assert!(wit_shape_matches("wasi:http/proxy", two));
12150        assert!(wit_shape_matches("http:incoming", two));
12151        assert!(!wit_shape_matches("wasi:keyvalue/store", two));
12152
12153        let one = &["nats:"];
12154        assert!(wit_shape_matches("nats:pub-sub", one));
12155        assert!(!wit_shape_matches("kafka:topic", one));
12156
12157        // Empty accept-set matches nothing — the identity element
12158        // for the disjunctive `any()` fold across the prefix set.
12159        // Reachable via a future `wit_shape_is_<name>` const paired
12160        // to a still-empty prefix table on a nascent shape-arm draft.
12161        let empty: &[&str] = &[];
12162        assert!(!wit_shape_matches("wasi:http/proxy", empty));
12163        assert!(!wit_shape_matches("", empty));
12164
12165        // starts_with, not contains: a prefix embedded mid-string
12166        // never matches. Pins the routing invariant [`WitContract::target`]
12167        // relies on (an authored `:wit "custom:wasi:http/"` string
12168        // does not silently route through the HTTP arm just because
12169        // it happens to contain the canonical HTTP prefix).
12170        assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
12171    }
12172
12173    #[test]
12174    fn wit_shape_predicates_delegate_to_wit_shape_matches() {
12175        // Equivalence pin: each per-shape predicate is exactly
12176        // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
12177        // every canonical prefix + the empty string + one negative
12178        // sample against every peer so a future predicate that grew
12179        // its own inline `iter().any(starts_with)` (rather than
12180        // delegating through the lifted combinator) drifts loudly here
12181        // — the peer-const table's contents must agree with the
12182        // predicate's accept-set by construction.
12183        let samples = [
12184            String::new(),
12185            "wasi:http/proxy".to_string(),
12186            "http:incoming".to_string(),
12187            "nats:pub-sub".to_string(),
12188            "kafka:topic".to_string(),
12189            "wasi:keyvalue/store".to_string(),
12190            "kv:cache/session".to_string(),
12191            "custom-shape".to_string(),
12192            "WASI:HTTP/proxy".to_string(),
12193        ];
12194        for wit in &samples {
12195            assert_eq!(
12196                wit_shape_is_http(wit),
12197                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
12198                "wit_shape_is_http drifted from combinator on {wit:?}",
12199            );
12200            assert_eq!(
12201                wit_shape_is_pubsub(wit),
12202                wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
12203                "wit_shape_is_pubsub drifted from combinator on {wit:?}",
12204            );
12205            assert_eq!(
12206                wit_shape_is_store(wit),
12207                wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
12208                "wit_shape_is_store drifted from combinator on {wit:?}",
12209            );
12210        }
12211    }
12212
12213    #[test]
12214    fn wit_contract_shape_methods_delegate_to_free_functions() {
12215        // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
12216        // `is_store` are `&self` conveniences on top of the free
12217        // functions — for every canonical prefix the method's return
12218        // matches its free-function peer. Sweeps the union of the
12219        // three prefix sets so a future method that grew its own
12220        // inline prefix logic (rather than delegating) drifts loudly
12221        // here on the first prefix the free function accepts and the
12222        // method doesn't.
12223        for shape_set in [
12224            WIT_HTTP_SHAPE_PREFIXES,
12225            WIT_PUBSUB_SHAPE_PREFIXES,
12226            WIT_STORE_SHAPE_PREFIXES,
12227        ] {
12228            for prefix in shape_set {
12229                let c = WitContract {
12230                    de: "cart".into(),
12231                    para: "catalog".into(),
12232                    wit: format!("{prefix}x"),
12233                    endpoint: None,
12234                    subject: None,
12235                    slot: None,
12236                };
12237                assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
12238                assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
12239                assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
12240                assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
12241            }
12242        }
12243        // Capability-arm delegation sweep: two representative
12244        // Capability-shaped `:wit` values (a bare non-prefix-matching
12245        // WIT world, the deliberately-shaped empty string
12246        // [`WitContract::is_capability`]'s docstring calls out as
12247        // syntactically Capability). Extends the free-function
12248        // delegation pin onto the fourth arm so a future
12249        // [`WitContract::is_capability`] rewrite that grew an inline
12250        // prefix-set scan (rather than delegating through
12251        // [`wit_shape_is_capability`]) drifts loudly here on the first
12252        // Capability-shaped sample.
12253        for wit in ["custom:capability-only", ""] {
12254            let c = WitContract {
12255                de: "cart".into(),
12256                para: "catalog".into(),
12257                wit: wit.into(),
12258                endpoint: None,
12259                subject: None,
12260                slot: None,
12261            };
12262            assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
12263        }
12264    }
12265
12266    #[test]
12267    fn wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis() {
12268        // 4-way partition-witness pin on the raw `&str` axis: for every
12269        // canonical prefix in the three payload-arm accept-sets,
12270        // exactly one of the four [`wit_shape_is_http`] /
12271        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
12272        // [`wit_shape_is_capability`] free functions returns `true` and
12273        // the other three return `false` — the four-arm partition
12274        // witness that locks the free-function WIT-shape-classifier
12275        // family into a partition of the `:contratos :wit` axis
12276        // load-bearing. Peer of the sibling [`WitContract`]-surface
12277        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
12278        // partition pin — extends the discipline onto the raw `&str`
12279        // axis so any future arm addition (a hypothetical
12280        // `wasi:sockets/*` transport-layer shape, an `oci:*`
12281        // capability-import carrier per the sibling
12282        // [`wit_shape_matches`] docstring's trajectory bullet) that
12283        // landed on one of the payload-arm free functions without
12284        // shrinking [`wit_shape_is_capability`]'s accept-set surfaces
12285        // here as two arms returning `true` simultaneously at
12286        // caixa-core build time rather than a silent per-consumer
12287        // misclassification at renderer emit time.
12288        for shape_set in [
12289            WIT_HTTP_SHAPE_PREFIXES,
12290            WIT_PUBSUB_SHAPE_PREFIXES,
12291            WIT_STORE_SHAPE_PREFIXES,
12292        ] {
12293            for prefix in shape_set {
12294                let wit = format!("{prefix}x");
12295                let hits = [
12296                    wit_shape_is_http(&wit),
12297                    wit_shape_is_pubsub(&wit),
12298                    wit_shape_is_store(&wit),
12299                    wit_shape_is_capability(&wit),
12300                ]
12301                .iter()
12302                .filter(|&&b| b)
12303                .count();
12304                assert_eq!(
12305                    hits,
12306                    1,
12307                    "raw-&str WIT-shape 4-way predicate partition must \
12308                     admit exactly one arm per canonical prefix; got {hits} \
12309                     hits at wit={wit:?} (is_http={}, is_pubsub={}, is_store={}, \
12310                     is_capability={})",
12311                    wit_shape_is_http(&wit),
12312                    wit_shape_is_pubsub(&wit),
12313                    wit_shape_is_store(&wit),
12314                    wit_shape_is_capability(&wit),
12315                );
12316            }
12317        }
12318        // Capability-arm sweep on the raw `&str` axis: two
12319        // representative Capability-shaped `:wit` values (a bare non-
12320        // prefix-matching WIT world, the deliberately-shaped empty
12321        // string the pure classifier still admits per
12322        // [`wit_shape_is_capability`]'s docstring). Both must land on
12323        // the fourth arm exclusively so the partition witness holds
12324        // across the full 4-arm closure on the raw `&str` axis.
12325        for wit in ["custom:capability-only", ""] {
12326            let hits = [
12327                wit_shape_is_http(wit),
12328                wit_shape_is_pubsub(wit),
12329                wit_shape_is_store(wit),
12330                wit_shape_is_capability(wit),
12331            ]
12332            .iter()
12333            .filter(|&&b| b)
12334            .count();
12335            assert_eq!(
12336                hits, 1,
12337                "raw-&str WIT-shape 4-way predicate partition must \
12338                 admit exactly one arm on Capability-shaped wit={wit:?}"
12339            );
12340            assert!(
12341                wit_shape_is_capability(wit),
12342                "wit={wit:?} must project onto the Capability arm on the raw-&str axis"
12343            );
12344        }
12345    }
12346
12347    #[test]
12348    fn wit_shape_is_capability_composes_through_payload_arm_predicate_negation() {
12349        // Composition-witness pin: [`wit_shape_is_capability`] is the
12350        // exact-inverse disjunction of the sibling payload-arm free-
12351        // function trio [`wit_shape_is_http`] / [`wit_shape_is_pubsub`]
12352        // / [`wit_shape_is_store`]. A future reimplementation that
12353        // grew its own prefix-set scan (e.g. inlining a fourth
12354        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does
12355        // not own today) rather than delegating to the sibling trio
12356        // would drift loudly here — the composition contract binds the
12357        // fourth-arm free-function predicate to the exact-inverse of
12358        // the three payload-arm free-function predicates, so any
12359        // rebrand of any prefix-set const flows through
12360        // [`wit_shape_is_capability`] by construction without a
12361        // coordinated per-consumer rewrite. Peer of the sibling
12362        // [`WitContract`]-surface
12363        // [`wit_contract_is_capability_composes_through_shape_predicate_negation`]
12364        // composition pin — extends the discipline onto the raw
12365        // `&str` axis.
12366        let mut cases: Vec<String> = Vec::new();
12367        for shape_set in [
12368            WIT_HTTP_SHAPE_PREFIXES,
12369            WIT_PUBSUB_SHAPE_PREFIXES,
12370            WIT_STORE_SHAPE_PREFIXES,
12371        ] {
12372            for prefix in shape_set {
12373                cases.push(format!("{prefix}x"));
12374            }
12375        }
12376        cases.push("custom:capability-only".to_string());
12377        cases.push(String::new());
12378        for wit in cases {
12379            assert_eq!(
12380                wit_shape_is_capability(&wit),
12381                !wit_shape_is_http(&wit) && !wit_shape_is_pubsub(&wit) && !wit_shape_is_store(&wit),
12382                "wit_shape_is_capability must equal \
12383                 !wit_shape_is_http() && !wit_shape_is_pubsub() && !wit_shape_is_store() \
12384                 at wit={wit:?}"
12385            );
12386        }
12387    }
12388
12389    #[test]
12390    fn wit_shape_classifier_family_is_const_fn() {
12391        // Fail-before-pass-after pin on the 4-arm free-function WIT-
12392        // shape classifier family's `const`-eval posture. Each of the
12393        // four peer classifiers ([`wit_shape_is_http`] /
12394        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
12395        // [`wit_shape_is_capability`]) and the underlying combinator
12396        // [`wit_shape_matches`] must be `pub const fn` — any future
12397        // accidental downgrade to non-`const` fails the `const fn`
12398        // wrappers below at caixa-core build time with E0015
12399        // (`cannot call non-const function`), strictly stronger than
12400        // a runtime `assert!` and strictly stronger than the module-
12401        // scope `const _: () = assert!(…)` pins immediately after the
12402        // classifier declarations (those anchor specific accept-set
12403        // truth-table entries; this pin anchors the `const` posture
12404        // itself via `const fn` wrappers that are only well-formed
12405        // when the callee is itself `const fn`).
12406        //
12407        // Verified fail-before-pass-after by locally reverting
12408        // `pub const fn` → `pub fn` on each classifier and observing
12409        // E0015 at every corresponding wrapper call site (build
12410        // error, no test-time surface), then restoring `pub const fn`
12411        // and observing the pin pass at test time. Peer of the
12412        // sibling M3
12413        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
12414        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
12415        // M2
12416        // [`child_spec_restart_accessor_is_const_fn`] /
12417        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
12418        // and M3
12419        // [`placement_estrategia_accessor_is_const_fn`] /
12420        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
12421        // sibling `const`-eval-surface-pass axes.
12422        const fn matches_via_const_fn(wit: &str, prefixes: &[&str]) -> bool {
12423            wit_shape_matches(wit, prefixes)
12424        }
12425        const fn http_via_const_fn(wit: &str) -> bool {
12426            wit_shape_is_http(wit)
12427        }
12428        const fn pubsub_via_const_fn(wit: &str) -> bool {
12429            wit_shape_is_pubsub(wit)
12430        }
12431        const fn store_via_const_fn(wit: &str) -> bool {
12432            wit_shape_is_store(wit)
12433        }
12434        const fn capability_via_const_fn(wit: &str) -> bool {
12435            wit_shape_is_capability(wit)
12436        }
12437        // Sweep one canonical accept-set sample per arm plus the
12438        // payload-less/empty capability samples, asserting the
12439        // wrapper and direct dispatches agree byte-for-byte across
12440        // the closed 4-arm partition.
12441        let cases: [(&str, bool, bool, bool, bool); 6] = [
12442            ("wasi:http/proxy", true, false, false, false),
12443            ("http:incoming", true, false, false, false),
12444            ("nats:events", false, true, false, false),
12445            ("kafka:topic", false, true, false, false),
12446            ("wasi:keyvalue/store", false, false, true, false),
12447            ("kv:cache", false, false, true, false),
12448        ];
12449        for (wit, is_http, is_pubsub, is_store, _is_capability) in cases {
12450            assert_eq!(
12451                matches_via_const_fn(wit, WIT_HTTP_SHAPE_PREFIXES),
12452                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
12453                "wit_shape_matches const fn wrapper disagrees at wit={wit:?}",
12454            );
12455            assert_eq!(http_via_const_fn(wit), wit_shape_is_http(wit));
12456            assert_eq!(pubsub_via_const_fn(wit), wit_shape_is_pubsub(wit));
12457            assert_eq!(store_via_const_fn(wit), wit_shape_is_store(wit));
12458            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
12459            assert_eq!(wit_shape_is_http(wit), is_http);
12460            assert_eq!(wit_shape_is_pubsub(wit), is_pubsub);
12461            assert_eq!(wit_shape_is_store(wit), is_store);
12462        }
12463        // Payload-less capability arm (the 4th partition arm).
12464        let capability_samples: [&str; 3] =
12465            ["wasi:filesystem/preopens", "custom:capability-only", ""];
12466        for wit in capability_samples {
12467            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
12468            assert!(wit_shape_is_capability(wit));
12469            assert!(!wit_shape_is_http(wit));
12470            assert!(!wit_shape_is_pubsub(wit));
12471            assert!(!wit_shape_is_store(wit));
12472        }
12473    }
12474
12475    #[test]
12476    fn wit_shape_matches_composes_through_bytes_starts_with_across_boundary_lengths() {
12477        // Composition-witness pin: [`wit_shape_matches`] agrees with
12478        // the reference `prefixes.iter().any(|p| wit.starts_with(p))`
12479        // dispatch (the prior non-`const` implementation) across
12480        // boundary lengths — empty `wit`, empty prefix, one-byte
12481        // slack, prefix longer than `wit`, one-byte trailing slack.
12482        // The rewrite to a byte-level manual starts_with loop (the
12483        // enabler for the `pub const fn` posture) must not change any
12484        // truth-table entry on the canonical accept-set — this pin
12485        // sweeps a targeted boundary corpus and asserts byte-for-byte
12486        // agreement, locking the const-fn rewrite's semantics against
12487        // the prior iterator body by construction.
12488        let prefixes = &["wasi:http/", "http:"][..];
12489        let cases: [(&str, bool); 12] = [
12490            ("wasi:http/proxy", true),
12491            ("wasi:http/", true), // exact-length match on prefix
12492            ("wasi:http", false), // one byte short
12493            ("http:", true),
12494            ("http:incoming", true),
12495            ("http", false), // one byte short
12496            ("", false),
12497            ("wasi:https/proxy", false),
12498            ("nats:events", false),
12499            ("HTTPS:", false), // uppercase — no case-fold in classifier
12500            ("wasi:HTTP/proxy", false),
12501            ("wasi:http", false),
12502        ];
12503        for (wit, expected) in cases {
12504            assert_eq!(
12505                wit_shape_matches(wit, prefixes),
12506                expected,
12507                "wit_shape_matches disagrees with reference at wit={wit:?}",
12508            );
12509            // Byte-equal to the iterator body it replaced.
12510            let via_iter = prefixes.iter().any(|p| wit.starts_with(p));
12511            assert_eq!(
12512                wit_shape_matches(wit, prefixes),
12513                via_iter,
12514                "wit_shape_matches must byte-equal iter().any(starts_with) at wit={wit:?}",
12515            );
12516        }
12517        // Empty prefix set → always false regardless of `wit`.
12518        let empty: &[&str] = &[];
12519        assert!(!wit_shape_matches("", empty));
12520        assert!(!wit_shape_matches("wasi:http/proxy", empty));
12521        // Empty prefix inside a non-empty set → always true (every
12522        // string starts with the empty string, matching the
12523        // iterator body's semantics on `str::starts_with("")`).
12524        let contains_empty: &[&str] = &["nats:", ""];
12525        assert!(wit_shape_matches("", contains_empty));
12526        assert!(wit_shape_matches("wasi:http/proxy", contains_empty));
12527    }
12528
12529    #[test]
12530    fn wit_contract_is_capability_partitions_the_wit_shape_space() {
12531        // 4-way partition-witness pin: for every canonical prefix in
12532        // the payload-arm accept-sets, exactly one of the four
12533        // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
12534        // [`WitContract::is_store`] / [`WitContract::is_capability`]
12535        // predicates returns `true` and the other three return `false`
12536        // — the four-arm partition witness that locks the substrate's
12537        // WIT-shape-space closure on the pre-projection axis load-
12538        // bearing. A future arm addition (a hypothetical fourth
12539        // payload-shape prefix set, a `wasi:sockets/*` transport-layer
12540        // shape) that landed on one of the payload-arm predicates
12541        // without shrinking [`WitContract::is_capability`]'s accept-set
12542        // would surface here as two arms returning `true` simultaneously
12543        // — a partition-witness break the pin catches at caixa-core
12544        // build time rather than a silent per-consumer misclassification
12545        // at renderer emit time. Peer of the sibling `WitTarget`-side
12546        // [`tests::wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`]
12547        // partition-witness pin on the post-projection payload-scalar
12548        // arm-set — extends the discipline onto the pre-projection
12549        // 4-arm shape-space.
12550        for shape_set in [
12551            WIT_HTTP_SHAPE_PREFIXES,
12552            WIT_PUBSUB_SHAPE_PREFIXES,
12553            WIT_STORE_SHAPE_PREFIXES,
12554        ] {
12555            for prefix in shape_set {
12556                let c = WitContract {
12557                    de: "cart".into(),
12558                    para: "catalog".into(),
12559                    wit: format!("{prefix}x"),
12560                    endpoint: None,
12561                    subject: None,
12562                    slot: None,
12563                };
12564                let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
12565                    .iter()
12566                    .filter(|&&b| b)
12567                    .count();
12568                assert_eq!(
12569                    hits,
12570                    1,
12571                    "WitContract WIT-shape 4-way predicate partition must \
12572                     admit exactly one arm per canonical prefix; got {hits} \
12573                     hits at wit={:?} (is_http={}, is_pubsub={}, is_store={}, \
12574                     is_capability={})",
12575                    c.wit,
12576                    c.is_http(),
12577                    c.is_pubsub(),
12578                    c.is_store(),
12579                    c.is_capability(),
12580                );
12581            }
12582        }
12583        // Capability-arm sweep: two representative capability shapes
12584        // (a bare WIT world outside the three payload-arm prefix sets,
12585        // and the deliberately-shaped empty string that
12586        // [`crate::render::is_wit_world_ref`] rejects at
12587        // [`WitContract::target`] time but which the pure classifier
12588        // still admits — see the method docstring's "purely syntactic
12589        // classification" note). Both must land on the fourth arm
12590        // exclusively, so the partition witness holds across the full
12591        // 4-arm closure.
12592        for wit in ["custom:capability-only", ""] {
12593            let c = WitContract {
12594                de: "cart".into(),
12595                para: "catalog".into(),
12596                wit: wit.into(),
12597                endpoint: None,
12598                subject: None,
12599                slot: None,
12600            };
12601            let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
12602                .iter()
12603                .filter(|&&b| b)
12604                .count();
12605            assert_eq!(
12606                hits, 1,
12607                "WitContract WIT-shape 4-way predicate partition must \
12608                 admit exactly one arm on Capability-shaped wit={wit:?}"
12609            );
12610            assert!(
12611                c.is_capability(),
12612                "wit={wit:?} must project onto the Capability arm"
12613            );
12614        }
12615    }
12616
12617    #[test]
12618    fn wit_contract_is_capability_composes_through_shape_predicate_negation() {
12619        // Composition-witness pin: [`WitContract::is_capability`] is the
12620        // exact-inverse disjunction of the sibling payload-arm predicate
12621        // trio [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
12622        // [`WitContract::is_store`]. A future reimplementation that
12623        // grew its own prefix-set scan (e.g. inlining a fourth
12624        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does not
12625        // own today) rather than delegating to the sibling trio would
12626        // drift loudly here — the composition contract binds the
12627        // fourth-arm predicate to the exact-inverse of the three
12628        // payload-arm predicates, so any rebrand of any prefix-set const
12629        // flows through this method by construction without a
12630        // coordinated per-consumer rewrite. Sweeps the union of the
12631        // three payload-arm prefix sets plus two Capability-shaped
12632        // shapes (a bare non-prefix-matching WIT world, the deliberately-
12633        // empty string the pure classifier still admits per the method
12634        // docstring's "purely syntactic classification" note).
12635        let mut cases: Vec<String> = Vec::new();
12636        for shape_set in [
12637            WIT_HTTP_SHAPE_PREFIXES,
12638            WIT_PUBSUB_SHAPE_PREFIXES,
12639            WIT_STORE_SHAPE_PREFIXES,
12640        ] {
12641            for prefix in shape_set {
12642                cases.push(format!("{prefix}x"));
12643            }
12644        }
12645        cases.push("custom:capability-only".to_string());
12646        cases.push(String::new());
12647        for wit in cases {
12648            let c = WitContract {
12649                de: "cart".into(),
12650                para: "catalog".into(),
12651                wit: wit.clone(),
12652                endpoint: None,
12653                subject: None,
12654                slot: None,
12655            };
12656            assert_eq!(
12657                c.is_capability(),
12658                !c.is_http() && !c.is_pubsub() && !c.is_store(),
12659                "WitContract::is_capability must equal \
12660                 !is_http() && !is_pubsub() && !is_store() at wit={wit:?}"
12661            );
12662        }
12663    }
12664
12665    #[test]
12666    fn wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant() {
12667        // Cross-projection-witness pin: whenever [`WitContract::target`]
12668        // succeeds, the pre-projection [`WitContract::is_capability`]
12669        // classification agrees with the post-projection
12670        // [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
12671        // predicate — the 4-arm typed partition on the substrate's
12672        // typed-view surface (7f6aa98 IsVariant lift) and the peer 4-arm
12673        // partition on the pre-projection axis line up by construction.
12674        // A future divergence between the two axes (a peer
12675        // [`WitTarget`] variant addition that landed on the typed-view
12676        // surface without a peer prefix-set + [`WitContract`] predicate
12677        // extension, or vice versa) would surface here at caixa-core
12678        // build time rather than a silent per-consumer split at renderer
12679        // emit time. Peer of the sibling pre-/post-projection
12680        // agreement pins the payload-carrier trio
12681        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
12682        // [`WitContract::slot`] on pre-projection; [`WitTarget::http_endpoint`]
12683        // / [`WitTarget::pubsub_subject`] / [`WitTarget::store_slot`] on
12684        // post-projection — b11bb49 trio lift) already carry across the
12685        // three payload arms — this pin closes the pair on the fourth
12686        // payload-less arm.
12687        let http = WitContract {
12688            de: "cart".into(),
12689            para: "catalog".into(),
12690            wit: "wasi:http/proxy".into(),
12691            endpoint: Some("/x".into()),
12692            subject: None,
12693            slot: None,
12694        };
12695        assert!(!http.is_capability());
12696        assert!(!http.target().unwrap().is_capability());
12697
12698        let nats = WitContract {
12699            de: "cart".into(),
12700            para: "catalog".into(),
12701            wit: "nats:pub-sub".into(),
12702            endpoint: None,
12703            subject: Some("events.x".into()),
12704            slot: None,
12705        };
12706        assert!(!nats.is_capability());
12707        assert!(!nats.target().unwrap().is_capability());
12708
12709        let kv = WitContract {
12710            de: "cart".into(),
12711            para: "catalog".into(),
12712            wit: "wasi:keyvalue/store".into(),
12713            endpoint: None,
12714            subject: None,
12715            slot: Some("checkout/$orderId".into()),
12716        };
12717        assert!(!kv.is_capability());
12718        assert!(!kv.target().unwrap().is_capability());
12719
12720        let cap = WitContract {
12721            de: "cart".into(),
12722            para: "catalog".into(),
12723            wit: "custom:capability-only".into(),
12724            endpoint: None,
12725            subject: None,
12726            slot: None,
12727        };
12728        assert!(cap.is_capability());
12729        assert!(cap.target().unwrap().is_capability());
12730    }
12731
12732    #[test]
12733    fn wit_contract_pre_projection_accessor_family_is_const_fn() {
12734        // Fail-before-pass-after pin on the [`WitContract`] pre-
12735        // projection accessor family's `const`-eval-surface posture.
12736        // Each of the three per-`:contratos` byte-string scalar
12737        // accessors ([`WitContract::source`] / [`WitContract::destination`]
12738        // / [`WitContract::world_ref`], each projecting through
12739        // `String::as_str` — const-stable since Rust 1.87, well within
12740        // the workspace MSRV) and each of the four peer WIT-shape
12741        // predicates ([`WitContract::is_http`] /
12742        // [`WitContract::is_pubsub`] / [`WitContract::is_store`] /
12743        // [`WitContract::is_capability`], each composing
12744        // `wit_shape_is_<arm>(self.world_ref())` on the `pub const fn`
12745        // free-function classifier family the sibling
12746        // [`wit_shape_classifier_family_is_const_fn`] pin already
12747        // anchors on the raw `&str → bool` axis) must be `pub const fn`
12748        // — any future accidental downgrade to non-`const` fails the
12749        // `const fn` wrappers below at caixa-core build time with E0015
12750        // (`cannot call non-const function`), strictly stronger than a
12751        // runtime `assert!` and strictly stronger than a
12752        // module-scope `const _: () = assert!(…)` pin (which cannot be
12753        // formed on a `&WitContract` fixture because the type's
12754        // `String` / `Option<String>` carriers rule out `const`-context
12755        // construction; the `const fn` wrapper is the load-bearing
12756        // shape that side-steps the destructor-in-const restriction on
12757        // the value axis while still pinning the `const`-fn posture on
12758        // the callee).
12759        //
12760        // Peer of the sibling free-function classifier pin
12761        // [`wit_shape_classifier_family_is_const_fn`] (d46420c) on the
12762        // raw `&str → bool` axis — this pin extends the same
12763        // `const`-eval-surface discipline onto the peer method surface
12764        // that composes through those free-function classifiers, and
12765        // simultaneously onto the underlying per-`:contratos`
12766        // byte-string scalar-accessor trio each predicate reads
12767        // through. Sibling of the peer M3
12768        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
12769        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
12770        // M2
12771        // [`child_spec_restart_accessor_is_const_fn`] /
12772        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
12773        // and M3
12774        // [`placement_estrategia_accessor_is_const_fn`] /
12775        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
12776        // sibling `const`-eval-surface-pass axes.
12777        const fn source_via_const_fn(c: &WitContract) -> &str {
12778            c.source()
12779        }
12780        const fn destination_via_const_fn(c: &WitContract) -> &str {
12781            c.destination()
12782        }
12783        const fn world_ref_via_const_fn(c: &WitContract) -> &str {
12784            c.world_ref()
12785        }
12786        const fn is_http_via_const_fn(c: &WitContract) -> bool {
12787            c.is_http()
12788        }
12789        const fn is_pubsub_via_const_fn(c: &WitContract) -> bool {
12790            c.is_pubsub()
12791        }
12792        const fn is_store_via_const_fn(c: &WitContract) -> bool {
12793            c.is_store()
12794        }
12795        const fn is_capability_via_const_fn(c: &WitContract) -> bool {
12796            c.is_capability()
12797        }
12798        // Sweep one canonical accept-set sample per WIT-shape arm plus
12799        // a payload-less capability sample, asserting the wrapper and
12800        // direct dispatches agree byte-for-byte across the closed
12801        // 4-arm partition on both the scalar-accessor trio and the
12802        // WIT-shape-predicate family.
12803        for (wit, is_http, is_pubsub, is_store, is_capability) in [
12804            ("wasi:http/proxy", true, false, false, false),
12805            ("http:incoming", true, false, false, false),
12806            ("nats:events", false, true, false, false),
12807            ("kafka:topic", false, true, false, false),
12808            ("wasi:keyvalue/store", false, false, true, false),
12809            ("kv:cache", false, false, true, false),
12810            ("custom:capability-only", false, false, false, true),
12811            ("", false, false, false, true),
12812        ] {
12813            let c = WitContract {
12814                de: "cart".into(),
12815                para: "catalog".into(),
12816                wit: wit.into(),
12817                endpoint: None,
12818                subject: None,
12819                slot: None,
12820            };
12821            assert_eq!(source_via_const_fn(&c), c.source());
12822            assert_eq!(destination_via_const_fn(&c), c.destination());
12823            assert_eq!(world_ref_via_const_fn(&c), c.world_ref());
12824            assert_eq!(is_http_via_const_fn(&c), c.is_http());
12825            assert_eq!(is_pubsub_via_const_fn(&c), c.is_pubsub());
12826            assert_eq!(is_store_via_const_fn(&c), c.is_store());
12827            assert_eq!(is_capability_via_const_fn(&c), c.is_capability());
12828            assert_eq!(c.source(), "cart");
12829            assert_eq!(c.destination(), "catalog");
12830            assert_eq!(c.world_ref(), wit);
12831            assert_eq!(c.is_http(), is_http);
12832            assert_eq!(c.is_pubsub(), is_pubsub);
12833            assert_eq!(c.is_store(), is_store);
12834            assert_eq!(c.is_capability(), is_capability);
12835        }
12836    }
12837
12838    #[test]
12839    fn wit_contract_identity_projection_accessor_is_const_fn() {
12840        // Fail-before-pass-after pin on the [`WitContract::identity`]
12841        // six-arm composite-projection accessor's `const`-eval-surface
12842        // posture. The accessor projects the typed edge's six identity
12843        // arms (`:de` / `:para` / `:wit` / `:endpoint` / `:subject` /
12844        // `:slot`) as a borrowed [`ContratoIdentity<'_>`] six-tuple —
12845        // every callee is itself `pub const fn` ([`WitContract::source`]
12846        // / [`WitContract::destination`] / [`WitContract::world_ref`]
12847        // through `String::as_str`, const-stable since Rust 1.87;
12848        // [`WitContract::endpoint`] / [`WitContract::subject`] /
12849        // [`WitContract::slot`] through the sibling `match &self
12850        // .<field> { Some(s) => Some(s.as_str()), None => None }` shape
12851        // 0650f64 closed the const-eval surface on) and the tuple
12852        // constructor from borrowed-reference / `Option`-of-borrowed-
12853        // reference arms is trivially const. Any future accidental
12854        // downgrade fails the `identity_via_const_fn` wrapper at
12855        // caixa-core build time with E0015 (`cannot call non-const
12856        // method`), strictly stronger than a runtime `assert!` and
12857        // strictly stronger than a module-scope `const _: () =
12858        // assert!(…)` pin (which cannot be formed on a `&WitContract`
12859        // fixture because the type's `String` / `Option<String>`
12860        // carriers rule out `const`-context value construction; the
12861        // `const fn` wrapper is the load-bearing shape that side-steps
12862        // the destructor-in-const restriction on the value axis while
12863        // still pinning the `const`-fn posture on the callee — mirror
12864        // of the sibling
12865        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
12866        // pin's discipline verbatim on the peer scalar-accessor
12867        // surface).
12868        //
12869        // Peer of the sibling
12870        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
12871        // (279823b) pin on the six per-`:contratos` scalar-accessor
12872        // callees this composite-projection reads through — where that
12873        // pin anchors the const-eval surface at the six individual
12874        // scalar-accessor arms, this pin extends the same posture onto
12875        // the composite six-tuple projection every consumer that dedups
12876        // typed edges on the [`ContratoIdentity`] axis keys off (the
12877        // [`AplicacaoSpec::validate`]-side duplicate-`:contratos`
12878        // scanner + its BTreeMap dedup key; a future per-Aplicacao CR
12879        // materializer's per-edge identity-based admission webhook; a
12880        // future L7 policy-emitter that shards CNPs by identity-tuple
12881        // rather than by name). Same fail-before-pass-after wrapper
12882        // discipline as the peer M2 / M3 accessor-family pins on the
12883        // sibling `const`-eval-surface passes.
12884        const fn identity_via_const_fn(c: &WitContract) -> ContratoIdentity<'_> {
12885            c.identity()
12886        }
12887        // Sweep one canonical WIT-shape sample per payload-carrier arm
12888        // plus a payload-less capability sample so the pin exercises
12889        // both `Some(_)`-carrying and `None`-carrying arms on all three
12890        // `Option<String>` payload-carrier axes (`:endpoint` / `:subject`
12891        // / `:slot`) — every wrapper dispatch must agree byte-for-byte
12892        // with the direct method call on every arm of the closed WIT-
12893        // shape partition.
12894        for (wit, endpoint, subject, slot) in [
12895            ("wasi:http/proxy", Some("/checkout"), None, None),
12896            ("http:incoming", Some("/api"), None, None),
12897            ("nats:events", None, Some("orders.placed"), None),
12898            ("kafka:topic", None, Some("orders.stream"), None),
12899            ("wasi:keyvalue/store", None, None, Some("carts/{id}")),
12900            ("kv:cache", None, None, Some("session/{token}")),
12901            ("custom:capability-only", None, None, None),
12902        ] {
12903            let c = WitContract {
12904                de: "cart".into(),
12905                para: "catalog".into(),
12906                wit: wit.into(),
12907                endpoint: endpoint.map(str::to_string),
12908                subject: subject.map(str::to_string),
12909                slot: slot.map(str::to_string),
12910            };
12911            assert_eq!(identity_via_const_fn(&c), c.identity());
12912            assert_eq!(
12913                c.identity(),
12914                ("cart", "catalog", wit, endpoint, subject, slot,),
12915            );
12916        }
12917    }
12918
12919    #[test]
12920    fn m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn() {
12921        // Fail-before-pass-after pin on the four M3 mesh-slot
12922        // `String → &str` scalar accessors ([`Membro::nome`] /
12923        // [`Membro::versao_requirement`] on the per-`:membros` axis,
12924        // [`Entrada::hostname`] / [`Entrada::destination`] on the
12925        // per-`:entrada` axis) — each projects the typed slot's
12926        // [`String`] storage through the `pub const fn`
12927        // [`String::as_str`] (const-stable since Rust 1.87, well
12928        // within the workspace MSRV) and any future accidental
12929        // downgrade to non-`const` fails the corresponding
12930        // `<name>_via_const_fn` wrapper at caixa-core build time with
12931        // E0015 (`cannot call non-const method`), strictly stronger
12932        // than a runtime `assert!` and strictly stronger than a
12933        // module-scope `const _: () = assert!(…)` pin (which cannot
12934        // be formed on `&Membro` / `&Entrada` fixtures because the
12935        // types' `String` carriers rule out `const`-context value
12936        // construction; the `const fn` wrapper is the load-bearing
12937        // shape that side-steps the destructor-in-const restriction
12938        // on the value axis while still pinning the `const`-fn
12939        // posture on the callee — mirror of the sibling
12940        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
12941        // (279823b) pin on the per-`:contratos` axis). Peer of the
12942        // sibling per-M2/M3/universal-axis `String → &str` accessor
12943        // family pins on the sibling `const`-eval-surface passes
12944        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
12945        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
12946        // typed-newtype wrapper,
12947        // [`crate::supervisor::ChildSpec::nome`] /
12948        // [`crate::supervisor::ChildSpec::versao_requirement`] at the
12949        // M2 supervisor-tree axis,
12950        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
12951        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
12952        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
12953        // axis, and the sibling per-`:contratos`
12954        // [`WitContract::source`] / [`WitContract::destination`] /
12955        // [`WitContract::world_ref`] trio at 279823b).
12956        const fn membro_nome_via_const_fn(m: &Membro) -> &str {
12957            m.nome()
12958        }
12959        const fn membro_versao_via_const_fn(m: &Membro) -> &str {
12960            m.versao_requirement()
12961        }
12962        const fn entrada_hostname_via_const_fn(e: &Entrada) -> &str {
12963            e.hostname()
12964        }
12965        const fn entrada_destination_via_const_fn(e: &Entrada) -> &str {
12966            e.destination()
12967        }
12968        for (caixa, versao) in [
12969            ("cart", "^0.1"),
12970            ("catalog-v2", "~0.2.3"),
12971            ("checkout", "*"),
12972        ] {
12973            let m = Membro {
12974                caixa: caixa.into(),
12975                versao: versao.into(),
12976            };
12977            assert_eq!(membro_nome_via_const_fn(&m), m.nome());
12978            assert_eq!(membro_versao_via_const_fn(&m), m.versao_requirement());
12979            assert_eq!(m.nome(), caixa);
12980            assert_eq!(m.versao_requirement(), versao);
12981        }
12982        for (host, para) in [
12983            ("cart.example.com", "cart"),
12984            ("api.checkout.io", "checkout"),
12985        ] {
12986            let e = Entrada {
12987                host: host.into(),
12988                para: para.into(),
12989                paths: vec![],
12990                port: DEFAULT_SERVICO_PORT,
12991            };
12992            assert_eq!(entrada_hostname_via_const_fn(&e), e.hostname());
12993            assert_eq!(entrada_destination_via_const_fn(&e), e.destination());
12994            assert_eq!(e.hostname(), host);
12995            assert_eq!(e.destination(), para);
12996        }
12997    }
12998
12999    #[test]
13000    fn m3_option_string_scalar_accessor_family_is_const_fn() {
13001        // Fail-before-pass-after pin on the five M3 mesh-slot
13002        // `Option<String> → Option<&str>` scalar accessors
13003        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
13004        // [`WitContract::slot`] on the per-`:contratos` HTTP /
13005        // pub-sub / key-value payload-carrier trio,
13006        // [`Placement::shard_key`] / [`Placement::affinity`] on the
13007        // per-`:placement` Akka-sharding-key + Adaptive-compression-
13008        // hint pair). Each accessor destructures the typed slot's
13009        // `Option<String>` storage through the `match &self.<field> {
13010        // Some(s) => Some(s.as_str()), None => None }` shape —
13011        // routing through [`String::as_str`] (const-stable since Rust
13012        // 1.87, well within the workspace MSRV) rather than the
13013        // non-const [`Option::as_deref`] the pre-lift bodies carried
13014        // — and any future accidental downgrade to non-`const` fails
13015        // the corresponding `<name>_via_const_fn` wrapper at
13016        // caixa-core build time with E0015 (`cannot call non-const
13017        // method`), strictly stronger than a runtime `assert!` and
13018        // strictly stronger than a module-scope `const _: () =
13019        // assert!(…)` pin (which cannot be formed on `&WitContract`
13020        // / `&Placement` fixtures because the types' `String` /
13021        // `Option<String>` carriers rule out `const`-context value
13022        // construction; the `const fn` wrapper is the load-bearing
13023        // shape that side-steps the destructor-in-const restriction
13024        // on the value axis while still pinning the `const`-fn
13025        // posture on the callee — mirror of the sibling
13026        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
13027        // (279823b) and
13028        // [`m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn`]
13029        // (29c5d7e) pins on the peer `String → &str` axes at the same
13030        // structs).
13031        //
13032        // Peer of the sibling per-`Caixa` `Option<String> →
13033        // Option<&str>` accessor family pin
13034        // [`crate::manifest::tests::caixa_option_string_scalar_accessor_family_is_const_fn`]
13035        // on the top-level manifest's optional universal-axis surface
13036        // (`:licenca` / `:repositorio` / `:descricao` / `:edicao` /
13037        // `:restart-window`).
13038        const fn wit_endpoint_via_const_fn(w: &WitContract) -> Option<&str> {
13039            w.endpoint()
13040        }
13041        const fn wit_subject_via_const_fn(w: &WitContract) -> Option<&str> {
13042            w.subject()
13043        }
13044        const fn wit_slot_via_const_fn(w: &WitContract) -> Option<&str> {
13045            w.slot()
13046        }
13047        const fn placement_shard_key_via_const_fn(p: &Placement) -> Option<&str> {
13048            p.shard_key()
13049        }
13050        const fn placement_affinity_via_const_fn(p: &Placement) -> Option<&str> {
13051            p.affinity()
13052        }
13053        // Sweep every closed shape-arm partition on the
13054        // per-`:contratos` payload-carrier trio: HTTP (`:endpoint`
13055        // Some, sibling pair None), pub-sub (`:subject` Some, sibling
13056        // pair None), key-value (`:slot` Some, sibling pair None),
13057        // and Capability (all three None) so each accessor's
13058        // Some/None arm carries a pin through the const dispatch.
13059        for (wit, endpoint, subject, slot) in [
13060            ("wasi:http/proxy", Some("/api"), None, None),
13061            ("nats:pub-sub", None, Some("orders.paid"), None),
13062            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
13063            ("custom:capability-only", None, None, None),
13064        ] {
13065            let c = WitContract {
13066                de: "cart".into(),
13067                para: "catalog".into(),
13068                wit: wit.into(),
13069                endpoint: endpoint.map(str::to_string),
13070                subject: subject.map(str::to_string),
13071                slot: slot.map(str::to_string),
13072            };
13073            assert_eq!(wit_endpoint_via_const_fn(&c), c.endpoint());
13074            assert_eq!(wit_subject_via_const_fn(&c), c.subject());
13075            assert_eq!(wit_slot_via_const_fn(&c), c.slot());
13076            assert_eq!(c.endpoint(), endpoint);
13077            assert_eq!(c.subject(), subject);
13078            assert_eq!(c.slot(), slot);
13079        }
13080        // Sweep both `Some`/`None` arms on each per-`:placement`
13081        // optional-scalar so the shard-key + affinity pair carries a
13082        // const-dispatch pin on both arms.
13083        for (shard_key, affinity) in [
13084            (Some("tenantId"), Some("data-locality")),
13085            (Some("$tenantId"), None),
13086            (None, Some("low-latency")),
13087            (None, None),
13088        ] {
13089            let p = Placement {
13090                estrategia: PlacementStrategy::default(),
13091                clusters: vec![],
13092                affinity: affinity.map(str::to_string),
13093                shard_key: shard_key.map(str::to_string),
13094            };
13095            assert_eq!(placement_shard_key_via_const_fn(&p), p.shard_key());
13096            assert_eq!(placement_affinity_via_const_fn(&p), p.affinity());
13097            assert_eq!(p.shard_key(), shard_key);
13098            assert_eq!(p.affinity(), affinity);
13099        }
13100    }
13101
13102    #[test]
13103    fn m3_placement_entrada_slice_return_accessor_pair_is_const_fn() {
13104        // Fail-before-pass-after pin on the two M3-mesh-slot inner-
13105        // composite `Vec → &[String]` slice-return accessors on
13106        // [`Placement::clusters`] and [`Entrada::paths`]. Each
13107        // destructures the typed slot's `Vec<String>` storage through
13108        // the `pub const fn` [`Vec::as_slice`] (const-stable since Rust
13109        // 1.66, well within the workspace MSRV) — any future accidental
13110        // downgrade to non-`const` fails the corresponding
13111        // `<name>_via_const_fn` wrapper at caixa-core build time with
13112        // E0015 (`cannot call non-const method`), strictly stronger
13113        // than a runtime `assert!`. Sibling of the peer
13114        // [`m3_aplicacao_spec_reference_return_accessor_family_is_const_fn`]
13115        // pin on the outer-`AplicacaoSpec` reference-return family
13116        // (`:membros` / `:contratos` slice-return + `:politicas` /
13117        // `:placement` / `:entrada` composite-reference), and of the
13118        // peer M2 slice-return axis pins
13119        // [`crate::supervisor::tests::supervisor_children_slice_return_accessor_is_const_fn`]
13120        // (on `SupervisorSpec::children`) and
13121        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
13122        // (on `UpgradeFromEntry::instructions`). Together the four
13123        // pins close the last unlifted reference-return accessor
13124        // family across the substrate primitive.
13125        const fn placement_clusters_via_const_fn(p: &Placement) -> &[String] {
13126            p.clusters()
13127        }
13128        const fn entrada_paths_via_const_fn(e: &Entrada) -> &[String] {
13129            e.paths()
13130        }
13131        // Sweep both the empty-Vec (no author-declared entries) and
13132        // the populated-Vec arms on every slice-return accessor so
13133        // each carries a const-dispatch pin on both arms.
13134        let p_empty = Placement {
13135            estrategia: PlacementStrategy::default(),
13136            clusters: vec![],
13137            affinity: None,
13138            shard_key: None,
13139        };
13140        let p_full = Placement {
13141            estrategia: PlacementStrategy::default(),
13142            clusters: vec!["prod-a".into(), "prod-b".into()],
13143            affinity: None,
13144            shard_key: None,
13145        };
13146        assert_eq!(
13147            placement_clusters_via_const_fn(&p_empty),
13148            p_empty.clusters()
13149        );
13150        assert_eq!(placement_clusters_via_const_fn(&p_full), p_full.clusters());
13151        assert!(p_empty.clusters().is_empty());
13152        assert_eq!(p_full.clusters(), &["prod-a", "prod-b"]);
13153        let e_empty = Entrada {
13154            host: "web.example.com".into(),
13155            para: "web".into(),
13156            paths: vec![],
13157            port: DEFAULT_SERVICO_PORT,
13158        };
13159        let e_full = Entrada {
13160            host: "web.example.com".into(),
13161            para: "web".into(),
13162            paths: vec!["/api".into(), "/health".into()],
13163            port: DEFAULT_SERVICO_PORT,
13164        };
13165        assert_eq!(entrada_paths_via_const_fn(&e_empty), e_empty.paths());
13166        assert_eq!(entrada_paths_via_const_fn(&e_full), e_full.paths());
13167        assert!(e_empty.paths().is_empty());
13168        assert_eq!(e_full.paths(), &["/api", "/health"]);
13169    }
13170
13171    #[test]
13172    fn m3_aplicacao_spec_reference_return_accessor_family_is_const_fn() {
13173        // Fail-before-pass-after pin on the five outer-`AplicacaoSpec`
13174        // reference-return accessors — the two `Vec → &[T]` slice-
13175        // return accessors on [`AplicacaoSpec::membros`] and
13176        // [`AplicacaoSpec::contratos`] (each routes through the
13177        // `pub const fn` [`Vec::as_slice`], const-stable since Rust
13178        // 1.66), the two `&Composite` composite-reference accessors
13179        // on [`AplicacaoSpec::politicas`] and
13180        // [`AplicacaoSpec::placement`] (each routes through a raw
13181        // `&self.<field>` borrow, trivially const), and the one
13182        // `Option<&Composite>` optional-composite-reference accessor
13183        // on [`AplicacaoSpec::entrada`] (routes through the
13184        // `pub const fn` [`Option::as_ref`], const-stable since Rust
13185        // 1.83). Any future accidental downgrade to non-`const` fails
13186        // the corresponding `<name>_via_const_fn` wrapper at caixa-
13187        // core build time with E0015 (`cannot call non-const
13188        // method`), strictly stronger than a runtime `assert!`.
13189        // Sibling of the peer inner-composite pin
13190        // [`m3_placement_entrada_slice_return_accessor_pair_is_const_fn`]
13191        // on the `Placement::clusters` + `Entrada::paths` slice-
13192        // return pair, and of the peer M2 axis pins on
13193        // [`crate::supervisor::SupervisorSpec::children`] and
13194        // [`crate::upgrade::UpgradeFromEntry::instructions`].
13195        const fn aplicacao_membros_via_const_fn(s: &AplicacaoSpec) -> &[Membro] {
13196            s.membros()
13197        }
13198        const fn aplicacao_contratos_via_const_fn(s: &AplicacaoSpec) -> &[WitContract] {
13199            s.contratos()
13200        }
13201        const fn aplicacao_politicas_via_const_fn(s: &AplicacaoSpec) -> &MeshPolicy {
13202            s.politicas()
13203        }
13204        const fn aplicacao_placement_via_const_fn(s: &AplicacaoSpec) -> &Placement {
13205            s.placement()
13206        }
13207        const fn aplicacao_entrada_via_const_fn(s: &AplicacaoSpec) -> Option<&Entrada> {
13208            s.entrada()
13209        }
13210        // Construct both a minimal "no :entrada" (internal-only
13211        // mesh) and a full "with :entrada" (external-gateway)
13212        // fixture so the family pins both the `None`-arm (author-
13213        // omitted `:entrada`) and the `Some`-arm (author-declared
13214        // `:entrada`) on the optional-composite axis.
13215        let membro = Membro {
13216            caixa: "web".into(),
13217            versao: "^0.1".into(),
13218        };
13219        let entrada_full = Entrada {
13220            host: "web.example.com".into(),
13221            para: "web".into(),
13222            paths: vec!["/api".into()],
13223            port: DEFAULT_SERVICO_PORT,
13224        };
13225        let internal_only = AplicacaoSpec {
13226            membros: vec![membro.clone()],
13227            contratos: vec![],
13228            politicas: MeshPolicy::default(),
13229            placement: Placement::default(),
13230            entrada: None,
13231        };
13232        let with_entrada = AplicacaoSpec {
13233            membros: vec![membro],
13234            contratos: vec![],
13235            politicas: MeshPolicy::default(),
13236            placement: Placement::default(),
13237            entrada: Some(entrada_full),
13238        };
13239        assert_eq!(
13240            aplicacao_membros_via_const_fn(&internal_only),
13241            internal_only.membros()
13242        );
13243        assert_eq!(
13244            aplicacao_membros_via_const_fn(&with_entrada),
13245            with_entrada.membros()
13246        );
13247        assert_eq!(
13248            aplicacao_contratos_via_const_fn(&internal_only),
13249            internal_only.contratos()
13250        );
13251        assert!(std::ptr::eq(
13252            aplicacao_politicas_via_const_fn(&internal_only),
13253            internal_only.politicas(),
13254        ));
13255        assert!(std::ptr::eq(
13256            aplicacao_placement_via_const_fn(&internal_only),
13257            internal_only.placement(),
13258        ));
13259        assert!(aplicacao_entrada_via_const_fn(&internal_only).is_none());
13260        match (
13261            aplicacao_entrada_via_const_fn(&with_entrada),
13262            with_entrada.entrada(),
13263        ) {
13264            (Some(a), Some(b)) => assert!(std::ptr::eq(a, b)),
13265            _ => panic!(
13266                "aplicacao_entrada_via_const_fn must agree with \
13267                 AplicacaoSpec::entrada on the Some-arm reference"
13268            ),
13269        }
13270    }
13271
13272    #[test]
13273    fn target_projected_returns_byte_equal_typed_view_across_all_four_arms() {
13274        // Load-bearing contract pin: on every canonical
13275        // `(:wit, :endpoint/:subject/:slot)` shape the substrate admits,
13276        // [`WitContract::target_projected`] returns byte-equal to
13277        // [`WitContract::target`]`().unwrap()` — the post-validation
13278        // projection accessor is a thin panicking wrapper over the
13279        // pre-validation validator, no extra work in the projection
13280        // path. Any future divergence (a validator-side normalization
13281        // the projection doesn't route through, an accessor-side
13282        // caching layer the validator doesn't populate) would surface
13283        // here at caixa-core build time rather than a silent per-consumer
13284        // split at renderer emit time. Sweeps the closed 4-arm
13285        // [`WitTarget`] partition ([`WitTarget::Http`] /
13286        // [`WitTarget::PubSub`] / [`WitTarget::Store`] /
13287        // [`WitTarget::Capability`]) so every arm carries a byte-equality
13288        // pin on the two-accessor pair.
13289        for (wit, endpoint, subject, slot) in [
13290            ("wasi:http/proxy", Some("/x"), None, None),
13291            ("nats:pub-sub", None, Some("events.x"), None),
13292            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
13293            ("custom:capability-only", None, None, None),
13294        ] {
13295            let c = WitContract {
13296                de: "cart".into(),
13297                para: "catalog".into(),
13298                wit: wit.into(),
13299                endpoint: endpoint.map(str::to_string),
13300                subject: subject.map(str::to_string),
13301                slot: slot.map(str::to_string),
13302            };
13303            assert_eq!(
13304                c.target_projected(),
13305                c.target().unwrap(),
13306                "target_projected must return byte-equal to target().unwrap() at wit={wit:?}"
13307            );
13308        }
13309    }
13310
13311    #[test]
13312    #[should_panic(expected = "validated by typed_view")]
13313    fn target_projected_panics_with_canonical_message_on_unvalidated_contract() {
13314        // Panic-path pin: [`WitContract::target_projected`] threads the
13315        // canonical [`WitContract::PROJECTED_INVARIANT_MSG`] byte-string
13316        // through its expect-panic when called on a contract whose
13317        // (`:wit`, payload) shape has not been crossed by
13318        // [`AplicacaoSpec::validate`] — a contract with a structurally-
13319        // invalid `:wit` (hyphen-for-colon typo) that would surface
13320        // [`AplicacaoError::ContratoWitInvalid`] at the validator gate.
13321        // A future rebrand on the panic-message axis would land at one
13322        // caixa-core edit on [`WitContract::PROJECTED_INVARIANT_MSG`]
13323        // and this pin's [`should_panic(expected = …)`] literal would
13324        // migrate alongside — the pin catches drift between the const
13325        // and the accessor's `expect(…)` call by construction.
13326        let c = WitContract {
13327            de: "cart".into(),
13328            para: "catalog".into(),
13329            // Hyphen-for-colon typo: `WitContract::target` returns
13330            // [`AplicacaoError::ContratoWitInvalid`] on this shape,
13331            // driving the [`WitContract::target_projected`] expect-panic.
13332            wit: "wasi-http/proxy".into(),
13333            endpoint: Some("/x".into()),
13334            subject: None,
13335            slot: None,
13336        };
13337        let _ = c.target_projected();
13338    }
13339
13340    #[test]
13341    fn target_projected_invariant_msg_matches_prior_inline_call_site_literal() {
13342        // Byte-equivalence pin: [`WitContract::PROJECTED_INVARIANT_MSG`]
13343        // carries the exact byte-string the two prior open-coded
13344        // `.target().expect("validated by typed_view")` production
13345        // consumers threaded through inline before this lift converged
13346        // them onto [`WitContract::target_projected`] — the caixa-mesh
13347        // per-`(:de, :para)` CNP L7 introspection branch at
13348        // `caixa-mesh/src/lib.rs:2825` and the caixa-feira `feira app
13349        // graph` per-`:contratos` payload-column printer at
13350        // `caixa-feira/src/cmd/app.rs:110`. Locks the panic-message
13351        // byte-string load-bearing so a well-meaning const-side rebrand
13352        // that didn't carry a matched pin migration would surface here
13353        // at caixa-core build time rather than a silent per-consumer
13354        // panic-message drift at cluster-apply time. Peer of the
13355        // sibling [`WitTarget::CAPABILITY_LABEL`] /
13356        // [`WitTarget::CAPABILITY_EXPECTED`] /
13357        // [`WitTarget::CAPABILITY_GRAPH_LABEL`] byte-equivalence pins on
13358        // the paired payload-less-arm scalar-const family.
13359        assert_eq!(
13360            WitContract::PROJECTED_INVARIANT_MSG,
13361            "validated by typed_view"
13362        );
13363    }
13364
13365    #[test]
13366    fn empty_wit_takes_precedence_over_invalid() {
13367        // Ordering pin: `EmptyWit` is the more self-locating
13368        // diagnostic on `""` and must lead — the value-shape gate is
13369        // only reached after the empty-check fires. Mirrors
13370        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
13371        // the peer payload axis.
13372        let mut s = three_member_spec();
13373        s.contratos.push(WitContract {
13374            de: "payment".into(),
13375            para: "catalog".into(),
13376            wit: String::new(),
13377            endpoint: None,
13378            subject: None,
13379            slot: None,
13380        });
13381        let err = s.validate().unwrap_err();
13382        assert!(
13383            matches!(err, AplicacaoError::EmptyWit { .. }),
13384            "got {err:?}"
13385        );
13386    }
13387
13388    #[test]
13389    fn wit_invalid_fires_before_payload_shape_arm() {
13390        // Ordering pin: a malformed `:wit` surfaces *its own*
13391        // diagnostic (which names the offending wit verbatim) before
13392        // any payload-field check — a contrato whose wit is
13393        // structurally invalid AND carries a wrong target field
13394        // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
13395        // because the dispatch on the wit is what decides which
13396        // payload field is "right" in the first place. Without this
13397        // ordering, the author would see "wrong target field" for a
13398        // wit that hasn't even been parsed, which doesn't name the
13399        // root cause.
13400        let mut s = three_member_spec();
13401        s.contratos.push(WitContract {
13402            de: "payment".into(),
13403            para: "catalog".into(),
13404            // Hyphen-for-colon typo + endpoint set: pre-gate this
13405            // raised `ContratoWrongTarget { expected: "none" }` (the
13406            // Capability arm rejecting the endpoint), masking the
13407            // real authoring mistake (the wit isn't `wasi:http/proxy`).
13408            wit: "wasi-http/proxy".into(),
13409            endpoint: Some("/x".into()),
13410            subject: None,
13411            slot: None,
13412        });
13413        let err = s.validate().unwrap_err();
13414        assert!(
13415            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
13416                if wit == "wasi-http/proxy"),
13417            "got {err:?}"
13418        );
13419    }
13420
13421    #[test]
13422    fn wit_invalid_diagnostic_carries_offending_wit() {
13423        // Diagnostic-shape pin — the offending `:wit` + `:de` +
13424        // `:para` + a non-empty reason flow through verbatim so the
13425        // author can grep their caixa.lisp for the offending contrato
13426        // block and fix it in one edit. Same shape as
13427        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
13428        let err = contrato_wit_err("WASI:HTTP/proxy");
13429        match err {
13430            AplicacaoError::ContratoWitInvalid {
13431                de,
13432                para,
13433                wit,
13434                reason,
13435            } => {
13436                assert_eq!(de, "payment");
13437                assert_eq!(para, "catalog");
13438                assert_eq!(wit, "WASI:HTTP/proxy");
13439                assert!(!reason.is_empty(), "reason field must be non-empty");
13440            }
13441            other => panic!("expected ContratoWitInvalid, got {other:?}"),
13442        }
13443    }
13444
13445    // ── :contratos :subject value-shape gate ─────────────────────────────
13446    //
13447    // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
13448    // suites on the peer payload axes. Until this gate landed
13449    // `WitContract::target()` only refused the empty string; a
13450    // structurally invalid subject silently passed validate and the
13451    // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
13452    // Subject'` on publish / subscribe, or as a silent message drop,
13453    // far from the source caixa.lisp. Every authoring footgun the
13454    // NATS server's subject parser would catch on admission now
13455    // becomes a caixa-build-time `ContratoSubjectInvalid` with the
13456    // offending `:subject` + `:de` + `:para` named verbatim. Same
13457    // diagnostic shape as `ContratoEndpointInvalid` /
13458    // `ContratoWitInvalid` on the peer payload axes; same shared
13459    // predicate (`crate::render::is_nats_subject`) ensures drift
13460    // between any two axes' rule enforcement is a build error at the
13461    // predicate, not piecemeal across renderers.
13462
13463    fn contrato_subject_err(subject: &str) -> AplicacaoError {
13464        // Fresh spec per call so the new contract doesn't collide on
13465        // identity with `three_member_spec`'s pre-existing entries.
13466        // The new edge uses `(payment, catalog)` — a pair the fixture
13467        // doesn't already declare — with `:wit "nats:pub-sub"` and the
13468        // varying `:subject`, so the subject-shape gate fires cleanly
13469        // after the wit-shape gate (which `"nats:pub-sub"` passes).
13470        let mut s = three_member_spec();
13471        s.contratos.push(WitContract {
13472            de: "payment".into(),
13473            para: "catalog".into(),
13474            wit: "nats:pub-sub".into(),
13475            endpoint: None,
13476            subject: Some(subject.into()),
13477            slot: None,
13478        });
13479        s.validate().unwrap_err()
13480    }
13481
13482    #[test]
13483    fn rejects_pubsub_contrato_subject_with_whitespace() {
13484        // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
13485        // landed at the NATS server as a malformed subject the parser
13486        // rejects with `-ERR 'Invalid Subject'`. Now caught at the
13487        // source caixa.lisp.
13488        let err = contrato_subject_err("foo bar");
13489        assert!(
13490            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
13491                if subject == "foo bar" && reason.contains("whitespace")),
13492            "got {err:?}"
13493        );
13494    }
13495
13496    #[test]
13497    fn rejects_pubsub_contrato_subject_with_control_char() {
13498        let err = contrato_subject_err("foo\x01bar");
13499        assert!(
13500            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
13501                if subject == "foo\x01bar" && reason.contains("control character")),
13502            "got {err:?}"
13503        );
13504    }
13505
13506    #[test]
13507    fn rejects_pubsub_contrato_subject_with_non_ascii() {
13508        // Un-percent-encoded non-ASCII byte — the canonical "I copied
13509        // the subject from a doc with smart quotes / accented
13510        // characters" footgun.
13511        let err = contrato_subject_err("foo.caf\u{e9}");
13512        assert!(
13513            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
13514                if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
13515            "got {err:?}"
13516        );
13517    }
13518
13519    #[test]
13520    fn rejects_pubsub_contrato_subject_with_leading_dot() {
13521        // Empty leading token — NATS rejects.
13522        let err = contrato_subject_err(".foo");
13523        assert!(
13524            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
13525                if subject == ".foo" && reason.contains("must not start with `.`")),
13526            "got {err:?}"
13527        );
13528    }
13529
13530    #[test]
13531    fn rejects_pubsub_contrato_subject_with_trailing_dot() {
13532        // Empty trailing token — NATS rejects. The remediation
13533        // (use `>` instead) is in the reason string.
13534        let err = contrato_subject_err("foo.");
13535        assert!(
13536            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
13537                if subject == "foo." && reason.contains("must not end with `.`")),
13538            "got {err:?}"
13539        );
13540    }
13541
13542    #[test]
13543    fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
13544        // The canonical "I forgot to fill in the middle segment"
13545        // typo — `"foo..bar"`. NATS rejects empty tokens.
13546        let err = contrato_subject_err("foo..bar");
13547        assert!(
13548            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
13549                if subject == "foo..bar" && reason.contains("consecutive `.`")),
13550            "got {err:?}"
13551        );
13552    }
13553
13554    #[test]
13555    fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
13556        // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
13557        // as the final segment. Pre-gate this passed as a typed edge
13558        // and surfaced at runtime as a NATS subscribe rejection.
13559        let err = contrato_subject_err("foo.>.bar");
13560        assert!(
13561            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
13562                if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
13563            "got {err:?}"
13564        );
13565    }
13566
13567    #[test]
13568    fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
13569        // `foo*.bar` — NATS wildcards are standalone tokens. The
13570        // remediation is in the reason string.
13571        let err = contrato_subject_err("foo*.bar");
13572        assert!(
13573            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
13574                if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
13575            "got {err:?}"
13576        );
13577    }
13578
13579    #[test]
13580    fn rejects_pubsub_contrato_subject_with_invalid_char() {
13581        // `foo,bar` — comma is not a valid NATS subject character.
13582        // Pinned separately from the wildcard arms so the invalid-
13583        // character diagnostic is in force.
13584        let err = contrato_subject_err("foo,bar");
13585        assert!(
13586            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
13587                if subject == "foo,bar" && reason.contains("invalid character")),
13588            "got {err:?}"
13589        );
13590    }
13591
13592    #[test]
13593    fn rejects_pubsub_contrato_subject_too_long() {
13594        // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
13595        // The legitimate-shape arms all pass (one all-`a` token, no
13596        // `.`, no wildcards); only the cap arm fires. Surfaces the
13597        // paste-from-binary / accidental-multi-line-blob landing
13598        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
13599        // on the peer axis.
13600        let big = "a".repeat(257);
13601        assert_eq!(big.len(), 257);
13602        let err = contrato_subject_err(&big);
13603        assert!(
13604            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
13605                if subject == &big && reason.contains("max length of 256")),
13606            "got {err:?}"
13607        );
13608    }
13609
13610    #[test]
13611    fn pubsub_contrato_subject_max_length_validates() {
13612        // 256-byte subject — exactly the cap. Boundary pin: drift in
13613        // the cap surfaces here and at
13614        // `rejects_pubsub_contrato_subject_too_long` simultaneously,
13615        // mirroring `http_contrato_endpoint_max_length_validates` and
13616        // `wit_max_length_validates` on the peer axes.
13617        let big = "a".repeat(256);
13618        assert_eq!(big.len(), 256);
13619        let mut s = three_member_spec();
13620        s.contratos.push(WitContract {
13621            de: "payment".into(),
13622            para: "catalog".into(),
13623            wit: "nats:pub-sub".into(),
13624            endpoint: None,
13625            subject: Some(big),
13626            slot: None,
13627        });
13628        s.validate().unwrap();
13629    }
13630
13631    #[test]
13632    fn pubsub_contrato_subject_accepts_canonical_forms() {
13633        // Positive-set sweep: every canonical NATS subject shape the
13634        // substrate-side `is_nats_subject` predicate accepts (the
13635        // multi-dot `events.order.charged`, the snake_case / kebab-
13636        // case / mixed-case tokens, the digit-bearing tokens, the
13637        // single-token wildcard `*` at every segment position, and
13638        // the trailing `>` multi-token wildcard) must remain a valid
13639        // contrato subject too. Drift between this list and the
13640        // substrate-side `nats_subject_accepts_canonical_forms` sweep
13641        // surfaces at the shared predicate — one source of truth.
13642        // Uses a fresh `(payment, catalog)` edge so none of the swept
13643        // subjects collide with the pre-existing entries in
13644        // `three_member_spec`.
13645        for subject in [
13646            "checkout.events.charge.failed",
13647            "rio.events.order.charged",
13648            "orders",
13649            "orders.123",
13650            "snake_case.token",
13651            "kebab-case.token",
13652            "MixedCase.Token",
13653            "orders.*.charged",
13654            "*.events.*",
13655            "orders.>",
13656        ] {
13657            let mut s = three_member_spec();
13658            s.contratos.push(WitContract {
13659                de: "payment".into(),
13660                para: "catalog".into(),
13661                wit: "nats:pub-sub".into(),
13662                endpoint: None,
13663                subject: Some(subject.into()),
13664                slot: None,
13665            });
13666            s.validate()
13667                .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
13668        }
13669    }
13670
13671    #[test]
13672    fn contrato_subject_empty_takes_precedence_over_invalid() {
13673        // Ordering pin: `ContratoSubjectEmpty` is the more self-
13674        // locating diagnostic on `""` and must lead — the value-shape
13675        // gate is only reached after the empty-check fires. Mirrors
13676        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
13677        // the peer payload axis.
13678        let mut s = three_member_spec();
13679        s.contratos.push(WitContract {
13680            de: "payment".into(),
13681            para: "catalog".into(),
13682            wit: "nats:pub-sub".into(),
13683            endpoint: None,
13684            subject: Some(String::new()),
13685            slot: None,
13686        });
13687        let err = s.validate().unwrap_err();
13688        assert!(
13689            matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
13690            "got {err:?}"
13691        );
13692    }
13693
13694    #[test]
13695    fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
13696        // Diagnostic-shape pin — the offending `:subject` + `:de` +
13697        // `:para` + a non-empty reason flow through verbatim so the
13698        // author can grep their caixa.lisp for the offending contrato
13699        // block and fix it in one edit. Same shape as
13700        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
13701        // and `wit_invalid_diagnostic_carries_offending_wit`.
13702        let err = contrato_subject_err("foo..bar");
13703        match err {
13704            AplicacaoError::ContratoSubjectInvalid {
13705                de,
13706                para,
13707                subject,
13708                reason,
13709            } => {
13710                assert_eq!(de, "payment");
13711                assert_eq!(para, "catalog");
13712                assert_eq!(subject, "foo..bar");
13713                assert!(!reason.is_empty(), "reason field must be non-empty");
13714            }
13715            other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
13716        }
13717    }
13718
13719    #[test]
13720    fn target_view_pubsub_subject_passes_through_to_typed_view() {
13721        // The compounding theorem on the pub-sub axis: every
13722        // `WitTarget::PubSub { subject }` returned by `target()` carries
13723        // a NATS-server-accepted subject. Renderers downstream of
13724        // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
13725        // NATS Stream/Consumer CR emitter, the future `feira app graph`
13726        // view's subject labeller) can rely on this without re-checking
13727        // — the type system carries the proof. Mirrors
13728        // `target_view_payload_is_guaranteed_nonempty_after_target_call`
13729        // on the peer axes.
13730        let nats = WitContract {
13731            de: "a".into(),
13732            para: "b".into(),
13733            wit: "nats:pub-sub".into(),
13734            endpoint: None,
13735            subject: Some("orders.events.*.charged".into()),
13736            slot: None,
13737        };
13738        match nats.target().unwrap() {
13739            WitTarget::PubSub { subject } => {
13740                assert_eq!(subject, "orders.events.*.charged");
13741            }
13742            other => panic!("expected PubSub, got {other:?}"),
13743        }
13744    }
13745
13746    // ── :contratos :slot value-shape gate ────────────────────────────────
13747    //
13748    // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
13749    // (63e18a0) value-shape suites on the peer payload axes. Until this
13750    // gate landed `WitContract::target()` only refused the empty string
13751    // for the Store arm; a structurally invalid slot (raw whitespace,
13752    // control character, non-ASCII byte, paste-from-binary multi-line
13753    // blob) silently passed validate and surfaced at runtime as a
13754    // per-backend kv write rejection or a silent next-read corruption,
13755    // far from the source caixa.lisp with no field naming which
13756    // `:contratos` edge carried the typo. Every authoring footgun the
13757    // kv backend intersection-floor would catch on write now becomes a
13758    // caixa-build-time `ContratoSlotInvalid` with the offending
13759    // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
13760    // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
13761    // peer payload axes; same shared predicate
13762    // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
13763    // any two axes' rule enforcement is a build error at the
13764    // predicate, not piecemeal across renderers. Closes the typed
13765    // payload-axis value-shape trajectory across all three legs of the
13766    // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
13767
13768    fn contrato_slot_err(slot: &str) -> AplicacaoError {
13769        // Fresh spec per call so the new contract doesn't collide on
13770        // identity with `three_member_spec`'s pre-existing entries
13771        // and doesn't close a synchronous cycle the cycle detector
13772        // would reject before the slot-shape gate fires. The new edge
13773        // uses `(payment, catalog)` — a pair the fixture doesn't
13774        // already declare in either direction (the fixture carries
13775        // `cart -> catalog` and `cart -> payment`, so `payment ->
13776        // catalog` doesn't form a cycle on the sync subgraph) — with
13777        // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
13778        // slot-shape gate fires cleanly after the wit-shape gate
13779        // (which `"wasi:keyvalue/store"` passes). Same edge pair the
13780        // peer `contrato_subject_err` helper uses (63e18a0).
13781        let mut s = three_member_spec();
13782        s.contratos.push(WitContract {
13783            de: "payment".into(),
13784            para: "catalog".into(),
13785            wit: "wasi:keyvalue/store".into(),
13786            endpoint: None,
13787            subject: None,
13788            slot: Some(slot.into()),
13789        });
13790        s.validate().unwrap_err()
13791    }
13792
13793    #[test]
13794    fn rejects_store_contrato_slot_with_whitespace() {
13795        // Fail-before-pass-after pin — pre-gate `"check out/$order"`
13796        // silently landed at the kv backend with whitespace whose
13797        // runtime behavior varies unpredictably across backends (etcd
13798        // accepts, Redis accepts then breaks on next CLI op, DynamoDB
13799        // rejects on write). Now caught at the source caixa.lisp.
13800        let err = contrato_slot_err("check out/$order");
13801        assert!(
13802            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
13803                if slot == "check out/$order" && reason.contains("whitespace")),
13804            "got {err:?}"
13805        );
13806    }
13807
13808    #[test]
13809    fn rejects_store_contrato_slot_with_tab() {
13810        // Tab byte arm-pinned separately from the space arm so a
13811        // future relaxation that admits one but not the other surfaces
13812        // here.
13813        let err = contrato_slot_err("check\tout");
13814        assert!(
13815            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
13816                if slot == "check\tout" && reason.contains("whitespace")),
13817            "got {err:?}"
13818        );
13819    }
13820
13821    #[test]
13822    fn rejects_store_contrato_slot_with_control_char() {
13823        // SOH (0x01) — distinct from the whitespace arm. Redis admits
13824        // and corrupts on RESP protocol framing; DynamoDB rejects on
13825        // write.
13826        let err = contrato_slot_err("checkout/\x01order");
13827        assert!(
13828            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
13829                if slot == "checkout/\x01order" && reason.contains("control character")),
13830            "got {err:?}"
13831        );
13832    }
13833
13834    #[test]
13835    fn rejects_store_contrato_slot_with_newline() {
13836        // Embedded newline — the canonical "the paste-from-binary slug
13837        // spans multiple lines" footgun. Distinct from the whitespace
13838        // arm because `\n` is a control character (0x0A).
13839        let err = contrato_slot_err("checkout\norder");
13840        assert!(
13841            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
13842                if slot == "checkout\norder" && reason.contains("control character")),
13843            "got {err:?}"
13844        );
13845    }
13846
13847    #[test]
13848    fn rejects_store_contrato_slot_with_non_ascii() {
13849        // Un-percent-encoded non-ASCII byte — the canonical "I copied
13850        // the slot from a doc with accented characters" footgun. Each
13851        // kv backend re-encodes non-ASCII differently (etcd preserves
13852        // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
13853        // rejects), so the typed slot's value set is the intersection-
13854        // floor every backend admits identically (printable ASCII).
13855        let err = contrato_slot_err("ch\u{e9}ckout/$order");
13856        assert!(
13857            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
13858                if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
13859            "got {err:?}"
13860        );
13861    }
13862
13863    #[test]
13864    fn rejects_store_contrato_slot_too_long() {
13865        // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
13866        // legitimate-shape arms all pass (a single all-`a` token, no
13867        // separators); only the cap arm fires. Surfaces the paste-
13868        // from-binary / accidental-multi-line-blob landing footgun.
13869        // Mirrors `rejects_pubsub_contrato_subject_too_long` and
13870        // `rejects_http_contrato_endpoint_too_long` on the peer
13871        // payload axes.
13872        let big = "a".repeat(513);
13873        assert_eq!(big.len(), 513);
13874        let err = contrato_slot_err(&big);
13875        assert!(
13876            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
13877                if slot == &big && reason.contains("max length of 512")),
13878            "got {err:?}"
13879        );
13880    }
13881
13882    #[test]
13883    fn store_contrato_slot_max_length_validates() {
13884        // 512-byte slot — exactly the cap. Boundary pin: drift in the
13885        // cap surfaces here and at `rejects_store_contrato_slot_too_long`
13886        // simultaneously, mirroring
13887        // `pubsub_contrato_subject_max_length_validates` and
13888        // `http_contrato_endpoint_max_length_validates` on the peer
13889        // payload axes.
13890        let big = "a".repeat(512);
13891        assert_eq!(big.len(), 512);
13892        let mut s = three_member_spec();
13893        s.contratos.push(WitContract {
13894            de: "payment".into(),
13895            para: "catalog".into(),
13896            wit: "wasi:keyvalue/store".into(),
13897            endpoint: None,
13898            subject: None,
13899            slot: Some(big),
13900        });
13901        s.validate().unwrap();
13902    }
13903
13904    #[test]
13905    fn store_contrato_slot_accepts_canonical_forms() {
13906        // Positive-set sweep: every canonical kv slot template the
13907        // substrate-side `is_wasi_keyvalue_slot` predicate accepts
13908        // (single-token identifiers, path-namespaced `$`-templates,
13909        // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
13910        // snake_case / kebab-case / MixedCase tokens, digit-bearing
13911        // tokens, percent-encoded fragments) must remain valid
13912        // contrato slots too. Drift between this list and the
13913        // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
13914        // surfaces at the shared predicate — one source of truth.
13915        // Uses a fresh `(payment, catalog)` edge so none of the swept
13916        // slots collide with the pre-existing entries in
13917        // `three_member_spec`.
13918        for slot in [
13919            "checkout",
13920            "checkout/$orderId",
13921            "users:{tenant}/{id}",
13922            "session.<sid>",
13923            "session.tokens.<sid>",
13924            "snake_case_key",
13925            "kebab-case-key",
13926            "MixedCase",
13927            "shard0",
13928            "v2/key",
13929            "users/caf%C3%A9",
13930        ] {
13931            let mut s = three_member_spec();
13932            s.contratos.push(WitContract {
13933                de: "payment".into(),
13934                para: "catalog".into(),
13935                wit: "wasi:keyvalue/store".into(),
13936                endpoint: None,
13937                subject: None,
13938                slot: Some(slot.into()),
13939            });
13940            s.validate()
13941                .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
13942        }
13943    }
13944
13945    #[test]
13946    fn contrato_slot_empty_takes_precedence_over_invalid() {
13947        // Ordering pin: `ContratoSlotEmpty` is the more self-locating
13948        // diagnostic on `""` and must lead — the value-shape gate is
13949        // only reached after the empty-check fires. Mirrors
13950        // `contrato_subject_empty_takes_precedence_over_invalid` and
13951        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
13952        // the peer payload axes.
13953        let mut s = three_member_spec();
13954        s.contratos.push(WitContract {
13955            de: "payment".into(),
13956            para: "catalog".into(),
13957            wit: "wasi:keyvalue/store".into(),
13958            endpoint: None,
13959            subject: None,
13960            slot: Some(String::new()),
13961        });
13962        let err = s.validate().unwrap_err();
13963        assert!(
13964            matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
13965            "got {err:?}"
13966        );
13967    }
13968
13969    #[test]
13970    fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
13971        // Diagnostic-shape pin — the offending `:slot` + `:de` +
13972        // `:para` + a non-empty reason flow through verbatim so the
13973        // author can grep their caixa.lisp for the offending contrato
13974        // block and fix it in one edit. Same shape as
13975        // `contrato_subject_invalid_diagnostic_carries_offending_subject`
13976        // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
13977        // on the peer payload axes.
13978        let err = contrato_slot_err("check out/$order");
13979        match err {
13980            AplicacaoError::ContratoSlotInvalid {
13981                de,
13982                para,
13983                slot,
13984                reason,
13985            } => {
13986                assert_eq!(de, "payment");
13987                assert_eq!(para, "catalog");
13988                assert_eq!(slot, "check out/$order");
13989                assert!(!reason.is_empty(), "reason field must be non-empty");
13990            }
13991            other => panic!("expected ContratoSlotInvalid, got {other:?}"),
13992        }
13993    }
13994
13995    #[test]
13996    fn target_view_store_slot_passes_through_to_typed_view() {
13997        // The compounding theorem on the store axis: every
13998        // `WitTarget::Store { slot }` returned by `target()` carries a
13999        // kv-backend-accepted slot template. Renderers downstream of
14000        // `typed_view()` (the future per-Servico `:capabilities
14001        // wasi:keyvalue/store` axis emitter, the future `feira app
14002        // graph` view's slot labeller, the future kv-provider CR
14003        // materializer) can rely on this without re-checking — the
14004        // type system carries the proof. Mirrors
14005        // `target_view_pubsub_subject_passes_through_to_typed_view` on
14006        // the peer payload axis.
14007        let store = WitContract {
14008            de: "a".into(),
14009            para: "b".into(),
14010            wit: "wasi:keyvalue/store".into(),
14011            endpoint: None,
14012            subject: None,
14013            slot: Some("checkout/$orderId".into()),
14014        };
14015        match store.target().unwrap() {
14016            WitTarget::Store { slot } => {
14017                assert_eq!(slot, "checkout/$orderId");
14018            }
14019            other => panic!("expected Store, got {other:?}"),
14020        }
14021    }
14022
14023    #[test]
14024    fn rejects_self_loop_in_synchronous_contratos() {
14025        // A synchronous self-edge (`cart → cart` over HTTP) is now
14026        // rejected by the dedicated `ContratoSelfLoop` gate — a precise
14027        // "this edge is degenerate" diagnostic — rather than incidentally
14028        // by the cycle detector framing it as a `["cart", "cart"]`
14029        // multi-node deadlock.
14030        let mut s = three_member_spec();
14031        s.contratos.push(contract_http("cart", "cart", "/loop"));
14032        let err = s.validate().unwrap_err();
14033        match err {
14034            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
14035                assert_eq!(caixa, "cart");
14036                assert_eq!(wit, "wasi:http/proxy");
14037            }
14038            other => panic!("expected ContratoSelfLoop, got {other:?}"),
14039        }
14040    }
14041
14042    #[test]
14043    fn rejects_self_loop_in_pubsub_contratos() {
14044        // The cycle detector excludes pub-sub edges (acyclic by
14045        // construction), so before the explicit gate a `nats:pub-sub`
14046        // self-edge silently validated and rendered a self-allow CNP.
14047        // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
14048        let mut s = three_member_spec();
14049        s.contratos.push(WitContract {
14050            de: "payment".into(),
14051            para: "payment".into(),
14052            wit: "nats:pub-sub".into(),
14053            endpoint: None,
14054            subject: Some("rio.events.payment".into()),
14055            slot: None,
14056        });
14057        let err = s.validate().unwrap_err();
14058        match err {
14059            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
14060                assert_eq!(caixa, "payment");
14061                assert_eq!(wit, "nats:pub-sub");
14062            }
14063            other => panic!("expected ContratoSelfLoop, got {other:?}"),
14064        }
14065    }
14066
14067    #[test]
14068    fn self_loop_fires_before_payload_shape_check() {
14069        // The structural "this edge can't exist" error precedes the
14070        // narrower payload-shape diagnostics: a self-edge carrying an
14071        // otherwise-malformed endpoint still reports ContratoSelfLoop,
14072        // not ContratoEndpointInvalid.
14073        let mut s = three_member_spec();
14074        s.contratos.push(WitContract {
14075            de: "cart".into(),
14076            para: "cart".into(),
14077            wit: "wasi:http/proxy".into(),
14078            endpoint: Some("not-absolute".into()),
14079            subject: None,
14080            slot: None,
14081        });
14082        match s.validate().unwrap_err() {
14083            AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
14084            other => panic!("expected ContratoSelfLoop, got {other:?}"),
14085        }
14086    }
14087
14088    #[test]
14089    fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
14090        // A self-edge naming a non-member reports the more fundamental
14091        // ContratoMemberMissing first (the member doesn't exist), so the
14092        // self-loop gate is reached only once both endpoints resolve.
14093        let mut s = three_member_spec();
14094        s.contratos.push(contract_http("ghost", "ghost", "/loop"));
14095        match s.validate().unwrap_err() {
14096            AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
14097            other => panic!("expected ContratoMemberMissing, got {other:?}"),
14098        }
14099    }
14100
14101    #[test]
14102    fn rejects_two_node_synchronous_cycle() {
14103        let mut s = three_member_spec();
14104        // existing edges: cart → catalog, cart → payment
14105        // adding catalog → cart closes a 2-cycle on the HTTP subgraph
14106        s.contratos
14107            .push(contract_http("catalog", "cart", "/refresh"));
14108        let err = s.validate().unwrap_err();
14109        match err {
14110            AplicacaoError::ContratoCycle { cycle } => {
14111                // Cycle traversal should mention both endpoints, with
14112                // the back-edge target appearing as both first and last
14113                // element to close the loop.
14114                assert!(cycle.len() >= 3);
14115                assert_eq!(cycle.first(), cycle.last());
14116                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
14117                assert!(body.contains("cart"));
14118                assert!(body.contains("catalog"));
14119            }
14120            other => panic!("expected ContratoCycle, got {other:?}"),
14121        }
14122    }
14123
14124    #[test]
14125    fn rejects_three_node_synchronous_cycle() {
14126        let mut s = three_member_spec();
14127        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
14128        s.contratos = vec![
14129            contract_http("catalog", "cart", "/x"),
14130            contract_http("cart", "payment", "/y"),
14131            contract_http("payment", "catalog", "/z"),
14132        ];
14133        let err = s.validate().unwrap_err();
14134        match err {
14135            AplicacaoError::ContratoCycle { cycle } => {
14136                assert_eq!(cycle.first(), cycle.last());
14137                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
14138                assert_eq!(body.len(), 3);
14139                assert!(body.contains("cart"));
14140                assert!(body.contains("catalog"));
14141                assert!(body.contains("payment"));
14142            }
14143            other => panic!("expected ContratoCycle, got {other:?}"),
14144        }
14145    }
14146
14147    #[test]
14148    fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
14149        // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
14150        // "acyclic by construction" — so a cycle whose closing edge
14151        // is pub-sub should NOT raise ContratoCycle.
14152        let mut s = three_member_spec();
14153        s.contratos = vec![
14154            contract_http("catalog", "cart", "/x"),
14155            contract_http("cart", "payment", "/y"),
14156            // Closing edge is pub-sub — async; not a sync deadlock.
14157            WitContract {
14158                de: "payment".into(),
14159                para: "catalog".into(),
14160                wit: "nats:pub-sub".into(),
14161                endpoint: None,
14162                subject: Some("checkout.events.charge.completed".into()),
14163                slot: None,
14164            },
14165        ];
14166        s.validate().expect("pub-sub edge breaks the sync cycle");
14167    }
14168
14169    #[test]
14170    fn store_edge_counts_as_synchronous_for_cycle_detection() {
14171        // wasi:keyvalue/store is request/response; a cycle through one
14172        // *is* a sync deadlock, just like HTTP.
14173        let mut s = three_member_spec();
14174        s.contratos = vec![
14175            contract_http("catalog", "cart", "/x"),
14176            WitContract {
14177                de: "cart".into(),
14178                para: "catalog".into(),
14179                wit: "wasi:keyvalue/store".into(),
14180                endpoint: None,
14181                subject: None,
14182                slot: Some("session/$id".into()),
14183            },
14184        ];
14185        let err = s.validate().unwrap_err();
14186        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
14187    }
14188
14189    #[test]
14190    fn capability_edge_counts_as_synchronous_for_cycle_detection() {
14191        // Capability-only edges (unknown WIT shape, no payload) default
14192        // to synchronous — safer; authors with truly async capability
14193        // semantics can model them as pub-sub explicitly.
14194        let mut s = three_member_spec();
14195        s.contratos = vec![
14196            contract_http("catalog", "cart", "/x"),
14197            WitContract {
14198                de: "cart".into(),
14199                para: "catalog".into(),
14200                wit: "custom:exchange".into(),
14201                endpoint: None,
14202                subject: None,
14203                slot: None,
14204            },
14205        ];
14206        let err = s.validate().unwrap_err();
14207        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
14208    }
14209
14210    #[test]
14211    fn long_acyclic_chain_validates() {
14212        // A long sync chain (no back-edges) must validate even when
14213        // every node is reachable from the first.
14214        let mut s = three_member_spec();
14215        s.membros = vec![
14216            membro("a", "^0.1"),
14217            membro("b", "^0.1"),
14218            membro("c", "^0.1"),
14219            membro("d", "^0.1"),
14220            membro("e", "^0.1"),
14221        ];
14222        s.contratos = vec![
14223            contract_http("a", "b", "/1"),
14224            contract_http("b", "c", "/2"),
14225            contract_http("c", "d", "/3"),
14226            contract_http("d", "e", "/4"),
14227        ];
14228        s.entrada.as_mut().unwrap().para = "a".into();
14229        s.validate().unwrap();
14230    }
14231
14232    #[test]
14233    fn diamond_acyclic_validates() {
14234        // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
14235        let mut s = three_member_spec();
14236        s.membros = vec![
14237            membro("a", "^0.1"),
14238            membro("b", "^0.1"),
14239            membro("c", "^0.1"),
14240            membro("d", "^0.1"),
14241        ];
14242        s.contratos = vec![
14243            contract_http("a", "b", "/1"),
14244            contract_http("a", "c", "/2"),
14245            contract_http("b", "d", "/3"),
14246            contract_http("c", "d", "/4"),
14247        ];
14248        s.entrada.as_mut().unwrap().para = "a".into();
14249        s.validate().unwrap();
14250    }
14251
14252    // ── duplicate-`:contratos` build-error gate ──────────────────────────
14253
14254    #[test]
14255    fn rejects_duplicate_http_contrato() {
14256        // Fail-before-pass-after pin: the fixture's `cart → catalog`
14257        // HTTP edge appears once. Push an identical entry — same
14258        // (de, para, wit, endpoint) — and validate() must reject it.
14259        // Until this gate landed the typed surface accepted the
14260        // duplicate silently and caixa-mesh's `cilium_network_policies`
14261        // emitted two ``CiliumNetworkPolicy`` objects with identical
14262        // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
14263        // admission rejects on `kubectl apply` far from the source.
14264        let mut s = three_member_spec();
14265        s.contratos
14266            .push(contract_http("cart", "catalog", "/products/:id"));
14267        let err = s.validate().unwrap_err();
14268        assert!(
14269            matches!(
14270                err,
14271                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
14272                    if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
14273            ),
14274            "got {err:?}"
14275        );
14276    }
14277
14278    #[test]
14279    fn rejects_duplicate_pubsub_contrato() {
14280        // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
14281        // edges with identical (de, para, subject) are degenerate;
14282        // pin that the typed surface refuses both at validate time.
14283        let mut s = three_member_spec();
14284        let pubsub = WitContract {
14285            de: "payment".into(),
14286            para: "cart".into(),
14287            wit: "nats:pub-sub".into(),
14288            endpoint: None,
14289            subject: Some("checkout.events.charge.failed".into()),
14290            slot: None,
14291        };
14292        s.contratos.push(pubsub.clone());
14293        s.contratos.push(pubsub);
14294        let err = s.validate().unwrap_err();
14295        assert!(
14296            matches!(
14297                err,
14298                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
14299                    if de == "payment" && para == "cart" && wit == "nats:pub-sub"
14300            ),
14301            "got {err:?}"
14302        );
14303    }
14304
14305    #[test]
14306    fn rejects_duplicate_store_contrato() {
14307        // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
14308        // edges with identical (de, para, slot) collapse to one mesh-
14309        // policy edge; pin the build error.
14310        let mut s = three_member_spec();
14311        let store = WitContract {
14312            de: "cart".into(),
14313            para: "payment".into(),
14314            wit: "wasi:keyvalue/store".into(),
14315            endpoint: None,
14316            subject: None,
14317            slot: Some("checkout/$orderId".into()),
14318        };
14319        // Drop the conflicting HTTP `cart → payment` edge from the
14320        // fixture so the duplicate-store pair is the only one
14321        // distinguishable on this pair.
14322        s.contratos
14323            .retain(|c| !(c.de == "cart" && c.para == "payment"));
14324        s.contratos.push(store.clone());
14325        s.contratos.push(store);
14326        let err = s.validate().unwrap_err();
14327        assert!(
14328            matches!(
14329                err,
14330                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
14331                    if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
14332            ),
14333            "got {err:?}"
14334        );
14335    }
14336
14337    #[test]
14338    fn rejects_duplicate_capability_contrato() {
14339        // Same gate on the pure-capability axis (no payload selector).
14340        // Two contracts with identical (de, para, wit) and no
14341        // endpoint/subject/slot are duplicate edges; pin so a future
14342        // `target_label` change can't accidentally collapse the
14343        // capability arm into a None-shaped key that compares equal
14344        // to a populated one.
14345        let mut s = three_member_spec();
14346        let capability = WitContract {
14347            de: "cart".into(),
14348            para: "catalog".into(),
14349            wit: "pleme:cap/audit".into(),
14350            endpoint: None,
14351            subject: None,
14352            slot: None,
14353        };
14354        s.contratos.push(capability.clone());
14355        s.contratos.push(capability);
14356        let err = s.validate().unwrap_err();
14357        match err {
14358            AplicacaoError::ContratoDuplicate {
14359                de,
14360                para,
14361                wit,
14362                target,
14363            } => {
14364                assert_eq!(de, "cart");
14365                assert_eq!(para, "catalog");
14366                assert_eq!(wit, "pleme:cap/audit");
14367                assert!(
14368                    target.contains("capability"),
14369                    "capability-edge duplicate diagnostic must surface the \
14370                     no-payload shape (got target = {target:?})"
14371                );
14372            }
14373            other => panic!("expected ContratoDuplicate, got {other:?}"),
14374        }
14375    }
14376
14377    #[test]
14378    fn accepts_distinct_http_paths_between_same_pair() {
14379        // Negative pin: two HTTP contracts cart → catalog at distinct
14380        // endpoints (`/products/:id` and `/search`) are *not*
14381        // duplicates — they're distinct typed edges differing on the
14382        // payload axis. The duplicate-gate must not over-match here,
14383        // since the cart-calls-catalog-on-multiple-paths shape is the
14384        // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
14385        // example: cart calls catalog at /products/:id, payment at
14386        // /charge — same shape extends to two paths on one para).
14387        let mut s = three_member_spec();
14388        s.contratos
14389            .push(contract_http("cart", "catalog", "/search"));
14390        s.validate()
14391            .expect("distinct endpoints between same (de, para) must validate");
14392    }
14393
14394    #[test]
14395    fn accepts_same_endpoint_on_different_pairs() {
14396        // Negative pin: the same `/charge` endpoint reused on two
14397        // different (de, para) pairs is two distinct edges, not a
14398        // duplicate. Pinning this shape so the gate's identity key
14399        // includes both `de` and `para` (not just `(wit, endpoint)`).
14400        let mut s = three_member_spec();
14401        s.contratos
14402            .push(contract_http("payment", "catalog", "/charge"));
14403        s.validate()
14404            .expect("same endpoint reused on distinct (de, para) must validate");
14405    }
14406
14407    #[test]
14408    fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
14409        // Pin the diagnostic shape: the duplicate-edge error names
14410        // *which* target field carried the conflict, so the author
14411        // doesn't have to re-grep the source caixa.lisp to find it.
14412        // Same self-locating diagnostic discipline as
14413        // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
14414        let mut s = three_member_spec();
14415        s.contratos
14416            .push(contract_http("cart", "catalog", "/products/:id"));
14417        let err = s.validate().unwrap_err();
14418        let msg = format!("{err}");
14419        assert!(
14420            msg.contains("\"/products/:id\""),
14421            "duplicate-contrato diagnostic must name the offending \
14422             :endpoint payload (got: {msg:?})"
14423        );
14424        assert!(
14425            msg.contains("cart") && msg.contains("catalog"),
14426            "diagnostic must name both endpoints of the duplicate edge \
14427             (got: {msg:?})"
14428        );
14429    }
14430
14431    #[test]
14432    fn duplicate_contrato_gate_runs_after_membership_check() {
14433        // Order pin: a duplicate contract whose `:de` is *also* not in
14434        // `:membros` surfaces the membership error first — the
14435        // missing-member diagnostic is more locating than the
14436        // duplicate-edge one (the author has to fix the membership
14437        // before the duplicate is meaningful). Same ordering
14438        // discipline as `membros_validation_runs_before_contratos_membership_check`.
14439        let mut s = three_member_spec();
14440        s.contratos.push(contract_http("phantom", "catalog", "/x"));
14441        s.contratos.push(contract_http("phantom", "catalog", "/x"));
14442        let err = s.validate().unwrap_err();
14443        assert!(
14444            matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
14445            "membership-missing must fire before duplicate-edge (got {err:?})"
14446        );
14447    }
14448
14449    #[test]
14450    fn duplicate_contrato_gate_runs_after_target_shape_check() {
14451        // Order pin: a contract with a malformed target (e.g. an HTTP
14452        // wit world with an empty :endpoint) surfaces the target-shape
14453        // error first, not the duplicate one. Even when two such
14454        // malformed entries are identical, the per-contract `target()`
14455        // check fires inside the loop *before* the duplicate-key
14456        // insert, so the diagnostic remains the most-locating one.
14457        let mut s = three_member_spec();
14458        let malformed = WitContract {
14459            de: "cart".into(),
14460            para: "catalog".into(),
14461            wit: "wasi:http/proxy".into(),
14462            endpoint: Some(String::new()),
14463            subject: None,
14464            slot: None,
14465        };
14466        s.contratos.push(malformed.clone());
14467        s.contratos.push(malformed);
14468        let err = s.validate().unwrap_err();
14469        assert!(
14470            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
14471            "endpoint-empty must fire before duplicate-edge (got {err:?})"
14472        );
14473    }
14474
14475    #[test]
14476    fn wit_target_label_pins_per_variant_format() {
14477        // Label format is the single source of truth every duplicate-
14478        // `:contratos` diagnostic + every future `feira app graph`
14479        // consumer routes through. Pin the shape per variant so a
14480        // future edit to `WitTarget::label` (e.g. a JSON emitter that
14481        // strips the leading `:`, or a rename from `endpoint` →
14482        // `path`) surfaces as a red-red test rather than as a silent
14483        // downstream diagnostic drift. Together with the exhaustive
14484        // `match` on `WitTarget` inside `label()`, adding a future
14485        // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
14486        // peer, per-edge WIT registry variants) is a compile error at
14487        // the label site — not a fall-through into the `Capability`
14488        // "no payload" default the prior raw-field-probe helper
14489        // silently landed on.
14490        assert_eq!(
14491            WitTarget::Http {
14492                endpoint: "/charge",
14493            }
14494            .label(),
14495            "\
14496:endpoint \"/charge\""
14497        );
14498        assert_eq!(
14499            WitTarget::PubSub {
14500                subject: "events.checkout.paid",
14501            }
14502            .label(),
14503            "\
14504:subject \"events.checkout.paid\""
14505        );
14506        assert_eq!(
14507            WitTarget::Store {
14508                slot: "checkout/$order",
14509            }
14510            .label(),
14511            "\
14512:slot \"checkout/$order\""
14513        );
14514        assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
14515        // Capability-arm label routes through the lifted
14516        // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
14517        // declaration per arm, next to the variant" discipline the
14518        // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
14519        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
14520        // consts already carry extends to the payload-less arm; the
14521        // byte-string equality pin below plus this label-routes-
14522        // through-the-const pin make a future rebrand on either the
14523        // const declaration or the `label()` template a build error
14524        // here rather than a downstream consumer surprise.
14525        assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
14526        assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
14527    }
14528
14529    #[test]
14530    fn wit_target_display_routes_through_label_helper() {
14531        // Fail-before-pass-after pin on the fourth (and only remaining)
14532        // typed-shape-discriminator axis to converge onto the
14533        // three-path-convergence discipline the sibling M3
14534        // [`PlacementStrategy`] (0a2f653) and M2
14535        // [`crate::supervisor::RestartStrategy`] /
14536        // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
14537        // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
14538        // through [`WitTarget::label`], so every consumer reaching for
14539        // `format!("{v}")` on a typed payload target lands on the same
14540        // stable author-facing byte-string [`WitTarget::label`] returns
14541        // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
14542        // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
14543        // `:contratos` gate seeds via [`WitTarget::label`] at
14544        // aplicacao.rs:5491 already threads through.
14545        //
14546        // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
14547        // through to the `Debug` derive's structural output
14548        // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
14549        // rather than the [`WitTarget::label`] helper's stable byte-
14550        // string (`:endpoint "/charge"` — the author-facing `:contratos`
14551        // keyword form). Every future consumer that reaches for
14552        // `format!("{target}")` — the canonical shape every user-facing
14553        // pretty-print site on the sibling typed-enum axes
14554        // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
14555        // [`crate::supervisor::RestartPolicy`]) already uses — would
14556        // silently land under a different byte-string than the
14557        // [`WitTarget::label`] callers that the duplicate-`:contratos`
14558        // diagnostic already threads through, with the mismatch
14559        // surfacing as a downstream diagnostic / graph / audit line
14560        // reading one spelling while the substrate's own gate emitted
14561        // another.
14562        //
14563        // Pin the routing here so a future
14564        // `impl std::fmt::Display for WitTarget<'_>` reimplementation
14565        // that hand-rolls the per-arm formatting instead of delegating
14566        // to [`WitTarget::label`] fails at caixa-core build time.
14567        for variant in [
14568            WitTarget::Http {
14569                endpoint: "/charge",
14570            },
14571            WitTarget::PubSub {
14572                subject: "events.checkout.paid",
14573            },
14574            WitTarget::Store {
14575                slot: "checkout/$order",
14576            },
14577            WitTarget::Capability,
14578        ] {
14579            assert_eq!(
14580                variant.to_string(),
14581                variant.label(),
14582                "WitTarget::{variant:?} Display must route through \
14583                 WitTarget::label (single source of truth: the lifted \
14584                 payload_pair 4-arm dispatch the label helper already \
14585                 threads through)"
14586            );
14587        }
14588    }
14589
14590    #[test]
14591    fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
14592        // Consumer-side pin on the three-path convergence:
14593        // [`std::fmt::Display`] agrees byte-for-byte with the
14594        // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
14595        // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
14596        // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
14597        // Pre-lift the two paths were structurally independent — the
14598        // substrate-side gate reached for `target_view.label()` while a
14599        // future downstream diagnostic / graph / audit line reaching
14600        // for `format!("{target}")` would silently land on the `Debug`
14601        // derive's structural output. Pin the two paths byte-for-byte
14602        // here so any future variant addition (M4 `Rest`/`Grpc` split
14603        // of [`WitTarget::Http`], `Queue`-shaped peer of
14604        // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
14605        // match error at [`WitTarget::payload_pair`] rather than a
14606        // silent per-consumer dispatch miss.
14607        for variant in [
14608            WitTarget::Http {
14609                endpoint: "/charge",
14610            },
14611            WitTarget::PubSub {
14612                subject: "events.checkout.paid",
14613            },
14614            WitTarget::Store {
14615                slot: "checkout/$order",
14616            },
14617            WitTarget::Capability,
14618        ] {
14619            assert_eq!(
14620                format!("{variant}"),
14621                variant.label(),
14622                "WitTarget::{variant:?} Display byte-string must match \
14623                 the AplicacaoError::ContratoDuplicate `target:` carrier \
14624                 the AplicacaoSpec::validate duplicate-`:contratos` gate \
14625                 seeds via WitTarget::label — three-path convergence: \
14626                 Display + label + payload_pair all resolve to the same \
14627                 per-arm byte-string"
14628            );
14629        }
14630    }
14631
14632    #[test]
14633    fn wit_target_payload_pair_pins_per_variant() {
14634        // Pin the per-arm `(field-name, payload)` pair single-sourced
14635        // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
14636        // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
14637        // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
14638        // and [`WitTarget::field_name`] (returns the first component)
14639        // route through. Until this lift landed [`WitTarget::label`]
14640        // dispatched on the same three arms with a per-arm
14641        // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
14642        // paired [`WitTarget::HTTP_FIELD_NAME`] /
14643        // [`WitTarget::PUBSUB_FIELD_NAME`] /
14644        // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
14645        // canonical "same shape, written N times" duplication
14646        // THEORY.md §I.3.5 promotes to a build-time concern. A future
14647        // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
14648        // [`WitTarget::Http`], `Queue`-shaped peer of
14649        // [`WitTarget::Store`]) is one match-arm edit at
14650        // [`WitTarget::payload_pair`], visible here as a compile-time
14651        // exhaustiveness error on both this pin and the label-format
14652        // pin above.
14653        assert_eq!(
14654            WitTarget::Http {
14655                endpoint: "/charge"
14656            }
14657            .payload_pair(),
14658            Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
14659        );
14660        assert_eq!(
14661            WitTarget::PubSub {
14662                subject: "events.x",
14663            }
14664            .payload_pair(),
14665            Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
14666        );
14667        assert_eq!(
14668            WitTarget::Store {
14669                slot: "checkout/$order",
14670            }
14671            .payload_pair(),
14672            Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
14673        );
14674        assert_eq!(WitTarget::Capability.payload_pair(), None);
14675    }
14676
14677    #[test]
14678    fn wit_target_field_name_pins_per_variant() {
14679        // Pin the per-arm author-facing `:contratos` payload field
14680        // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
14681        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
14682        // + returned by [`WitTarget::field_name`]. Every downstream
14683        // consumer (the [`WitContract::target`] gate's `expected:`
14684        // scalar, the [`WitTarget::label`] template's keyword prefix,
14685        // the `feira app graph` verb's `endpoint=…` prefix) routes
14686        // through the same three peer consts, so a rename on the
14687        // author-surface `(defcaixa … :contratos ((:de … :para …
14688        // :wit … :endpoint …)))` field lands in exactly one place.
14689        assert_eq!(
14690            WitTarget::Http {
14691                endpoint: "/charge"
14692            }
14693            .field_name(),
14694            Some(WitTarget::HTTP_FIELD_NAME),
14695        );
14696        assert_eq!(
14697            WitTarget::PubSub {
14698                subject: "events.x",
14699            }
14700            .field_name(),
14701            Some(WitTarget::PUBSUB_FIELD_NAME),
14702        );
14703        assert_eq!(
14704            WitTarget::Store {
14705                slot: "checkout/$order",
14706            }
14707            .field_name(),
14708            Some(WitTarget::STORE_FIELD_NAME),
14709        );
14710        // Capability arm carries no payload field — the diagnostic
14711        // never reports `expected: "capability"` because the gate's
14712        // Capability arm accepts no payload at all (it fires the
14713        // "expected: none" WrongTarget error instead), so the field-
14714        // name method returns None here rather than a placeholder.
14715        assert_eq!(WitTarget::Capability.field_name(), None);
14716
14717        // Peer const scalar values pinned so a rename on either side
14718        // (author-surface field name in the `(defcaixa …)` DSL, or
14719        // the diagnostic's `expected:` scalar) can't drift without
14720        // failing here first.
14721        assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
14722        assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
14723        assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
14724    }
14725
14726    #[test]
14727    fn wit_target_payload_pins_per_variant() {
14728        // Pin the per-arm payload scalar single-sourced onto the
14729        // [`WitTarget::payload_pair`] 4-arm dispatch and surfaced through
14730        // [`WitTarget::payload`] — the peer per-half projection to
14731        // [`WitTarget::field_name`] on the paired sub-selector axis. The
14732        // three payload-carrying arms round-trip their author-declared
14733        // scalar verbatim (`Http` → `Some("/charge")`, `PubSub` →
14734        // `Some("events.x")`, `Store` → `Some("checkout/$order")`) and
14735        // the payload-less [`WitTarget::Capability`] arm returns `None`.
14736        // Same shape as the sibling `wit_target_field_name_pins_per_variant`
14737        // (c6ec2af) pin on the Component-0 projection axis, extended
14738        // onto the Component-1 projection axis so both per-half readers
14739        // on the paired dispatch carry their own byte-shape pin.
14740        assert_eq!(
14741            WitTarget::Http {
14742                endpoint: "/charge",
14743            }
14744            .payload(),
14745            Some("/charge"),
14746        );
14747        assert_eq!(
14748            WitTarget::PubSub {
14749                subject: "events.x",
14750            }
14751            .payload(),
14752            Some("events.x"),
14753        );
14754        assert_eq!(
14755            WitTarget::Store {
14756                slot: "checkout/$order",
14757            }
14758            .payload(),
14759            Some("checkout/$order"),
14760        );
14761        assert_eq!(WitTarget::Capability.payload(), None);
14762    }
14763
14764    #[test]
14765    fn wit_target_payload_matches_payload_pair_second_component_per_variant() {
14766        // Per-variant equivalence pin: for every arm of [`WitTarget`],
14767        // `.payload()` equals `.payload_pair().map(|(_, p)| p)`
14768        // byte-for-byte. Guards the drift surface where a future refactor
14769        // that split one accessor off the shared match onto its own
14770        // dispatch — a well-meaning "inline the pair back into per-half
14771        // fields for one crate-internal caller who only wanted one half"
14772        // or a scratch `impl` shadowing the derived projection — would
14773        // silently desynchronize [`WitTarget::payload`] from the
14774        // authoritative [`WitTarget::payload_pair`] dispatch, and every
14775        // downstream consumer that thinks "the payload half of the pair"
14776        // would drift from the diagnostic / graph consumers reading the
14777        // same match through [`WitTarget::label`] / [`WitTarget::graph_label`].
14778        // Sibling to the peer [`caixa_flux::GitRefSpec`] `ref_value`
14779        // per-half projection pin (`gitrefspec_ref_pair_projects_
14780        // ref_field_name_and_ref_value_per_variant`, 655a1c0) on the
14781        // FluxCD source-controller `spec.ref.<field>` axis — same "one
14782        // paired dispatch, both per-half projections agree byte-for-
14783        // byte" discipline extended onto the M3 `:contratos` payload-
14784        // arm surface.
14785        for variant in [
14786            WitTarget::Http {
14787                endpoint: "/charge",
14788            },
14789            WitTarget::PubSub {
14790                subject: "events.checkout.paid",
14791            },
14792            WitTarget::Store {
14793                slot: "checkout/$order",
14794            },
14795            WitTarget::Capability,
14796        ] {
14797            let via_projection = variant.payload();
14798            let via_pair = variant.payload_pair().map(|(_, p)| p);
14799            assert_eq!(
14800                via_projection, via_pair,
14801                "WitTarget::{variant:?} payload() must equal \
14802                 payload_pair().map(|(_, p)| p) byte-for-byte — a \
14803                 regression that splits the two per-half projections off \
14804                 their shared match would silently desynchronize the \
14805                 payload accessor from the paired dispatch every \
14806                 diagnostic / graph consumer reads through",
14807            );
14808        }
14809    }
14810
14811    #[test]
14812    fn wit_target_http_endpoint_pins_per_variant() {
14813        // Pin the per-arm HTTP-endpoint scalar single-sourced onto the
14814        // [`WitTarget::http_endpoint`] 2-arm dispatch — the
14815        // substrate-primitive per-arm post-projection accessor every
14816        // L7-HTTP-facing consumer routes through, sibling to the peer
14817        // WitContract pre-projection [`WitContract::endpoint`] (7020470)
14818        // scalar accessor on the raw-field axis. The [`WitTarget::Http`]
14819        // arm round-trips its author-declared endpoint verbatim as
14820        // `Some("/charge")`; the three sibling arms
14821        // ([`WitTarget::PubSub`] / [`WitTarget::Store`] /
14822        // [`WitTarget::Capability`]) each return `None` because they
14823        // carry no HTTP endpoint by definition. Same fail-before-pass-
14824        // after per-variant discipline as the sibling
14825        // `wit_target_payload_pins_per_variant` (5d6dc92) /
14826        // `wit_target_field_name_pins_per_variant` (c6ec2af) /
14827        // `wit_target_payload_pair_pins_per_variant` (6788ed6) pins on
14828        // the peer pan-arm / per-half projection axes — extended onto
14829        // the per-arm HTTP-shape post-projection axis so a future
14830        // [`WitTarget`] variant addition (a `Rest`/`Grpc` split of
14831        // [`WitTarget::Http`], a `Queue`-shaped peer of
14832        // [`WitTarget::Store`]) trips a compile-time exhaustiveness
14833        // error on the sibling [`WitTarget::http_endpoint`] match arms
14834        // whose payload the L7-HTTP-shape accept-set is meant to bound.
14835        assert_eq!(
14836            WitTarget::Http {
14837                endpoint: "/charge",
14838            }
14839            .http_endpoint(),
14840            Some("/charge"),
14841        );
14842        assert_eq!(
14843            WitTarget::PubSub {
14844                subject: "events.checkout.paid",
14845            }
14846            .http_endpoint(),
14847            None,
14848        );
14849        assert_eq!(
14850            WitTarget::Store {
14851                slot: "checkout/$order",
14852            }
14853            .http_endpoint(),
14854            None,
14855        );
14856        assert_eq!(WitTarget::Capability.http_endpoint(), None);
14857    }
14858
14859    #[test]
14860    fn wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere() {
14861        // Per-variant coherence pin: for every arm of [`WitTarget`],
14862        // `.http_endpoint()` equals `.payload()` on the [`WitTarget::Http`]
14863        // arm (both project the same author-declared request-path
14864        // scalar), and returns `None` on every sibling arm regardless of
14865        // whether [`WitTarget::payload`] itself returns `Some` (PubSub /
14866        // Store carry their own payload the pan-arm accessor surfaces,
14867        // but that payload is not an HTTP endpoint — the per-arm
14868        // accessor must not leak it through the HTTP-shape channel).
14869        // Guards the drift surface where a future refactor that
14870        // conflated the per-arm HTTP projection with the pan-arm
14871        // [`WitTarget::payload`] projection — a well-meaning "one
14872        // accessor for the L7 branch, one for the graph" collapse that
14873        // routes both through the same 4-arm dispatch — would silently
14874        // widen the L7-HTTP-shape accept-set onto pub-sub / store
14875        // payloads at the caixa-mesh L7 emit branch, admitting a
14876        // `nats:pub-sub` edge's `:subject` as a Cilium L7 HTTP `path:`
14877        // rule with the operator-side apply-time symptom (Cilium's
14878        // eBPF data-plane rejects every ingress edge whose L7 filter
14879        // doesn't match the wire-format HTTP request line) far from
14880        // the source refactor. Sibling to the peer
14881        // `wit_target_payload_matches_payload_pair_second_component_
14882        // per_variant` (5d6dc92) coherence pin on the pan-arm axis —
14883        // extended onto the per-arm HTTP specialization axis so both
14884        // the pan-arm and the per-arm projections carry their own
14885        // byte-shape coherence witness against the substrate's typed
14886        // arm-family accept-set.
14887        for variant in [
14888            WitTarget::Http {
14889                endpoint: "/charge",
14890            },
14891            WitTarget::PubSub {
14892                subject: "events.checkout.paid",
14893            },
14894            WitTarget::Store {
14895                slot: "checkout/$order",
14896            },
14897            WitTarget::Capability,
14898        ] {
14899            let per_arm = variant.http_endpoint();
14900            let pan_arm = variant.payload();
14901            if variant.is_http() {
14902                assert_eq!(
14903                    per_arm, pan_arm,
14904                    "WitTarget::{variant:?} http_endpoint() must equal \
14905                     payload() on the Http arm — a per-arm-vs-pan-arm \
14906                     split would silently drift the L7 emit branch's \
14907                     path-scalar source from the graph verb's payload \
14908                     scalar source",
14909                );
14910            } else {
14911                assert_eq!(
14912                    per_arm, None,
14913                    "WitTarget::{variant:?} http_endpoint() must return \
14914                     None on non-Http arms — a leak that surfaced a \
14915                     pub-sub :subject or a key/value :slot through the \
14916                     HTTP-endpoint accessor would silently widen the \
14917                     Cilium L7 HTTP `path:` rule accept-set onto \
14918                     protocol shapes Cilium's eBPF data-plane can't \
14919                     introspect",
14920                );
14921            }
14922        }
14923    }
14924
14925    #[test]
14926    fn wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant() {
14927        // Per-variant coherence pin: for every arm of [`WitTarget`],
14928        // `.http_endpoint().is_some()` iff `.is_http()`. Guards the
14929        // drift surface where a future extension of the
14930        // [`WitTarget::http_endpoint`] accessor's accept-set (e.g. a
14931        // `Rest`/`Grpc` split of [`WitTarget::Http`] that widened the
14932        // accessor to cover both peers) landed without a paired
14933        // extension of the [`gen_platform::IsVariant`]-derived
14934        // `is_http()` predicate's accept-set, or vice versa — a
14935        // regression that split the "which arms count as HTTP-shaped
14936        // for L7-path emission?" answer between two dispatch surfaces
14937        // the substrate ships. Sibling to the peer
14938        // `wit_target_field_name_pins_per_variant` (c6ec2af) discipline
14939        // on the paired dispatch axis — extended onto the per-arm
14940        // predicate-vs-accessor coherence axis so the gen-platform
14941        // IsVariant predicate and the substrate-lifted per-arm
14942        // accessor carry one shared answer to "is this the HTTP arm?".
14943        for variant in [
14944            WitTarget::Http {
14945                endpoint: "/charge",
14946            },
14947            WitTarget::PubSub {
14948                subject: "events.checkout.paid",
14949            },
14950            WitTarget::Store {
14951                slot: "checkout/$order",
14952            },
14953            WitTarget::Capability,
14954        ] {
14955            assert_eq!(
14956                variant.http_endpoint().is_some(),
14957                variant.is_http(),
14958                "WitTarget::{variant:?} http_endpoint().is_some() must \
14959                 equal is_http() — a drift would split the L7 emit \
14960                 branch's arm-set gate from the substrate-derived \
14961                 shape-discrimination predicate on the same axis",
14962            );
14963        }
14964    }
14965
14966    #[test]
14967    fn wit_target_pubsub_subject_pins_per_variant() {
14968        // Fail-before-pass-after pin: the substrate-canonical per-arm
14969        // pub-sub-subject scalar accessor [`WitTarget::pubsub_subject`]
14970        // is the single dispatch every future pub-sub-facing consumer
14971        // routes through, sibling to the peer [`WitContract::subject`]
14972        // (63e18a0) pre-projection scalar accessor on the raw-field
14973        // axis and to the peer [`WitTarget::http_endpoint`] (5d6dc92)
14974        // post-projection per-arm accessor on the sibling HTTP-shape
14975        // axis. The [`WitTarget::PubSub`] arm round-trips its
14976        // author-declared subject verbatim as
14977        // `Some("events.checkout.paid")`; the three sibling arms each
14978        // return `None` because they carry no NATS-shaped subject by
14979        // definition. Same fail-before-pass-after per-variant discipline
14980        // as the sibling `wit_target_http_endpoint_pins_per_variant`
14981        // pin on the peer per-arm axis — extended onto the per-arm
14982        // pub-sub-shape post-projection axis so a future [`WitTarget`]
14983        // variant addition (a `Rest`/`Grpc` split of [`WitTarget::Http`],
14984        // a `Queue`-shaped peer of [`WitTarget::Store`]) trips a
14985        // compile-time exhaustiveness error on the sibling
14986        // [`WitTarget::pubsub_subject`] match arms whose payload the
14987        // pub-sub-shape accept-set is meant to bound.
14988        assert_eq!(
14989            WitTarget::PubSub {
14990                subject: "events.checkout.paid",
14991            }
14992            .pubsub_subject(),
14993            Some("events.checkout.paid"),
14994        );
14995        assert_eq!(
14996            WitTarget::Http {
14997                endpoint: "/charge",
14998            }
14999            .pubsub_subject(),
15000            None,
15001        );
15002        assert_eq!(
15003            WitTarget::Store {
15004                slot: "checkout/$order",
15005            }
15006            .pubsub_subject(),
15007            None,
15008        );
15009        assert_eq!(WitTarget::Capability.pubsub_subject(), None);
15010    }
15011
15012    #[test]
15013    fn wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere() {
15014        // Per-variant coherence pin: for every arm of [`WitTarget`],
15015        // `.pubsub_subject()` equals `.payload()` on the
15016        // [`WitTarget::PubSub`] arm (both project the same
15017        // author-declared subject scalar), and returns `None` on every
15018        // sibling arm regardless of whether [`WitTarget::payload`]
15019        // itself returns `Some` (Http / Store carry their own payload
15020        // the pan-arm accessor surfaces, but that payload is not a
15021        // pub-sub subject — the per-arm accessor must not leak it
15022        // through the pub-sub-shape channel). Sibling to the peer
15023        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
15024        // coherence pin on the per-arm HTTP-shape axis — extended onto
15025        // the per-arm pub-sub specialization axis so both per-arm
15026        // projections carry their own byte-shape coherence witness
15027        // against the substrate's typed arm-family accept-set.
15028        for variant in [
15029            WitTarget::Http {
15030                endpoint: "/charge",
15031            },
15032            WitTarget::PubSub {
15033                subject: "events.checkout.paid",
15034            },
15035            WitTarget::Store {
15036                slot: "checkout/$order",
15037            },
15038            WitTarget::Capability,
15039        ] {
15040            let per_arm = variant.pubsub_subject();
15041            let pan_arm = variant.payload();
15042            if variant.is_pubsub() {
15043                assert_eq!(
15044                    per_arm, pan_arm,
15045                    "WitTarget::{variant:?} pubsub_subject() must equal \
15046                     payload() on the PubSub arm — a per-arm-vs-pan-arm \
15047                     split would silently drift the pub-sub-shape emit \
15048                     branch's subject-scalar source from the graph verb's \
15049                     payload scalar source",
15050                );
15051            } else {
15052                assert_eq!(
15053                    per_arm, None,
15054                    "WitTarget::{variant:?} pubsub_subject() must return \
15055                     None on non-PubSub arms — a leak that surfaced an \
15056                     HTTP :endpoint or a key/value :slot through the \
15057                     pub-sub-subject accessor would silently widen the \
15058                     downstream NATS-shape accept-set onto protocol \
15059                     shapes NATS servers can't route",
15060                );
15061            }
15062        }
15063    }
15064
15065    #[test]
15066    fn wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant() {
15067        // Per-variant coherence pin: for every arm of [`WitTarget`],
15068        // `.pubsub_subject().is_some()` iff `.is_pubsub()`. Guards the
15069        // drift surface where a future extension of the
15070        // [`WitTarget::pubsub_subject`] accessor's accept-set landed
15071        // without a paired extension of the [`gen_platform::IsVariant`]-
15072        // derived `is_pubsub()` predicate's accept-set, or vice versa
15073        // — a regression that split the "which arms count as pub-sub-
15074        // shaped for subject emission?" answer between two dispatch
15075        // surfaces the substrate ships. Sibling to the peer
15076        // `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
15077        // pin on the per-arm HTTP-shape axis — extended onto the
15078        // per-arm pub-sub predicate-vs-accessor coherence axis so the
15079        // gen-platform IsVariant predicate and the substrate-lifted
15080        // per-arm accessor carry one shared answer to "is this the
15081        // PubSub arm?".
15082        for variant in [
15083            WitTarget::Http {
15084                endpoint: "/charge",
15085            },
15086            WitTarget::PubSub {
15087                subject: "events.checkout.paid",
15088            },
15089            WitTarget::Store {
15090                slot: "checkout/$order",
15091            },
15092            WitTarget::Capability,
15093        ] {
15094            assert_eq!(
15095                variant.pubsub_subject().is_some(),
15096                variant.is_pubsub(),
15097                "WitTarget::{variant:?} pubsub_subject().is_some() must \
15098                 equal is_pubsub() — a drift would split the pub-sub \
15099                 emit branch's arm-set gate from the substrate-derived \
15100                 shape-discrimination predicate on the same axis",
15101            );
15102        }
15103    }
15104
15105    #[test]
15106    fn wit_target_store_slot_pins_per_variant() {
15107        // Fail-before-pass-after pin: the substrate-canonical per-arm
15108        // key/value-store-slot scalar accessor [`WitTarget::store_slot`]
15109        // is the single dispatch every future store-facing consumer
15110        // routes through, sibling to the peer [`WitContract::slot`]
15111        // pre-projection scalar accessor on the raw-field axis and to
15112        // the peer [`WitTarget::http_endpoint`] (5d6dc92) +
15113        // [`WitTarget::pubsub_subject`] post-projection per-arm
15114        // accessors on the sibling per-payload-arm axes. The
15115        // [`WitTarget::Store`] arm round-trips its author-declared
15116        // slot verbatim as `Some("checkout/$order")`; the three
15117        // sibling arms each return `None` because they carry no
15118        // WASI-key/value slot by definition. Same fail-before-pass-
15119        // after per-variant discipline as the sibling
15120        // `wit_target_http_endpoint_pins_per_variant` +
15121        // `wit_target_pubsub_subject_pins_per_variant` pins on the
15122        // peer per-arm axes — extended onto the per-arm store-shape
15123        // post-projection axis so a future [`WitTarget`] variant
15124        // addition trips a compile-time exhaustiveness error on the
15125        // sibling [`WitTarget::store_slot`] match arms whose payload
15126        // the store-shape accept-set is meant to bound.
15127        assert_eq!(
15128            WitTarget::Store {
15129                slot: "checkout/$order",
15130            }
15131            .store_slot(),
15132            Some("checkout/$order"),
15133        );
15134        assert_eq!(
15135            WitTarget::Http {
15136                endpoint: "/charge",
15137            }
15138            .store_slot(),
15139            None,
15140        );
15141        assert_eq!(
15142            WitTarget::PubSub {
15143                subject: "events.checkout.paid",
15144            }
15145            .store_slot(),
15146            None,
15147        );
15148        assert_eq!(WitTarget::Capability.store_slot(), None);
15149    }
15150
15151    #[test]
15152    fn wit_target_store_slot_matches_payload_on_store_arm_and_is_none_elsewhere() {
15153        // Per-variant coherence pin: for every arm of [`WitTarget`],
15154        // `.store_slot()` equals `.payload()` on the
15155        // [`WitTarget::Store`] arm (both project the same
15156        // author-declared slot scalar), and returns `None` on every
15157        // sibling arm regardless of whether [`WitTarget::payload`]
15158        // itself returns `Some`. Sibling to the peer
15159        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
15160        // and `wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere`
15161        // pins on the per-arm HTTP and PubSub axes — closes the
15162        // per-arm-vs-pan-arm byte-shape coherence trio across all
15163        // three payload arms.
15164        for variant in [
15165            WitTarget::Http {
15166                endpoint: "/charge",
15167            },
15168            WitTarget::PubSub {
15169                subject: "events.checkout.paid",
15170            },
15171            WitTarget::Store {
15172                slot: "checkout/$order",
15173            },
15174            WitTarget::Capability,
15175        ] {
15176            let per_arm = variant.store_slot();
15177            let pan_arm = variant.payload();
15178            if variant.is_store() {
15179                assert_eq!(
15180                    per_arm, pan_arm,
15181                    "WitTarget::{variant:?} store_slot() must equal \
15182                     payload() on the Store arm — a per-arm-vs-pan-arm \
15183                     split would silently drift the store-shape emit \
15184                     branch's slot-scalar source from the graph verb's \
15185                     payload scalar source",
15186                );
15187            } else {
15188                assert_eq!(
15189                    per_arm, None,
15190                    "WitTarget::{variant:?} store_slot() must return \
15191                     None on non-Store arms — a leak that surfaced an \
15192                     HTTP :endpoint or a NATS :subject through the \
15193                     key/value-slot accessor would silently widen the \
15194                     downstream WASI-key/value slot accept-set onto \
15195                     protocol shapes the kv backends can't route",
15196                );
15197            }
15198        }
15199    }
15200
15201    #[test]
15202    fn wit_target_store_slot_agrees_with_is_store_predicate_per_variant() {
15203        // Per-variant coherence pin: for every arm of [`WitTarget`],
15204        // `.store_slot().is_some()` iff `.is_store()`. Guards the
15205        // drift surface where a future extension of the
15206        // [`WitTarget::store_slot`] accessor's accept-set landed
15207        // without a paired extension of the [`gen_platform::IsVariant`]-
15208        // derived `is_store()` predicate's accept-set. Sibling to the
15209        // peer `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
15210        // and `wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant`
15211        // pins — closes the per-arm predicate-vs-accessor coherence
15212        // trio across all three payload arms so the gen-platform
15213        // IsVariant predicate and the substrate-lifted per-arm
15214        // accessor carry one shared answer to "is this the Store arm?".
15215        for variant in [
15216            WitTarget::Http {
15217                endpoint: "/charge",
15218            },
15219            WitTarget::PubSub {
15220                subject: "events.checkout.paid",
15221            },
15222            WitTarget::Store {
15223                slot: "checkout/$order",
15224            },
15225            WitTarget::Capability,
15226        ] {
15227            assert_eq!(
15228                variant.store_slot().is_some(),
15229                variant.is_store(),
15230                "WitTarget::{variant:?} store_slot().is_some() must \
15231                 equal is_store() — a drift would split the store-shape \
15232                 emit branch's arm-set gate from the substrate-derived \
15233                 shape-discrimination predicate on the same axis",
15234            );
15235        }
15236    }
15237
15238    #[test]
15239    fn wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set() {
15240        // Fail-before-pass-after cross-axis pin on the trio
15241        // (`http_endpoint`, `pubsub_subject`, `store_slot`): on every
15242        // payload-carrying arm of [`WitTarget`], exactly one per-arm
15243        // accessor returns `Some(payload)` and the two peers return
15244        // `None`; and on the payload-less [`WitTarget::Capability`]
15245        // arm, all three return `None`. Guards the drift surface where
15246        // a future extension of one per-arm accessor's accept-set (e.g.
15247        // a hypothetical `Rest`/`Grpc` split of [`WitTarget::Http`]
15248        // that widened `http_endpoint` to cover both peers without
15249        // narrowing the peer `pubsub_subject` / `store_slot` accept-
15250        // sets to keep the partition mutually exclusive) landed without
15251        // threading through the peer per-arm accessors — the resulting
15252        // silent overlap would land the same edge's payload on two
15253        // downstream per-shape emit branches at once, or leak a
15254        // pub-sub subject through the store-slot channel, at renderer
15255        // emit time far from the substrate primitive's arm-widening
15256        // commit. Peer of the sibling `wit_target_field_names_are_pairwise_distinct`
15257        // 3-way pin on the payload-field-name axis — extended onto the
15258        // per-arm-accessor payload-projection axis so the substrate-
15259        // owned partition invariant is load-bearing at every per-arm
15260        // consumer's read site.
15261        let payload_variants = [
15262            (
15263                WitTarget::Http {
15264                    endpoint: "/charge",
15265                },
15266                "http",
15267            ),
15268            (
15269                WitTarget::PubSub {
15270                    subject: "events.checkout.paid",
15271                },
15272                "pubsub",
15273            ),
15274            (
15275                WitTarget::Store {
15276                    slot: "checkout/$order",
15277                },
15278                "store",
15279            ),
15280        ];
15281        for (variant, own_arm_label) in payload_variants {
15282            let own_arm_hit = match own_arm_label {
15283                "http" => variant.is_http(),
15284                "pubsub" => variant.is_pubsub(),
15285                "store" => variant.is_store(),
15286                other => panic!("unknown own-arm label {other:?}"),
15287            };
15288            let per_arm_results = [
15289                ("http_endpoint", variant.http_endpoint()),
15290                ("pubsub_subject", variant.pubsub_subject()),
15291                ("store_slot", variant.store_slot()),
15292            ];
15293            let some_count = per_arm_results.iter().filter(|(_, v)| v.is_some()).count();
15294            assert_eq!(
15295                some_count, 1,
15296                "WitTarget::{variant:?} must land exactly one per-arm \
15297                 post-projection accessor's Some result — the trio \
15298                 (http_endpoint, pubsub_subject, store_slot) must \
15299                 partition the payload arm-set; got {per_arm_results:?}",
15300            );
15301            assert!(
15302                own_arm_hit,
15303                "WitTarget::{variant:?} own-arm gen-platform predicate \
15304                 must return true on its own arm — a partition failure \
15305                 upstream of this pin",
15306            );
15307            assert!(
15308                variant.payload().is_some(),
15309                "WitTarget::{variant:?} pan-arm payload() must return \
15310                 Some on every payload-carrying arm the trio partitions",
15311            );
15312        }
15313        // The payload-less Capability arm must return None on every
15314        // per-arm accessor — the partition's terminal-fallback shape.
15315        let cap = WitTarget::Capability;
15316        assert_eq!(cap.http_endpoint(), None);
15317        assert_eq!(cap.pubsub_subject(), None);
15318        assert_eq!(cap.store_slot(), None);
15319        assert_eq!(
15320            cap.payload(),
15321            None,
15322            "WitTarget::Capability pan-arm payload() must return None — \
15323             the trio's payload-less-arm coherence witness",
15324        );
15325    }
15326
15327    #[test]
15328    fn wit_target_field_names_are_pairwise_distinct() {
15329        // Distinctness pin: if any two of the three payload-field-name
15330        // scalars ever collapse (e.g. an accidental `endpoint` copy-
15331        // paste over the `subject` const), the [`WitContract::target`]
15332        // gate's diagnostic would point authors at the wrong field —
15333        // an "expected `:endpoint`" error on a pub-sub edge would
15334        // silently misroute the fix. Same cross-axis-distinctness
15335        // discipline as the peer M3 `:placement :estrategia` variant-
15336        // discriminator scalar-value pins (cc8f749) applied to the
15337        // payload-field-name axis.
15338        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
15339        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
15340        assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
15341    }
15342
15343    #[test]
15344    fn wit_target_graph_label_routes_through_payload_pair_on_payload_arms() {
15345        // Fail-before-pass-after pin: the graph-verb payload column's
15346        // per-arm `{field}={payload}` byte-string is derived through the
15347        // single [`WitTarget::payload_pair`] 4-arm dispatch on the three
15348        // payload-carrying arms, not through a hand-rolled per-arm match
15349        // that re-projects [`WitTarget::HTTP_FIELD_NAME`] /
15350        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
15351        // inline. A future variant addition — the M4-and-later per-edge
15352        // WIT registry may split [`WitTarget::Http`] into `Rest` / `Grpc`
15353        // peers, or extend [`WitTarget::Store`] with a `Queue`-shaped
15354        // peer — becomes one match-arm edit at [`WitTarget::payload_pair`],
15355        // and both [`WitTarget::label`] (duplicate-`:contratos`
15356        // diagnostic) and [`WitTarget::graph_label`] (`feira app graph`
15357        // payload column) pick up the new arm from the same dispatch.
15358        // Prior to this lift the graph verb open-coded the 4-arm match
15359        // in caixa-feira, so a variant addition would have to be threaded
15360        // through both projections in lockstep or the graph verb would
15361        // silently drop the new arm to `(capability-only)`.
15362        for variant in [
15363            WitTarget::Http {
15364                endpoint: "/charge",
15365            },
15366            WitTarget::PubSub {
15367                subject: "events.checkout.paid",
15368            },
15369            WitTarget::Store {
15370                slot: "checkout/$order",
15371            },
15372        ] {
15373            let (field, payload) = variant
15374                .payload_pair()
15375                .expect("payload arm must expose (field, payload)");
15376            assert_eq!(
15377                variant.graph_label(),
15378                format!("{field}={payload}"),
15379                "WitTarget::{variant:?} graph_label must route the \
15380                 `{{field}}={{payload}}` template through payload_pair — \
15381                 a regression to a hand-rolled per-arm match at the graph \
15382                 verb would silently disagree with a future variant \
15383                 addition landed only at payload_pair"
15384            );
15385        }
15386    }
15387
15388    #[test]
15389    fn wit_target_graph_label_returns_capability_graph_label_const_on_capability_arm() {
15390        // Fail-before-pass-after pin on the payload-less arm: the graph
15391        // verb's `(capability-only)` byte-string routes through the
15392        // lifted [`WitTarget::CAPABILITY_GRAPH_LABEL`] const on the
15393        // [`WitTarget::Capability`] arm, not through an inline
15394        // `.to_string()` literal at the caixa-feira `cmd::app::GraphArgs::run`
15395        // per-`:contratos` payload column. Peer of the sibling
15396        // [`wit_target_label_pins_per_variant_format`] Capability-arm
15397        // assertion on the [`WitTarget::CAPABILITY_LABEL`] const —
15398        // extended here onto the third payload-less-arm consumer axis
15399        // (graph verb, sibling to the duplicate-`:contratos` diagnostic
15400        // axis and the wrong-target diagnostic axis).
15401        assert_eq!(
15402            WitTarget::Capability.graph_label(),
15403            WitTarget::CAPABILITY_GRAPH_LABEL,
15404        );
15405        assert_eq!(WitTarget::CAPABILITY_GRAPH_LABEL, "(capability-only)");
15406    }
15407
15408    #[test]
15409    fn wit_target_capability_graph_label_distinct_from_capability_label() {
15410        // Cross-consumer-axis distinctness pin: the graph-verb
15411        // payload-column const [`WitTarget::CAPABILITY_GRAPH_LABEL`]
15412        // (`(capability-only)`) and the duplicate-`:contratos` diagnostic
15413        // label const [`WitTarget::CAPABILITY_LABEL`] (`(capability — no
15414        // payload)`) surface the payload-less arm on two distinct
15415        // consumer axes; a collapse (an accidental rebrand that lands
15416        // one spelling on both consts, a copy-paste that unifies them
15417        // "for consistency") would silently merge the two byte-strings
15418        // and lose the vocabulary distinction the graph verb's
15419        // compact-column form and the diagnostic's descriptive-clause
15420        // form each carry on purpose. Peer of the sibling 4-way
15421        // [`wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`]
15422        // pin on the `ContratoWrongTarget::expected` scalar-value axis —
15423        // extended here onto the cross-consumer-axis distinctness of the
15424        // two payload-less-arm consts.
15425        assert_ne!(
15426            WitTarget::CAPABILITY_GRAPH_LABEL,
15427            WitTarget::CAPABILITY_LABEL,
15428            "WitTarget::CAPABILITY_GRAPH_LABEL (graph-verb payload column) \
15429             and WitTarget::CAPABILITY_LABEL (duplicate-`:contratos` \
15430             diagnostic) must remain distinct — a collapse would silently \
15431             merge two consumer axes onto one spelling"
15432        );
15433    }
15434
15435    #[test]
15436    fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
15437        // 4-way distinctness pin extending the sibling
15438        // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
15439        // (which covers only the HTTP / PubSub / Store payload arms)
15440        // onto the fourth scalar the shared
15441        // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
15442        // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
15443        // (`"none"`), the payload-less Capability-arm rejection scalar.
15444        //
15445        // All four [`WitTarget::HTTP_FIELD_NAME`] /
15446        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
15447        // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
15448        // dispatch surface [`WitContract::target`] writes onto the
15449        // `ContratoWrongTarget::expected` field — the same `&'static
15450        // str` axis authors read as "this WIT world's shape admits
15451        // (only|not) `:<field>`". Pairwise-distinctness is the invariant
15452        // downstream consumers rely on: an `expected: "endpoint"`
15453        // diagnostic on a Capability-shaped edge tells the author to
15454        // add a `:endpoint "…"` slot to a WIT world that admits none,
15455        // silently misrouting the fix. Until this pin landed the three
15456        // payload-arm consts were distinctness-guarded by the sibling
15457        // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
15458        // scalar (d4f54f2) sat unguarded — a rebrand collision (the
15459        // author-facing vocabulary shift from `"none"` to `"endpoint"`
15460        // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
15461        // into per-shape peers) would have silently landed one
15462        // Capability-arm rejection on a payload-arm's `expected:` byte-
15463        // string and desynchronized the diagnostic from the author's
15464        // typed shape.
15465        //
15466        // Same 4-way pairwise-distinctness pin discipline as the peer
15467        // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
15468        // (cc8f749) applies on the sibling M3 closed-set typed-enum
15469        // scalar-value dispatch axis; extends the pin trajectory the
15470        // sibling `wit_target_field_names_are_pairwise_distinct`
15471        // 3-way pin opened to cover the last unguarded corner on the
15472        // `ContratoWrongTarget::expected` scalar-value axis.
15473        //
15474        // Fail-before-pass-after locally verified by mutating
15475        // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
15476        // — this pin fires as expected; restoring passes.
15477        let all = [
15478            WitTarget::HTTP_FIELD_NAME,
15479            WitTarget::PUBSUB_FIELD_NAME,
15480            WitTarget::STORE_FIELD_NAME,
15481            WitTarget::CAPABILITY_EXPECTED,
15482        ];
15483        for (i, a) in all.iter().enumerate() {
15484            for (j, b) in all.iter().enumerate() {
15485                if i != j {
15486                    assert_ne!(
15487                        a, b,
15488                        "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
15489                         STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
15490                         pairwise distinct — got duplicate {a:?} at indices \
15491                         {i} and {j}; all four scalars thread through the \
15492                         shared `AplicacaoError::ContratoWrongTarget::expected` \
15493                         &'static str axis, so a collapse silently misdirects \
15494                         the diagnostic on which typed shape the WIT world admits",
15495                    );
15496                }
15497            }
15498        }
15499    }
15500
15501    #[test]
15502    fn wit_target_is_variant_predicates_partition_the_arm_set() {
15503        // Fail-before-pass-after pin on the
15504        // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
15505        // each of the four variants exactly one of the generated
15506        // `is_http` / `is_pubsub` / `is_store` / `is_capability`
15507        // predicates returns `true` and the other three return
15508        // `false`. Prior to this derive the only production
15509        // arm-discriminator on [`WitTarget`] — the sync-cycle
15510        // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
15511        // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
15512        // the variant that expressed no compile-time link back to
15513        // the closed-set typed dispatch a future fifth
15514        // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
15515        // split of [`WitTarget::PubSub`] into shape-specific peers,
15516        // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
15517        // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
15518        // to thread through in lockstep or the DFS exclusion would
15519        // silently disagree with the peer diagnostic templates on
15520        // which arms carry sync-versus-async semantics. Peer of the
15521        // sibling [`crate::CaixaKind`] (f5bba80),
15522        // [`PlacementStrategy`] (766ec63),
15523        // [`crate::supervisor::RestartStrategy`],
15524        // [`crate::supervisor::RestartPolicy`], and
15525        // [`crate::upgrade::UpgradeInstruction`] (915a934)
15526        // `IsVariant` derives on the sibling closed-set typed-enum
15527        // discriminator axes — extends the same one-typed-dispatch-
15528        // per-variant discipline onto the last unlifted closed-set
15529        // typed-enum discriminator on the caixa surface (the M3
15530        // mesh-slot per-`:contratos` target-arm axis), closing the
15531        // arm-discriminator convergence trajectory across every
15532        // closed-set typed enum in caixa-core.
15533        let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
15534            (
15535                WitTarget::Http { endpoint: "/x" },
15536                [true, false, false, false],
15537            ),
15538            (
15539                WitTarget::PubSub {
15540                    subject: "events.x",
15541                },
15542                [false, true, false, false],
15543            ),
15544            (
15545                WitTarget::Store { slot: "kv/x" },
15546                [false, false, true, false],
15547            ),
15548            (WitTarget::Capability, [false, false, false, true]),
15549        ];
15550        for (variant, expected) in rows {
15551            let observed = [
15552                variant.is_http(),
15553                variant.is_pubsub(),
15554                variant.is_store(),
15555                variant.is_capability(),
15556            ];
15557            assert_eq!(
15558                observed, expected,
15559                "WitTarget::{variant:?} is_* predicates must partition \
15560                 the arm set (http, pubsub, store, capability); got {observed:?}"
15561            );
15562        }
15563    }
15564
15565    #[test]
15566    fn wit_target_is_variant_predicates_are_const_fn() {
15567        // The [`gen_platform::IsVariant`] derive emits `const fn`
15568        // predicates on the peer [`crate::CaixaKind`] +
15569        // [`crate::upgrade::UpgradeInstruction`] +
15570        // [`crate::supervisor::RestartStrategy`] +
15571        // [`crate::supervisor::RestartPolicy`] +
15572        // [`PlacementStrategy`] closed-set typed enums — pin the
15573        // same posture on [`WitTarget`] so a future accidental
15574        // downgrade to non-`const` (an added runtime helper reachable
15575        // only from a non-`const` context, a manual hand-rolled
15576        // `impl` that shadows the derive-generated method) trips at
15577        // caixa-core build time rather than surfacing as a downstream
15578        // `const`-context regression far from the derive declaration.
15579        //
15580        // Unlike the peer unit-variant enums (`CaixaKind` /
15581        // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
15582        // whose `const` constructors need no arguments, the three
15583        // payload-carrying [`WitTarget`] arms are const-constructed
15584        // through `&'static str` payloads — the same `'static`
15585        // lifetime the closed-set typed enum's four-arm partition
15586        // pin above already threads through.
15587        //
15588        // The pin lives inside a `const { assert!(..) }` block so the
15589        // compiler enforces both halves (arm predicate is `const`-
15590        // callable AND returns `true` for the matching arm) at
15591        // caixa-core compile time — peer to the sibling
15592        // [`crate::CaixaKind::is_*`] const-block pin on the closed-set
15593        // typed enum arm-predicate const-callability axis.
15594        const {
15595            assert!(WitTarget::Http { endpoint: "/x" }.is_http());
15596            assert!(WitTarget::PubSub { subject: "e" }.is_pubsub());
15597            assert!(WitTarget::Store { slot: "kv/x" }.is_store());
15598            assert!(WitTarget::Capability.is_capability());
15599        }
15600    }
15601
15602    #[test]
15603    fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
15604        // Consumer-side pin on the sole production converge site:
15605        // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
15606        // edges from the synchronous-subgraph DFS via the lifted
15607        // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
15608        // predicate (rebound from the prior raw
15609        // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
15610        // variant). Byte-equivalent today (`is_pubsub` is the
15611        // derive-generated `matches!(self, Self::PubSub { .. })` by
15612        // construction, the `#[is_variant(name = "pubsub")]` override
15613        // aliasing the auto-derived `is_pub_sub` back to the sibling
15614        // [`WitContract::is_pubsub`] name); pin the behavior so a
15615        // future accidental drift (a rebind onto a peer arm
15616        // predicate, a manual hand-rolled `impl` that shadows the
15617        // derive-generated method with different semantics, a peer
15618        // arm rename that shifts which variant carries sync-versus-
15619        // async semantics) trips at caixa-core test time rather than
15620        // at some downstream operator's runtime dispatch far from the
15621        // rebind commit.
15622        //
15623        // The fixture constructs a two-Servico Aplicacao with one
15624        // pub-sub edge that would close a sync-cycle if the DFS did
15625        // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
15626        // pub-sub exclusion means the DFS sees only the `b → a` HTTP
15627        // edge, which is not a cycle. A regression in the converge
15628        // (a rebind that reads the pub-sub arm as sync) would report
15629        // `AplicacaoError::ContratoCycle`.
15630        let s = AplicacaoSpec {
15631            membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
15632            contratos: vec![
15633                // Pub-sub edge: DFS must skip via is_pubsub().
15634                WitContract {
15635                    de: "a".into(),
15636                    para: "b".into(),
15637                    wit: "nats:pub-sub".into(),
15638                    endpoint: None,
15639                    subject: Some("events.x".into()),
15640                    slot: None,
15641                },
15642                // HTTP edge: DFS must include.
15643                WitContract {
15644                    de: "b".into(),
15645                    para: "a".into(),
15646                    wit: "wasi:http/proxy".into(),
15647                    endpoint: Some("/x".into()),
15648                    subject: None,
15649                    slot: None,
15650                },
15651            ],
15652            politicas: MeshPolicy::default(),
15653            placement: Placement {
15654                estrategia: PlacementStrategy::Replicated,
15655                clusters: vec!["rio".into()],
15656                affinity: None,
15657                shard_key: None,
15658            },
15659            entrada: None,
15660        };
15661        s.validate()
15662            .expect("pub-sub edge must be excluded from sync-cycle DFS");
15663    }
15664
15665    #[test]
15666    fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
15667        // Consumer-side pin: the same three peer consts thread through
15668        // both the [`WitTarget::label`] template (leading-`:` keyword
15669        // prefix in the duplicate-`:contratos` diagnostic) and the
15670        // [`WitContract::target`] gate's [`AplicacaoError::
15671        // ContratoMissingTarget`] `expected:` scalar (the field the
15672        // author needs to add). Pin both routes at once so a future
15673        // refactor can't accidentally split them onto separate string
15674        // literals — the "one place, everywhere reaches for it"
15675        // invariant the peer const set carries.
15676        let http_label = WitTarget::Http { endpoint: "/x" }.label();
15677        assert!(
15678            http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
15679            "label must lead with :{} keyword (got {http_label:?})",
15680            WitTarget::HTTP_FIELD_NAME,
15681        );
15682
15683        let mut s = three_member_spec();
15684        s.contratos.push(WitContract {
15685            de: "cart".into(),
15686            para: "catalog".into(),
15687            wit: "kafka:topic".into(),
15688            endpoint: None,
15689            subject: None,
15690            slot: None,
15691        });
15692        match s.validate().unwrap_err() {
15693            AplicacaoError::ContratoMissingTarget { expected, .. } => {
15694                assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
15695            }
15696            other => panic!("expected ContratoMissingTarget, got {other:?}"),
15697        }
15698    }
15699
15700    #[test]
15701    fn duplicate_pubsub_diagnostic_names_offending_subject() {
15702        // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
15703        // on the pub-sub target axis: the duplicate-edge diagnostic
15704        // must name the `:subject` payload verbatim (not just the
15705        // `(de, para, wit)` triple). Prior to lifting the label onto
15706        // [`WitTarget::label`] the diagnostic derived the label from
15707        // raw [`WitContract`] `Option<String>` probes — a future
15708        // `WitTarget` variant addition (M4 per-edge WIT registry)
15709        // would silently fall through to the `Capability` "no
15710        // payload" default without a compiler warning. Pinning the
15711        // pub-sub arm's format closes the second of three
15712        // payload-carrying `WitTarget` arms this diagnostic threads
15713        // through.
15714        let mut s = three_member_spec();
15715        let pubsub = WitContract {
15716            de: "payment".into(),
15717            para: "cart".into(),
15718            wit: "nats:pub-sub".into(),
15719            endpoint: None,
15720            subject: Some("events.checkout.paid".into()),
15721            slot: None,
15722        };
15723        s.contratos.push(pubsub.clone());
15724        s.contratos.push(pubsub);
15725        let err = s.validate().unwrap_err();
15726        let msg = format!("{err}");
15727        assert!(
15728            msg.contains(":subject \"events.checkout.paid\""),
15729            "duplicate-pubsub diagnostic must name the offending \
15730             :subject payload (got: {msg:?})"
15731        );
15732    }
15733
15734    #[test]
15735    fn duplicate_store_diagnostic_names_offending_slot() {
15736        // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
15737        // key-value target axis: the diagnostic must name the `:slot`
15738        // payload verbatim. Third of three payload-carrying
15739        // `WitTarget` arms this diagnostic threads through, closing
15740        // the per-arm label pin trilogy (`Http` — 6841,
15741        // `PubSub` + `Store` — this test + peer above).
15742        let mut s = three_member_spec();
15743        let store = WitContract {
15744            de: "cart".into(),
15745            para: "payment".into(),
15746            wit: "wasi:keyvalue/store".into(),
15747            endpoint: None,
15748            subject: None,
15749            slot: Some("checkout/$orderId".into()),
15750        };
15751        s.contratos
15752            .retain(|c| !(c.de == "cart" && c.para == "payment"));
15753        s.contratos.push(store.clone());
15754        s.contratos.push(store);
15755        let err = s.validate().unwrap_err();
15756        let msg = format!("{err}");
15757        assert!(
15758            msg.contains(":slot \"checkout/$orderId\""),
15759            "duplicate-store diagnostic must name the offending :slot \
15760             payload (got: {msg:?})"
15761        );
15762    }
15763
15764    #[test]
15765    fn rejects_entrada_path_without_leading_slash() {
15766        let mut s = three_member_spec();
15767        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
15768        let err = s.validate().unwrap_err();
15769        assert!(
15770            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
15771            "got {err:?}"
15772        );
15773    }
15774
15775    #[test]
15776    fn rejects_empty_entrada_path() {
15777        let mut s = three_member_spec();
15778        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), String::new()];
15779        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
15780    }
15781
15782    #[test]
15783    fn rejects_duplicate_entrada_paths() {
15784        let mut s = three_member_spec();
15785        s.entrada.as_mut().unwrap().paths = vec![
15786            "/api/cart".into(),
15787            "/api/products".into(),
15788            "/api/cart".into(),
15789        ];
15790        let err = s.validate().unwrap_err();
15791        assert!(
15792            matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
15793            "got {err:?}"
15794        );
15795    }
15796
15797    #[test]
15798    fn rejects_zero_entrada_port() {
15799        let mut s = three_member_spec();
15800        s.entrada.as_mut().unwrap().port = 0;
15801        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
15802    }
15803
15804    // ── :entrada :paths value-shape gate ─────────────────────────────
15805    //
15806    // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
15807    // sibling `:paths` axis. Every authoring footgun the K8s Gateway
15808    // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
15809    // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
15810    // time now becomes a caixa-build-time `EntradaPathInvalid` with
15811    // the offending `:paths` entry named verbatim.
15812
15813    #[test]
15814    fn rejects_entrada_path_with_query() {
15815        // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
15816        // silently passed validate and the Gateway API webhook
15817        // rejected it at apply time with no source citation.
15818        let mut s = three_member_spec();
15819        s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
15820        let err = s.validate().unwrap_err();
15821        assert!(
15822            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15823                if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
15824            "got {err:?}"
15825        );
15826    }
15827
15828    #[test]
15829    fn rejects_entrada_path_with_fragment() {
15830        let mut s = three_member_spec();
15831        s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
15832        let err = s.validate().unwrap_err();
15833        assert!(
15834            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15835                if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
15836            "got {err:?}"
15837        );
15838    }
15839
15840    #[test]
15841    fn rejects_entrada_path_with_space() {
15842        let mut s = three_member_spec();
15843        s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
15844        let err = s.validate().unwrap_err();
15845        assert!(
15846            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15847                if path == "/api/my cart" && reason.contains("whitespace")),
15848            "got {err:?}"
15849        );
15850    }
15851
15852    #[test]
15853    fn rejects_entrada_path_with_tab() {
15854        let mut s = three_member_spec();
15855        s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
15856        let err = s.validate().unwrap_err();
15857        assert!(
15858            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15859                if path == "/api/\tcart" && reason.contains("whitespace")),
15860            "got {err:?}"
15861        );
15862    }
15863
15864    #[test]
15865    fn rejects_entrada_path_with_control_char() {
15866        // 0x01 (SOH) — a non-whitespace control char surfaces the
15867        // distinct "control character" reason arm, separate from
15868        // the whitespace arm. Pinned so a future refactor that
15869        // collapses the two arms can't accidentally drop the more
15870        // self-locating diagnostic.
15871        let mut s = three_member_spec();
15872        s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
15873        let err = s.validate().unwrap_err();
15874        assert!(
15875            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15876                if path == "/api/\x01cart" && reason.contains("control character")),
15877            "got {err:?}"
15878        );
15879    }
15880
15881    #[test]
15882    fn rejects_entrada_path_with_non_ascii() {
15883        // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
15884        // unreserved-set rule rejects. The Gateway API webhook
15885        // rejects literal non-ASCII bytes; percent-encoding is the
15886        // only way to author non-ASCII in a path.
15887        let mut s = three_member_spec();
15888        s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
15889        let err = s.validate().unwrap_err();
15890        assert!(
15891            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15892                if path == "/api/café" && reason.contains("non-ASCII")),
15893            "got {err:?}"
15894        );
15895    }
15896
15897    #[test]
15898    fn rejects_entrada_path_with_consecutive_slashes() {
15899        let mut s = three_member_spec();
15900        s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
15901        let err = s.validate().unwrap_err();
15902        assert!(
15903            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15904                if path == "/api//cart" && reason.contains("consecutive `/`")),
15905            "got {err:?}"
15906        );
15907    }
15908
15909    #[test]
15910    fn rejects_entrada_path_with_dot_segment() {
15911        let mut s = three_member_spec();
15912        s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
15913        let err = s.validate().unwrap_err();
15914        assert!(
15915            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15916                if path == "/api/./cart" && reason.contains("`.` segment")),
15917            "got {err:?}"
15918        );
15919    }
15920
15921    #[test]
15922    fn rejects_entrada_path_with_trailing_dot_segment() {
15923        // The bare `/.` and the trailing `/foo/.` are both rejected
15924        // by the Gateway API webhook; pinned separately so a future
15925        // narrowing that catches only the inner form surfaces here.
15926        let mut s = three_member_spec();
15927        s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
15928        let err = s.validate().unwrap_err();
15929        assert!(
15930            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15931                if path == "/api/." && reason.contains("`.` segment")),
15932            "got {err:?}"
15933        );
15934    }
15935
15936    #[test]
15937    fn rejects_entrada_path_with_parent_segment() {
15938        let mut s = three_member_spec();
15939        s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
15940        let err = s.validate().unwrap_err();
15941        assert!(
15942            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15943                if path == "/api/../etc" && reason.contains("`..` parent-segment")),
15944            "got {err:?}"
15945        );
15946    }
15947
15948    #[test]
15949    fn rejects_entrada_path_with_trailing_parent_segment() {
15950        // Trailing `/..` — symmetric arm of the parent-segment rule,
15951        // pinned separately so a future relaxation that only checks
15952        // the inner form (`/../`) surfaces here.
15953        let mut s = three_member_spec();
15954        s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
15955        let err = s.validate().unwrap_err();
15956        assert!(
15957            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15958                if path == "/api/.." && reason.contains("`..` parent-segment")),
15959            "got {err:?}"
15960        );
15961    }
15962
15963    #[test]
15964    fn rejects_entrada_path_too_long() {
15965        // 1025-byte path — one over the Gateway API HTTPPathMatch.value
15966        // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
15967        // ASCII-alphanumeric body so only the length rule fires.
15968        let mut s = three_member_spec();
15969        let big = format!("/api/{}", "a".repeat(1020));
15970        assert_eq!(big.len(), 1025);
15971        s.entrada.as_mut().unwrap().paths = vec![big.clone()];
15972        let err = s.validate().unwrap_err();
15973        assert!(
15974            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15975                if path == &big && reason.contains("max length of 1024")),
15976            "got {err:?}"
15977        );
15978    }
15979
15980    #[test]
15981    fn entrada_path_max_length_validates() {
15982        // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
15983        // maxLength cap. Boundary pin: drift in the cap surfaces here
15984        // and at `rejects_entrada_path_too_long` simultaneously.
15985        let mut s = three_member_spec();
15986        let big = format!("/api/{}", "a".repeat(1019));
15987        assert_eq!(big.len(), 1024);
15988        s.entrada.as_mut().unwrap().paths = vec![big];
15989        s.validate().unwrap();
15990    }
15991
15992    #[test]
15993    fn entrada_accepts_canonical_paths() {
15994        // Positive-control sweep — every form the Gateway API
15995        // apiserver accepts must round-trip through validate. Covers
15996        // the root catch-all, plain paths, dot-prefixed segments
15997        // (hidden-file-style, distinct from `.` and `..` segments
15998        // which are rejected), digit-bearing segments, the canonical
15999        // route-template `:param` form (`:` is RFC 3986 reserved-set
16000        // valid in paths), trailing-slash form, percent-encoded
16001        // segments, and an interior `..` *substring* (`/foo..bar` is
16002        // not the `..` segment and is allowed).
16003        for path in [
16004            "/",
16005            "/api/cart",
16006            "/healthz",
16007            "/api/.config",
16008            "/v1/products",
16009            "/products/:id",
16010            "/api/cart/",
16011            "/api/caf%C3%A9",
16012            "/foo..bar",
16013            "/...",
16014        ] {
16015            let mut s = three_member_spec();
16016            s.entrada.as_mut().unwrap().paths = vec![path.into()];
16017            s.validate()
16018                .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
16019        }
16020    }
16021
16022    #[test]
16023    fn entrada_path_empty_takes_precedence_over_invalid() {
16024        // Ordering pin: `EntradaPathEmpty` is the more self-locating
16025        // diagnostic on `""` and must lead — `validate_entrada_path`
16026        // is only reached after the empty-check fires at the call
16027        // site. (The predicate itself defends against direct
16028        // invocation by returning the same error on `""`.)
16029        let mut s = three_member_spec();
16030        s.entrada.as_mut().unwrap().paths = vec![String::new()];
16031        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
16032    }
16033
16034    #[test]
16035    fn entrada_path_not_absolute_takes_precedence_over_invalid() {
16036        // Ordering pin: a path without a leading `/` surfaces the
16037        // narrower `EntradaPathNotAbsolute` diagnostic first; the
16038        // value-shape gate is only consulted on paths that already
16039        // satisfy the absolute-prefix invariant.
16040        let mut s = three_member_spec();
16041        // `bad path` would fire the whitespace rule under the
16042        // value-shape gate, but missing-leading-`/` is the more
16043        // self-locating diagnostic.
16044        s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
16045        let err = s.validate().unwrap_err();
16046        assert!(
16047            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
16048            "got {err:?}"
16049        );
16050    }
16051
16052    #[test]
16053    fn entrada_path_invalid_fires_before_duplicate_check() {
16054        // Ordering pin: a malformed path on the *first* entry of a
16055        // would-be duplicate pair fires the value-shape gate before
16056        // the duplicate gate, mirroring the
16057        // `placement_cluster_invalid_fires_before_duplicate_check`
16058        // (6cbb900) pattern on the peer axis.
16059        let mut s = three_member_spec();
16060        s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
16061        let err = s.validate().unwrap_err();
16062        assert!(
16063            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
16064            "got {err:?}"
16065        );
16066    }
16067
16068    #[test]
16069    fn entrada_path_diagnostic_carries_offending_path() {
16070        // Diagnostic-shape pin — the offending path + a non-empty
16071        // reason flow through verbatim so the author can grep their
16072        // caixa.lisp for `:paths` and fix it in one edit. Same shape
16073        // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
16074        let mut s = three_member_spec();
16075        s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
16076        let err = s.validate().unwrap_err();
16077        match err {
16078            AplicacaoError::EntradaPathInvalid { path, reason } => {
16079                assert_eq!(path, "/api?q=1");
16080                assert!(!reason.is_empty(), "reason field must be non-empty");
16081            }
16082            other => panic!("expected EntradaPathInvalid, got {other:?}"),
16083        }
16084    }
16085
16086    #[test]
16087    fn rejects_entrada_path_with_curly_brace_template_form() {
16088        // Per-axis pin on the shared `is_gateway_api_http_path`
16089        // reserved-byte arm: the canonical "I wrote an OpenAPI
16090        // path-template `{id}` instead of the Gateway API `:id` form"
16091        // footgun the K8s apiserver would otherwise catch at admission
16092        // time on every `HTTPRoute.spec.rules[].matches[].path.value`
16093        // landing site, far from the caixa.lisp. Surfaces as
16094        // `EntradaPathInvalid` carrying the offending path verbatim
16095        // plus the canonical `%7B`/`%7D` percent-encoding remediation
16096        // — the substrate-side `gateway_api_http_path_rejects_every_
16097        // reserved_printable_ascii_byte` predicate-level sweep pins the
16098        // full eleven-byte set; this per-axis pin confirms the
16099        // diagnostic flows through to the `EntradaPathInvalid` variant.
16100        let mut s = three_member_spec();
16101        s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
16102        let err = s.validate().unwrap_err();
16103        assert!(
16104            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16105                if path == "/api/cart/{id}"
16106                    && reason.contains("reserved character")
16107                    && reason.contains("'{'")
16108                    && reason.contains("%7B")),
16109            "got {err:?}"
16110        );
16111    }
16112
16113    #[test]
16114    fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
16115        // Per-axis peer of `rejects_entrada_path_with_curly_brace_
16116        // template_form` on the sibling `:contratos :endpoint` axis.
16117        // Same shared `is_gateway_api_http_path` reserved-byte arm
16118        // fires through `ContratoEndpointInvalid`, with the offending
16119        // endpoint + `:de` + `:para` + reason flowing through verbatim.
16120        // Pins that the lifted predicate's tightening lands on both
16121        // caller axes simultaneously — one source of truth for the
16122        // Gateway API HTTPPathMatch.value accepted set.
16123        let err = contrato_endpoint_err("/api/cart/{id}");
16124        assert!(
16125            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
16126                if endpoint == "/api/cart/{id}"
16127                    && reason.contains("reserved character")
16128                    && reason.contains("'{'")
16129                    && reason.contains("%7B")),
16130            "got {err:?}"
16131        );
16132    }
16133
16134    // ── :entrada :host value-shape gate ──────────────────────────────
16135    //
16136    // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
16137    // the sibling `:host` axis. Every authoring footgun the K8s
16138    // Gateway API v1 apiserver would catch at admission time becomes
16139    // a caixa-build-time `EntradaHostInvalid` with the offending
16140    // `:host` named verbatim. Same diagnostic shape as
16141    // `MembroVersaoInvalid` (9888b13).
16142
16143    #[test]
16144    fn rejects_entrada_host_with_scheme() {
16145        // Fail-before-pass-after pin — pre-gate codebases silently
16146        // accepted `https://…` and the apiserver rejected it at apply
16147        // time with no source citation.
16148        let mut s = three_member_spec();
16149        s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
16150        let err = s.validate().unwrap_err();
16151        assert!(
16152            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
16153                if host == "https://checkout.quero.cloud"),
16154            "got {err:?}"
16155        );
16156    }
16157
16158    #[test]
16159    fn rejects_entrada_host_with_port() {
16160        // The `:8080` port suffix is the canonical "I forgot the port
16161        // belongs in `:entrada :port`" footgun. The top-level `:` arm
16162        // (introduced after the per-label loop-only impl silently
16163        // surfaced a deep "label \"cloud:8080\" contains invalid
16164        // character ':'" leak) names the canonical fix verbatim — the
16165        // `:entrada :port` slot.
16166        let mut s = three_member_spec();
16167        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
16168        let err = s.validate().unwrap_err();
16169        assert!(
16170            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
16171                if host == "checkout.quero.cloud:8080"
16172                && reason.contains(":entrada :port")),
16173            "got {err:?}"
16174        );
16175    }
16176
16177    #[test]
16178    fn rejects_entrada_host_with_trailing_colon() {
16179        // Trailing `:` (e.g. an in-progress `:host "example.com:"`
16180        // edit) — the per-label loop would land it as a deep
16181        // "label \"com:\" must start and end with an alphanumeric"
16182        // / "contains invalid character ':'" leak. The top-level
16183        // `:` arm pre-empts with the canonical `:port` slot
16184        // diagnostic.
16185        let mut s = three_member_spec();
16186        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
16187        let err = s.validate().unwrap_err();
16188        assert!(
16189            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
16190                if host == "checkout.quero.cloud:"
16191                && reason.contains(":entrada :port")),
16192            "got {err:?}"
16193        );
16194    }
16195
16196    #[test]
16197    fn rejects_entrada_host_unbracketed_ipv6_literal() {
16198        // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
16199        // literals across the board (peer with `rejects_entrada_host_
16200        // ipv4_literal` above for the four-label-all-digit IPv4 arm).
16201        // Before this top-level `:` arm landed the per-label loop
16202        // surfaced a single-label byte-class diagnostic that named the
16203        // `:` byte but not the IP-literal prohibition. The top-level
16204        // `:` arm names both the `:port` slot and the IP-literal
16205        // prohibition verbatim, so an author whose `:host "2001:..."`
16206        // value lands here gets a self-locating fix either way.
16207        let mut s = three_member_spec();
16208        s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
16209        let err = s.validate().unwrap_err();
16210        assert!(
16211            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
16212                if host == "2001:db8::1"
16213                && reason.contains("IPv6")),
16214            "got {err:?}"
16215        );
16216    }
16217
16218    #[test]
16219    fn rejects_entrada_host_wildcard_with_port() {
16220        // Wildcard host with port suffix — the `*.` strip and the
16221        // per-label loop on `["foo", "quero", "cloud:8080"]` would
16222        // surface the deep byte-class leak. The top-level `:` arm sits
16223        // upstream of the `*.` strip, so it names the canonical `:port`
16224        // fix verbatim regardless of whether the host is wildcard-led.
16225        let mut s = three_member_spec();
16226        s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
16227        let err = s.validate().unwrap_err();
16228        assert!(
16229            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
16230                if host == "*.quero.cloud:8080"
16231                && reason.contains(":entrada :port")),
16232            "got {err:?}"
16233        );
16234    }
16235
16236    #[test]
16237    fn rejects_entrada_host_with_path() {
16238        let mut s = three_member_spec();
16239        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
16240        let err = s.validate().unwrap_err();
16241        assert!(
16242            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
16243                if host == "checkout.quero.cloud/api"),
16244            "got {err:?}"
16245        );
16246    }
16247
16248    #[test]
16249    fn rejects_entrada_host_with_uppercase() {
16250        // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
16251        // rejected, not silently lower-cased.
16252        let mut s = three_member_spec();
16253        s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
16254        let err = s.validate().unwrap_err();
16255        assert!(
16256            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16257                if reason.contains("uppercase")),
16258            "got {err:?}"
16259        );
16260    }
16261
16262    #[test]
16263    fn rejects_entrada_host_with_underscore() {
16264        // RFC 1123 allows `[a-z0-9-]` only; underscore is the
16265        // canonical "I'm thinking of HTTP cookies / SRV records" leak.
16266        let mut s = three_member_spec();
16267        s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
16268        let err = s.validate().unwrap_err();
16269        assert!(
16270            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16271                if reason.contains('_')),
16272            "got {err:?}"
16273        );
16274    }
16275
16276    #[test]
16277    fn rejects_entrada_host_ipv4_literal() {
16278        // Gateway API v1 explicitly forbids IP literals as Hostnames.
16279        let mut s = three_member_spec();
16280        s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
16281        let err = s.validate().unwrap_err();
16282        assert!(
16283            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16284                if reason.contains("IPv4")),
16285            "got {err:?}"
16286        );
16287    }
16288
16289    #[test]
16290    fn rejects_entrada_host_with_trailing_dot() {
16291        // The Gateway API regex anchors at end-of-string with no
16292        // trailing `.` allowance — the FQDN root-dot form is rejected.
16293        let mut s = three_member_spec();
16294        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
16295        let err = s.validate().unwrap_err();
16296        assert!(
16297            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
16298                if host == "checkout.quero.cloud."),
16299            "got {err:?}"
16300        );
16301    }
16302
16303    #[test]
16304    fn rejects_entrada_host_with_leading_dot() {
16305        let mut s = three_member_spec();
16306        s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
16307        let err = s.validate().unwrap_err();
16308        assert!(
16309            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16310                if reason.contains("empty label")),
16311            "got {err:?}"
16312        );
16313    }
16314
16315    #[test]
16316    fn rejects_entrada_host_with_consecutive_dots() {
16317        let mut s = three_member_spec();
16318        s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
16319        let err = s.validate().unwrap_err();
16320        assert!(
16321            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16322                if reason.contains("empty label")),
16323            "got {err:?}"
16324        );
16325    }
16326
16327    #[test]
16328    fn rejects_entrada_host_with_leading_hyphen_label() {
16329        let mut s = three_member_spec();
16330        s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
16331        let err = s.validate().unwrap_err();
16332        assert!(
16333            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16334                if reason.contains("alphanumeric")),
16335            "got {err:?}"
16336        );
16337    }
16338
16339    #[test]
16340    fn rejects_entrada_host_with_trailing_hyphen_label() {
16341        let mut s = three_member_spec();
16342        s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
16343        let err = s.validate().unwrap_err();
16344        assert!(
16345            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16346                if reason.contains("alphanumeric")),
16347            "got {err:?}"
16348        );
16349    }
16350
16351    #[test]
16352    fn rejects_entrada_host_with_inner_wildcard() {
16353        // Gateway API allows `*` only as the first label (`*.foo`);
16354        // any inner or trailing `*` is rejected.
16355        let mut s = three_member_spec();
16356        s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
16357        let err = s.validate().unwrap_err();
16358        assert!(
16359            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16360                if reason.contains("wildcard")),
16361            "got {err:?}"
16362        );
16363    }
16364
16365    #[test]
16366    fn rejects_entrada_host_bare_wildcard() {
16367        // `*.` with no domain is meaningless; Gateway API rejects it.
16368        let mut s = three_member_spec();
16369        s.entrada.as_mut().unwrap().host = "*.".into();
16370        let err = s.validate().unwrap_err();
16371        assert!(
16372            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16373                if reason.contains("wildcard")),
16374            "got {err:?}"
16375        );
16376    }
16377
16378    #[test]
16379    fn rejects_entrada_host_with_whitespace() {
16380        let mut s = three_member_spec();
16381        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
16382        let err = s.validate().unwrap_err();
16383        assert!(
16384            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16385                if reason.contains("whitespace")),
16386            "got {err:?}"
16387        );
16388    }
16389
16390    #[test]
16391    fn rejects_entrada_host_space_names_offending_byte() {
16392        // Embedded space in the `:entrada :host` axis surfaces the
16393        // byte-naming diagnostic through the lifted
16394        // `find_ascii_whitespace_byte` predicate. Peer with the
16395        // sibling `parse_rejects_leading_whitespace` pins on
16396        // `supervisor::duration_codec` (a7ae622) — same "the
16397        // diagnostic carries the offending byte's `0x{b:02x}` shape"
16398        // discipline extended from the shared duration codec to the
16399        // Gateway API v1 Hostname axis.
16400        let mut s = three_member_spec();
16401        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
16402        let err = s.validate().unwrap_err();
16403        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
16404            panic!("expected EntradaHostInvalid, got {err:?}");
16405        };
16406        assert!(
16407            reason.contains("ASCII whitespace byte"),
16408            "expected byte-naming diagnostic, got {reason:?}"
16409        );
16410        assert!(
16411            reason.contains("0x20"),
16412            "expected offending space byte 0x20, got {reason:?}"
16413        );
16414    }
16415
16416    #[test]
16417    fn rejects_entrada_host_tab_names_offending_byte() {
16418        // Embedded tab byte in the `:entrada :host` axis — the
16419        // canonical paste-from-YAML-block-scalar / paste-from-
16420        // indented-doc footgun. Pins that the lifted predicate covers
16421        // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
16422        // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
16423        // not just the leading-space case the pre-lift `.bytes().any`
16424        // arm's opaque "must not contain whitespace" reason already
16425        // covered. Peer with `parse_rejects_tab_byte` on
16426        // `supervisor::duration_codec` (a7ae622).
16427        let mut s = three_member_spec();
16428        s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
16429        let err = s.validate().unwrap_err();
16430        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
16431            panic!("expected EntradaHostInvalid, got {err:?}");
16432        };
16433        assert!(
16434            reason.contains("ASCII whitespace byte"),
16435            "expected byte-naming diagnostic, got {reason:?}"
16436        );
16437        assert!(
16438            reason.contains("0x09"),
16439            "expected offending tab byte 0x09, got {reason:?}"
16440        );
16441    }
16442
16443    #[test]
16444    fn rejects_entrada_host_lf_names_offending_byte() {
16445        // Embedded LF byte in the `:entrada :host` axis — the
16446        // canonical paste-from-shell-heredoc / paste-from-multiline-
16447        // doc footgun the caixa-mesh YAML emitter would silently
16448        // reinterpret at the Gateway API v1 HTTPRoute admission
16449        // layer (an embedded LF byte in a YAML plain scalar either
16450        // truncates the value at the emitter or crashes the parser
16451        // on the k8s-apiserver side). Pins the third representative
16452        // of the full ASCII-whitespace set through the shared
16453        // predicate.
16454        let mut s = three_member_spec();
16455        s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
16456        let err = s.validate().unwrap_err();
16457        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
16458            panic!("expected EntradaHostInvalid, got {err:?}");
16459        };
16460        assert!(
16461            reason.contains("ASCII whitespace byte"),
16462            "expected byte-naming diagnostic, got {reason:?}"
16463        );
16464        assert!(
16465            reason.contains("0x0a"),
16466            "expected offending LF byte 0x0a, got {reason:?}"
16467        );
16468    }
16469
16470    #[test]
16471    fn rejects_entrada_host_nbsp_names_offending_codepoint() {
16472        // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
16473        // axis — the canonical paste-from-typography /
16474        // paste-from-word-processor footgun. Before the non-ASCII
16475        // Unicode `White_Space` scan lifted through the shared
16476        // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
16477        // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
16478        // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
16479        // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
16480        // with the far-from-source `label "…" must start and end
16481        // with an alphanumeric` diagnostic — burying the
16482        // paste-from-typography origin under a label-shape leak.
16483        // Peer with the sibling non-ASCII-whitespace pins at
16484        // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
16485        // — 1b75b38), `limits::parse_duration`,
16486        // `limits::parse_millicores`, and the shared duration codec
16487        // — same "the diagnostic carries the offending Unicode
16488        // codepoint's `U+XXXX` shape" discipline extended from every
16489        // typed-magnitude codec to the Gateway API v1 Hostname axis.
16490        let mut s = three_member_spec();
16491        s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
16492        let err = s.validate().unwrap_err();
16493        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
16494            panic!("expected EntradaHostInvalid, got {err:?}");
16495        };
16496        assert!(
16497            reason.contains("non-ASCII Unicode whitespace character"),
16498            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
16499        );
16500        assert!(
16501            reason.contains("U+00A0"),
16502            "expected offending NBSP codepoint U+00A0, got {reason:?}"
16503        );
16504    }
16505
16506    #[test]
16507    fn rejects_entrada_host_line_separator_names_offending_codepoint() {
16508        // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
16509        // `:entrada :host` axis — the canonical paste-from-web-doc /
16510        // paste-from-published-HTML footgun. `char::is_whitespace`
16511        // returns true for `U+2028` per the Unicode `White_Space`
16512        // property, so `str::trim` at any downstream site would
16513        // silently strip it — same drift class as NBSP but on a
16514        // different codepoint region. Pins the second representative
16515        // (non-Latin-1 `char::is_whitespace` member) through the
16516        // shared predicate. Peer with
16517        // `parse_byte_size_rejects_internal_line_separator` on
16518        // `limits::parse_byte_size` (1b75b38).
16519        let mut s = three_member_spec();
16520        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
16521        let err = s.validate().unwrap_err();
16522        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
16523            panic!("expected EntradaHostInvalid, got {err:?}");
16524        };
16525        assert!(
16526            reason.contains("non-ASCII Unicode whitespace character"),
16527            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
16528        );
16529        assert!(
16530            reason.contains("U+2028"),
16531            "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
16532        );
16533    }
16534
16535    #[test]
16536    fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
16537        // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
16538        // labels in the `:entrada :host` axis — the canonical
16539        // paste-from-CJK-typography footgun (CJK IMEs default to
16540        // full-width whitespace when the space bar is pressed in
16541        // Japanese / Chinese input modes). Pins the third
16542        // representative of the non-ASCII Unicode `White_Space` set
16543        // through the shared predicate: the CJK block, distinct from
16544        // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
16545        // SEPARATOR `U+2028` — covering the same axis breadth the
16546        // sibling `parse_byte_size_rejects_trailing_ideographic_space`
16547        // (1b75b38) pins on `limits::parse_byte_size`.
16548        let mut s = three_member_spec();
16549        s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
16550        let err = s.validate().unwrap_err();
16551        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
16552            panic!("expected EntradaHostInvalid, got {err:?}");
16553        };
16554        assert!(
16555            reason.contains("non-ASCII Unicode whitespace character"),
16556            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
16557        );
16558        assert!(
16559            reason.contains("U+3000"),
16560            "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
16561        );
16562    }
16563
16564    #[test]
16565    fn rejects_entrada_host_too_long() {
16566        // Total length cap = 253; build a 254-byte host out of two
16567        // 63-byte labels + one 62-byte label + dots.
16568        let mut s = three_member_spec();
16569        let big = format!(
16570            "{}.{}.{}.{}",
16571            "a".repeat(63),
16572            "b".repeat(63),
16573            "c".repeat(63),
16574            "d".repeat(254 - 63 * 3 - 3)
16575        );
16576        assert_eq!(big.len(), 254);
16577        s.entrada.as_mut().unwrap().host = big;
16578        let err = s.validate().unwrap_err();
16579        assert!(
16580            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16581                if reason.contains("max length of 253")),
16582            "got {err:?}"
16583        );
16584    }
16585
16586    #[test]
16587    fn rejects_entrada_host_label_too_long() {
16588        let mut s = three_member_spec();
16589        // 64-byte label — one over the per-label cap.
16590        s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
16591        let err = s.validate().unwrap_err();
16592        assert!(
16593            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16594                if reason.contains("label max length of 63")),
16595            "got {err:?}"
16596        );
16597    }
16598
16599    #[test]
16600    fn entrada_host_diagnostic_carries_offending_host() {
16601        // Diagnostic-shape pin — the offending host + a non-empty
16602        // reason flow through verbatim so the author can grep their
16603        // caixa.lisp for `:host "<host>"` and fix it in one edit.
16604        let mut s = three_member_spec();
16605        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
16606        let err = s.validate().unwrap_err();
16607        match err {
16608            AplicacaoError::EntradaHostInvalid { host, reason } => {
16609                assert_eq!(host, "checkout.quero.cloud:8080");
16610                assert!(!reason.is_empty(), "reason field must be non-empty");
16611            }
16612            other => panic!("expected EntradaHostInvalid, got {other:?}"),
16613        }
16614    }
16615
16616    // Equivalence pin for the [`AplicacaoError::entrada_host_invalid`]
16617    // substrate primitive that folds the fourteen
16618    // `AplicacaoError::EntradaHostInvalid { host: host.to_string(),
16619    // reason: <expr> }` wire-up sites at [`validate_entrada_host`] onto
16620    // one dispatch — peer with the sixteen equivalence pins the
16621    // [`crate::LayoutError`] `_violation` constructor family carries in
16622    // `layout::tests::*_ctor_matches_struct_literal_wrap` (131ca0d). The
16623    // fixture host + reason are fixed `&'static str`s so both fields of
16624    // both constructed variants pin verbatim: the `host` axis is pinned
16625    // through the shared `host.to_string()` wrap (the ctor's uniform
16626    // one-slot construction) and the `reason` axis is pinned through
16627    // the shared `reason.into()` wrap (the ctor's `impl Into<String>`
16628    // routing). Any future regression on the lift (an extra field
16629    // introduced without updating the ctor, a diverging string
16630    // conversion at either arm) surfaces at this pin's diagnostic
16631    // rather than at a per-wire-up struct-literal reintroduction.
16632    #[test]
16633    fn entrada_host_invalid_ctor_matches_struct_literal_wrap() {
16634        let host = "checkout.quero.cloud:8080";
16635        let reason = "sample reason text";
16636        assert_eq!(
16637            AplicacaoError::entrada_host_invalid(host, reason),
16638            AplicacaoError::EntradaHostInvalid {
16639                host: host.to_string(),
16640                reason: reason.to_string(),
16641            },
16642            "generated constructor must produce byte-equal AplicacaoError to open-coded struct-literal wrap",
16643        );
16644    }
16645
16646    // Routing pin — the ctor's `host: &str` argument threads through
16647    // `.to_string()` verbatim on the `host` field, so the constructed
16648    // variant carries the offending host bytes without any wrapper-
16649    // side transformation (no `.to_ascii_lowercase()` normalization,
16650    // no `.trim()` strip, no truncation) — the same "diagnostic carries
16651    // the offending value verbatim so the author can grep their
16652    // caixa.lisp" discipline every peer typed-slot ctor at this
16653    // altitude carries.
16654    #[test]
16655    fn entrada_host_invalid_ctor_routes_host_through_to_string() {
16656        // Uppercase + trailing whitespace + port suffix — three
16657        // wrapper-side transformations the ctor must *not* apply.
16658        let host = " Checkout.quero.CLOUD:8080 ";
16659        let err = AplicacaoError::entrada_host_invalid(host, "sample");
16660        match err {
16661            AplicacaoError::EntradaHostInvalid { host: h, .. } => {
16662                assert_eq!(h, host, "host must thread through `.to_string()` verbatim");
16663            }
16664            other => panic!("expected EntradaHostInvalid, got {other:?}"),
16665        }
16666    }
16667
16668    // Routing pin — the ctor's `reason: impl Into<String>` accepts both
16669    // `&str` literals and `format!(…)` outputs identically and both
16670    // route through `Into::into` verbatim onto the `reason` field.
16671    // Pins both codepaths against the same host to prove the two
16672    // shapes the fourteen wire-up sites use at their per-arm diagnostic
16673    // (ten `&str` literals — some with `.to_string()` at the caller,
16674    // some without — plus four `format!(…)` outputs) each produce
16675    // byte-equal `reason` fields against the same offending host.
16676    #[test]
16677    fn entrada_host_invalid_ctor_routes_reason_through_into() {
16678        let host = "checkout.quero.cloud";
16679        // `&str` literal — the ctor's `impl Into<String>` accepts it
16680        // without a caller-side `.to_string()`.
16681        let from_literal = AplicacaoError::entrada_host_invalid(host, "literal reason text");
16682        // Owned `String` from `format!` — the peer `format!(…)`-shaped
16683        // wire-up arm.
16684        let from_format =
16685            AplicacaoError::entrada_host_invalid(host, format!("{} reason text", "literal"));
16686        // `String` from `.to_string()` on a literal — the peer
16687        // `"literal".to_string()`-shaped wire-up arm the pre-lift
16688        // sites carried.
16689        let from_to_string =
16690            AplicacaoError::entrada_host_invalid(host, "literal reason text".to_string());
16691        match (&from_literal, &from_format, &from_to_string) {
16692            (
16693                AplicacaoError::EntradaHostInvalid {
16694                    reason: r_lit,
16695                    host: h_lit,
16696                },
16697                AplicacaoError::EntradaHostInvalid {
16698                    reason: r_fmt,
16699                    host: h_fmt,
16700                },
16701                AplicacaoError::EntradaHostInvalid {
16702                    reason: r_ts,
16703                    host: h_ts,
16704                },
16705            ) => {
16706                assert_eq!(r_lit, "literal reason text");
16707                assert_eq!(r_fmt, "literal reason text");
16708                assert_eq!(r_ts, "literal reason text");
16709                assert_eq!(h_lit, host);
16710                assert_eq!(h_fmt, host);
16711                assert_eq!(h_ts, host);
16712            }
16713            _ => panic!("expected three EntradaHostInvalid variants"),
16714        }
16715        // Cross-arm equivalence — the three shapes must produce
16716        // byte-equal `AplicacaoError` values, so the fourteen wire-up
16717        // sites' mixed per-arm shapes fold onto one canonical form.
16718        assert_eq!(from_literal, from_format);
16719        assert_eq!(from_literal, from_to_string);
16720    }
16721
16722    // Equivalence pins for the six sibling
16723    // [`aplicacao_field_reason_ctors!`]-generated constructors that
16724    // fold the peer `{ <field>: String, reason: String }` variants
16725    // onto the same substrate-primitive family
16726    // `entrada_host_invalid` (17dd504) already carries pins for.
16727    // Each ctor's fixture pair (a fixed `&'static str` value and a
16728    // fixed `&'static str` reason) pins both fields verbatim so any
16729    // future regression on the macro (an extra field introduced
16730    // without updating the macro, a diverging string conversion at
16731    // either arm, a field-name typo on one variant that dropped it
16732    // off the shared shape) surfaces at the affected variant's pin
16733    // rather than at a per-wire-up struct-literal reintroduction. Peer
16734    // discipline of the sixteen `LayoutError` _violation ctor pins in
16735    // `layout::tests::*_ctor_matches_struct_literal_wrap` (131ca0d)
16736    // and the paired
16737    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
16738    // `contrato_missing_target_ctor_matches_struct_literal_wrap`
16739    // (14b81d5) / `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
16740    // (8580068) equivalence pins on the sibling `AplicacaoError`
16741    // ctor macros.
16742    #[test]
16743    fn membro_caixa_invalid_ctor_matches_struct_literal_wrap() {
16744        let caixa = "cart-svc";
16745        let reason = "sample reason text";
16746        assert_eq!(
16747            AplicacaoError::membro_caixa_invalid(caixa, reason),
16748            AplicacaoError::MembroCaixaInvalid {
16749                caixa: caixa.to_string(),
16750                reason: reason.to_string(),
16751            },
16752        );
16753    }
16754
16755    #[test]
16756    fn entrada_para_invalid_ctor_matches_struct_literal_wrap() {
16757        let para = "checkout";
16758        let reason = "sample reason text";
16759        assert_eq!(
16760            AplicacaoError::entrada_para_invalid(para, reason),
16761            AplicacaoError::EntradaParaInvalid {
16762                para: para.to_string(),
16763                reason: reason.to_string(),
16764            },
16765        );
16766    }
16767
16768    #[test]
16769    fn entrada_path_invalid_ctor_matches_struct_literal_wrap() {
16770        let path = "/api/cart";
16771        let reason = "sample reason text";
16772        assert_eq!(
16773            AplicacaoError::entrada_path_invalid(path, reason),
16774            AplicacaoError::EntradaPathInvalid {
16775                path: path.to_string(),
16776                reason: reason.to_string(),
16777            },
16778        );
16779    }
16780
16781    #[test]
16782    fn placement_cluster_invalid_ctor_matches_struct_literal_wrap() {
16783        let cluster = "rio";
16784        let reason = "sample reason text";
16785        assert_eq!(
16786            AplicacaoError::placement_cluster_invalid(cluster, reason),
16787            AplicacaoError::PlacementClusterInvalid {
16788                cluster: cluster.to_string(),
16789                reason: reason.to_string(),
16790            },
16791        );
16792    }
16793
16794    #[test]
16795    fn placement_affinity_invalid_ctor_matches_struct_literal_wrap() {
16796        let affinity = "data-locality";
16797        let reason = "sample reason text";
16798        assert_eq!(
16799            AplicacaoError::placement_affinity_invalid(affinity, reason),
16800            AplicacaoError::PlacementAffinityInvalid {
16801                affinity: affinity.to_string(),
16802                reason: reason.to_string(),
16803            },
16804        );
16805    }
16806
16807    #[test]
16808    fn shard_key_invalid_ctor_matches_struct_literal_wrap() {
16809        let shard_key = "tenantId";
16810        let reason = "sample reason text";
16811        assert_eq!(
16812            AplicacaoError::shard_key_invalid(shard_key, reason),
16813            AplicacaoError::ShardKeyInvalid {
16814                shard_key: shard_key.to_string(),
16815                reason: reason.to_string(),
16816            },
16817        );
16818    }
16819
16820    // Cross-family invariance pin — the six sibling ctors and
16821    // `entrada_host_invalid` all route `reason: impl Into<String>` +
16822    // `<field>: &str` verbatim onto their respective typed variants
16823    // through the shared [`aplicacao_field_reason_ctors!`] macro.
16824    // Sweeps a fixture pair (`&str` literal, `format!` output) against
16825    // every ctor to pin that no per-arm wrapper transformation drifted
16826    // in against the uniform macro-generated body.
16827    #[test]
16828    fn aplicacao_field_reason_ctors_route_reason_through_into_uniformly() {
16829        let via_literal = "literal reason text";
16830        let via_format = format!("{} reason text", "literal");
16831        assert_eq!(
16832            AplicacaoError::membro_caixa_invalid("m", via_literal),
16833            AplicacaoError::membro_caixa_invalid("m", via_format.clone()),
16834        );
16835        assert_eq!(
16836            AplicacaoError::entrada_para_invalid("p", via_literal),
16837            AplicacaoError::entrada_para_invalid("p", via_format.clone()),
16838        );
16839        assert_eq!(
16840            AplicacaoError::entrada_path_invalid("/a", via_literal),
16841            AplicacaoError::entrada_path_invalid("/a", via_format.clone()),
16842        );
16843        assert_eq!(
16844            AplicacaoError::placement_cluster_invalid("c", via_literal),
16845            AplicacaoError::placement_cluster_invalid("c", via_format.clone()),
16846        );
16847        assert_eq!(
16848            AplicacaoError::placement_affinity_invalid("a", via_literal),
16849            AplicacaoError::placement_affinity_invalid("a", via_format.clone()),
16850        );
16851        assert_eq!(
16852            AplicacaoError::shard_key_invalid("k", via_literal),
16853            AplicacaoError::shard_key_invalid("k", via_format.clone()),
16854        );
16855        assert_eq!(
16856            AplicacaoError::entrada_host_invalid("h", via_literal),
16857            AplicacaoError::entrada_host_invalid("h", via_format),
16858        );
16859    }
16860
16861    #[test]
16862    fn entrada_host_empty_takes_precedence_over_invalid() {
16863        // Ordering pin: `EmptyEntradaHost` is the more self-locating
16864        // diagnostic on `""` and must lead — `validate_entrada_host`
16865        // is only reached after the empty-check fires at the call
16866        // site. (The predicate itself defends against direct
16867        // invocation by returning the same error on `""`.)
16868        let mut s = three_member_spec();
16869        s.entrada.as_mut().unwrap().host = String::new();
16870        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
16871    }
16872
16873    #[test]
16874    fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
16875        // Ordering pin: a missing :para member is the more
16876        // self-locating diagnostic and fires before the host gate.
16877        let mut s = three_member_spec();
16878        let e = s.entrada.as_mut().unwrap();
16879        e.para = "ghost".into();
16880        e.host = "BAD HOST".into();
16881        let err = s.validate().unwrap_err();
16882        assert!(
16883            matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
16884            "got {err:?}"
16885        );
16886    }
16887
16888    #[test]
16889    fn entrada_host_invalid_fires_before_port_zero() {
16890        // Ordering pin: the host gate fires before the port gate so
16891        // a malformed host is named even when the port is also wrong.
16892        let mut s = three_member_spec();
16893        let e = s.entrada.as_mut().unwrap();
16894        e.host = "Checkout.quero.cloud".into();
16895        e.port = 0;
16896        let err = s.validate().unwrap_err();
16897        assert!(
16898            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
16899                if host == "Checkout.quero.cloud"),
16900            "got {err:?}"
16901        );
16902    }
16903
16904    #[test]
16905    fn entrada_accepts_canonical_hosts() {
16906        // Positive-control sweep — every form the Gateway API
16907        // apiserver accepts must round-trip through validate. Covers
16908        // a plain DNS subdomain, a leading wildcard, a single-label
16909        // host (cluster-internal), a max-length-edge label, a
16910        // hyphen-bearing label, and a Punycode IDN label.
16911        for host in [
16912            "checkout.quero.cloud",
16913            "*.quero.cloud",
16914            "checkout",
16915            // 63-byte label — exactly the per-label cap.
16916            "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
16917            "foo-bar.quero.cloud",
16918            // Punycode IDN — valid because the author pre-encoded.
16919            "xn--bcher-kva.example.com",
16920        ] {
16921            let mut s = three_member_spec();
16922            s.entrada.as_mut().unwrap().host = host.into();
16923            s.validate()
16924                .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
16925        }
16926    }
16927
16928    #[test]
16929    fn entrada_host_max_length_validates() {
16930        // 253-byte host is the cap exactly — must validate. Build a
16931        // 253-byte host out of three 63-byte labels + one 61-byte
16932        // label + 3 dots = 252 bytes, then pad one byte to 253.
16933        let mut s = three_member_spec();
16934        let host = format!(
16935            "{}.{}.{}.{}",
16936            "a".repeat(63),
16937            "b".repeat(63),
16938            "c".repeat(63),
16939            "d".repeat(253 - 63 * 3 - 3)
16940        );
16941        assert_eq!(host.len(), 253);
16942        s.entrada.as_mut().unwrap().host = host;
16943        s.validate().unwrap();
16944    }
16945
16946    #[test]
16947    fn entrada_host_total_length_cap_threads_lifted_render_const() {
16948        // Cross-crate-side pin: the aplicacao-side `:entrada :host`
16949        // total-length gate now reads the K8s Gateway API v1 Hostname
16950        // `maxLength: 253` cap from the lifted
16951        // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
16952        // of truth — the same constant every future Gateway-API-Hostname
16953        // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
16954        // materializer's per-host validator, the future per-`Certificate`
16955        // SAN emitter for cert-manager, the multi-`:entrada`
16956        // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
16957        // from. Before the lift, the aplicacao-side reader consumed a
16958        // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
16959        // 253-byte value as the peer render-side canonical bounds
16960        // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
16961        // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
16962        // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
16963        // module boundary — a future 253-byte drift on either side would
16964        // silently split into two axes' worth of admission-schema mismatch
16965        // without a build-time signal. Pin the cap through a fresh 254-
16966        // byte host that hits the total-length arm, then read the reason
16967        // for the exact byte count the shared constant carries: any future
16968        // regression on the lift (a private alias reintroduced, a hard-
16969        // coded literal at the arm, a mismatch between the aplicacao-side
16970        // and render-side canonicals) surfaces as this pin's diagnostic
16971        // failing to match, not as a per-cluster admission rejection far
16972        // from the caixa.lisp source line.
16973        let mut s = three_member_spec();
16974        let over_cap = format!(
16975            "{}.{}.{}.{}",
16976            "a".repeat(63),
16977            "b".repeat(63),
16978            "c".repeat(63),
16979            "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
16980        );
16981        assert_eq!(
16982            over_cap.len(),
16983            crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
16984        );
16985        s.entrada.as_mut().unwrap().host = over_cap;
16986        let err = s.validate().unwrap_err();
16987        match err {
16988            AplicacaoError::EntradaHostInvalid { reason, .. } => {
16989                let needle = format!(
16990                    "max length of {} bytes",
16991                    crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
16992                );
16993                assert!(
16994                    reason.contains(&needle),
16995                    "diagnostic must name the lifted \
16996                     GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
16997                );
16998            }
16999            other => panic!("expected EntradaHostInvalid, got {other:?}"),
17000        }
17001    }
17002
17003    #[test]
17004    fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
17005        // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
17006        // on the per-label-cap axis. Before the lift, the aplicacao-side
17007        // per-label arm consumed a private const alias
17008        // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
17009        // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
17010        // split from it at the module boundary — every `.`-separated
17011        // label in a Gateway API v1 Hostname is a DNS-1123 label under
17012        // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
17013        // so the private alias's 63 and the canonical const's 63 were
17014        // pinning the same underlying rule twice. Pin the cap through a
17015        // 64-byte label that hits the per-label arm, then read the reason
17016        // for the exact byte count the shared constant carries: any
17017        // future drift on either side (a private alias reintroduced, a
17018        // hard-coded literal at the arm, a mismatch between the two
17019        // 63-byte pins) surfaces at this pin's diagnostic rather than at
17020        // a per-cluster admission rejection whose "field is invalid"
17021        // opacity misframes the root cause.
17022        let mut s = three_member_spec();
17023        let over_cap_label = format!(
17024            "{}.quero.cloud",
17025            "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
17026        );
17027        s.entrada.as_mut().unwrap().host = over_cap_label;
17028        let err = s.validate().unwrap_err();
17029        match err {
17030            AplicacaoError::EntradaHostInvalid { reason, .. } => {
17031                let needle = format!(
17032                    "label max length of {} bytes",
17033                    crate::render::DNS_1123_LABEL_MAX_LEN,
17034                );
17035                assert!(
17036                    reason.contains(&needle),
17037                    "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
17038                     cap verbatim on the per-label arm, got: {reason:?}",
17039                );
17040            }
17041            other => panic!("expected EntradaHostInvalid, got {other:?}"),
17042        }
17043    }
17044
17045    #[test]
17046    fn entrada_with_empty_paths_validates() {
17047        // Empty `:paths` is the documented "match every path" form;
17048        // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
17049        let mut s = three_member_spec();
17050        s.entrada.as_mut().unwrap().paths = vec![];
17051        s.validate().unwrap();
17052    }
17053
17054    #[test]
17055    fn entrada_root_path_validates() {
17056        // The author-supplied bare-root `:entrada :paths` entry is the
17057        // same byte-shape the peer emit-side catch-all constant
17058        // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
17059        // the author's `:paths` list is empty — sweeping the test-side
17060        // probe literal onto the lifted const closes the two-axis pin
17061        // (author-side admit + emit-side canonical fallback) around
17062        // one `&'static str`, so a future rebrand of the catch-all
17063        // reaches both consumers by construction. Peer to
17064        // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
17065        // on the canonical-literal pin surface.
17066        let mut s = three_member_spec();
17067        s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
17068        s.validate().unwrap();
17069    }
17070
17071    #[test]
17072    fn placement_strategy_variants_round_trip() {
17073        for s in [
17074            PlacementStrategy::SingleNode,
17075            PlacementStrategy::Replicated,
17076            PlacementStrategy::Sharded,
17077        ] {
17078            let p = Placement {
17079                estrategia: s,
17080                clusters: vec!["rio".into()],
17081                affinity: None,
17082                // Route the paired `:shard-key` fixture-builder through the
17083                // typed cross-slot invariant predicate
17084                // [`PlacementStrategy::requires_shard_key`] rather than the
17085                // [`gen_platform::IsVariant`]-derived [`Self::is_sharded`]
17086                // arm-identity predicate — the two answer the same
17087                // question under today's closed accept-set but a future
17088                // arm addition that consumed `:shard-key` under a
17089                // non-`Sharded` name would silently mis-attach the
17090                // fixture's `:shard-key` if the builder read through the
17091                // arm-identity predicate. The cross-slot-invariant
17092                // predicate migrates through one caixa-core edit on any
17093                // future arm addition; the fixture keeps producing a
17094                // `validate()`-passing round-trip by construction.
17095                shard_key: if s.requires_shard_key() {
17096                    Some("$key".into())
17097                } else {
17098                    None
17099                },
17100            };
17101            let json = serde_json::to_string(&p).unwrap();
17102            let back: Placement = serde_json::from_str(&json).unwrap();
17103            assert_eq!(back, p);
17104        }
17105    }
17106
17107    #[test]
17108    fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
17109        // The fail-before-pass-after pin: pre-lift there was no
17110        // single-source binding between the [`PlacementStrategy`]
17111        // variant name the `Serialize` derive emits and the byte-
17112        // string every downstream cluster-side dispatcher (the
17113        // `lareira-fleet-programs` aggregator's per-entry strategy
17114        // branch, the future `app-operator` reconciler, the M3
17115        // Adaptive compression pass's per-strategy weighting) probes
17116        // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
17117        // future `#[serde(rename_all = "kebab-case")]` attribute on
17118        // the enum — or a variant rename in the source — would
17119        // silently rebrand the emitted scalar under one spelling
17120        // while every downstream dispatcher still probed the other,
17121        // with the failure surfacing at the aggregator's dispatch
17122        // step or the operator's reconcile posture (workloads coming
17123        // up under the `default()` `Replicated` arm rather than the
17124        // typed slot's declared strategy) far from the source
17125        // rebrand commit and with no field naming the drift. Pinning
17126        // the two paths (the `Serialize` derive's serialized string
17127        // AND the [`PlacementStrategy::as_str`] helper) to the same
17128        // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
17129        // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
17130        // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
17131        // makes any future drift on either endpoint fail here at
17132        // caixa-core build time.
17133        for (variant, expected) in [
17134            (
17135                PlacementStrategy::SingleNode,
17136                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
17137            ),
17138            (
17139                PlacementStrategy::Replicated,
17140                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
17141            ),
17142            (
17143                PlacementStrategy::Sharded,
17144                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
17145            ),
17146        ] {
17147            let json = serde_json::to_string(&variant).unwrap();
17148            assert_eq!(
17149                json,
17150                format!("\"{expected}\""),
17151                "PlacementStrategy::{variant:?} must serialize to {expected:?}"
17152            );
17153            assert_eq!(
17154                variant.as_str(),
17155                expected,
17156                "PlacementStrategy::{variant:?}.as_str() must return the lifted \
17157                 M3_PLACEMENT_ESTRATEGIA_* constant"
17158            );
17159        }
17160    }
17161
17162    #[test]
17163    fn m3_placement_estrategia_consts_are_pairwise_distinct() {
17164        // Cross-arm drift-detection pin on the M3
17165        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
17166        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
17167        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
17168        // scalar-value pentad: a future collapse of two canonical
17169        // variant byte-strings onto the same value (an accidental
17170        // copy-paste flip of
17171        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
17172        // read `"SingleNode"`, a per-arm rebrand that lands one const
17173        // without touching its paired peer) would silently reroute
17174        // every downstream operator's per-strategy dispatch onto the
17175        // sibling arm's reconcile branch and pass every
17176        // propagation-probe test that expected only the stale arm's
17177        // value — a `Replicated`-declared Aplicacao would come up
17178        // under the `SingleNode` primary-and-standby reconcile
17179        // posture, so every-cluster active-active workload would
17180        // silently collapse onto one-cluster-runs-at-a-time takeover
17181        // semantics against its declared strategy, with no field
17182        // naming the strategy-value drift root cause. Peer of the
17183        // sibling
17184        // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
17185        // (09ffb2d) /
17186        // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
17187        // (ccdf955) /
17188        // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
17189        // (d739850) distinctness pins on the sibling OTP-shape /
17190        // caixa-kind closed-set typed-enum discriminator axes — the
17191        // fourth (and structurally the M3 mesh-primitive-defining)
17192        // closed-set typed-enum axis to converge on the same
17193        // "pairwise-distinct-by-construction" discipline.
17194        //
17195        // Fail-before-pass-after locally verified by mutating
17196        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
17197        // also read `"SingleNode"` — this pin fires as expected;
17198        // restoring passes.
17199        let all = [
17200            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
17201            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
17202            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
17203        ];
17204        for (i, a) in all.iter().enumerate() {
17205            for (j, b) in all.iter().enumerate() {
17206                if i != j {
17207                    assert_ne!(
17208                        a, b,
17209                        "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
17210                         distinct — got duplicate {a:?} at indices {i} and {j}",
17211                    );
17212                }
17213            }
17214        }
17215    }
17216
17217    #[test]
17218    fn placement_strategy_display_routes_through_as_str_helper() {
17219        // The fail-before-pass-after pin: pre-lift the sibling
17220        // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
17221        // / [`crate::supervisor::RestartPolicy`] both carried a stable
17222        // [`std::fmt::Display`] surface via their
17223        // `#[discriminant(also_display)]` gen-platform derive, but
17224        // [`PlacementStrategy`] did not — every consumer reaching for
17225        // a strategy byte-string past the wire format had to pick
17226        // between three paths ([`PlacementStrategy::as_str`], the
17227        // `Serialize` derive's serialized string, or `format!("{v:?}")`
17228        // on the `Debug` derive), any two of which a future variant
17229        // rename or `#[serde(rename_all = "kebab-case")]` attribute
17230        // would silently desynchronize. Wiring [`std::fmt::Display`]
17231        // through [`PlacementStrategy::as_str`] closes the third path:
17232        // every `format!("{v}")` call reaches the same lifted
17233        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
17234        // and the [`PlacementStrategy::as_str`] helper already route
17235        // through, so a future variant rename lands at exactly one
17236        // place. Pin the routing here so a future
17237        // `impl std::fmt::Display for PlacementStrategy` reimplementation
17238        // that hand-rolls the arms instead of delegating to
17239        // [`PlacementStrategy::as_str`] fails at caixa-core build time.
17240        for variant in [
17241            PlacementStrategy::SingleNode,
17242            PlacementStrategy::Replicated,
17243            PlacementStrategy::Sharded,
17244        ] {
17245            assert_eq!(
17246                variant.to_string(),
17247                variant.as_str(),
17248                "PlacementStrategy::{variant:?} Display must route through \
17249                 PlacementStrategy::as_str (single source of truth: the lifted \
17250                 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
17251            );
17252        }
17253    }
17254
17255    #[test]
17256    fn placement_strategy_display_matches_serialized_wire_byte_string() {
17257        // The fail-before-pass-after pin on the second half of the
17258        // three-path convergence: `Display` (user-facing text) agrees
17259        // byte-for-byte with the `Serialize` derive's wire format
17260        // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
17261        // scalar) on every variant. Pre-lift the two paths were
17262        // structurally independent — a future
17263        // `#[serde(rename_all = "kebab-case")]` attribute on the enum
17264        // would silently rebrand the emitted wire scalar
17265        // (`single-node`, `replicated`, `sharded`) while every consumer
17266        // that pretty-prints the strategy (the M3 diagnostic templates,
17267        // the future `feira app graph` per-Aplicacao strategy line,
17268        // the future M4 CR materializer's admission-webhook rejection
17269        // body) would still emit the TitleCase form the `as_str` /
17270        // `Display` route returns, with the mismatch surfacing at
17271        // consumer parse time / operator dispatch time far from the
17272        // source rebrand commit. Pin the two paths byte-for-byte here
17273        // so any future serde-attribute or variant-rename drift is a
17274        // caixa-core-build-time test failure at this call, not a
17275        // silent per-consumer dispatch miss.
17276        for variant in [
17277            PlacementStrategy::SingleNode,
17278            PlacementStrategy::Replicated,
17279            PlacementStrategy::Sharded,
17280        ] {
17281            let wire = serde_json::to_string(&variant).unwrap();
17282            // Strip the outer `"…"` the JSON string form carries — the
17283            // wire scalar the K8s / YAML apiserver consumes is the
17284            // enclosed byte-string, not the quote wrapper.
17285            let unquoted = wire
17286                .strip_prefix('"')
17287                .and_then(|s| s.strip_suffix('"'))
17288                .expect("serialized PlacementStrategy is a JSON string");
17289            assert_eq!(
17290                variant.to_string(),
17291                unquoted,
17292                "PlacementStrategy::{variant:?} Display byte-string must match the \
17293                 Serialize derive's wire byte-string (three-path convergence: \
17294                 Display + as_str + Serialize all resolve to the same \
17295                 M3_PLACEMENT_ESTRATEGIA_* const)"
17296            );
17297        }
17298    }
17299
17300    #[test]
17301    fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
17302        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
17303        // derive on [`PlacementStrategy`]: for each of the three variants
17304        // exactly one of the generated `is_single_node` / `is_replicated`
17305        // / `is_sharded` predicates returns `true` and the other two
17306        // return `false`. Prior to this derive the three per-arm
17307        // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
17308        // (the `placement_strategy_variants_round_trip` fixture, the
17309        // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
17310        // fixture, and the
17311        // `validate_placement_reads_through_lifted_estrategia_accessor`
17312        // fixture) each open-coded a per-arm PartialEq compare against
17313        // the enum variant — three sites that expressed no compile-time
17314        // link back to the closed-set typed dispatch a future fourth
17315        // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
17316        // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
17317        // would have to thread through in lockstep or one fixture would
17318        // silently disagree with the others on which arms consume the
17319        // `:shard-key` axis. Peer of the sibling
17320        // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
17321        // / [`crate::supervisor::RestartPolicy`] /
17322        // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
17323        // the sibling closed-set typed-enum discriminator axes — extends
17324        // the same one-typed-dispatch-per-variant discipline onto the
17325        // fifth (and only remaining) closed-set typed-enum discriminator
17326        // on the caixa surface, closing the axis on the M3 mesh-slot
17327        // family.
17328        let rows: [(PlacementStrategy, [bool; 3]); 3] = [
17329            (PlacementStrategy::SingleNode, [true, false, false]),
17330            (PlacementStrategy::Replicated, [false, true, false]),
17331            (PlacementStrategy::Sharded, [false, false, true]),
17332        ];
17333        for (variant, expected) in rows {
17334            let observed = [
17335                variant.is_single_node(),
17336                variant.is_replicated(),
17337                variant.is_sharded(),
17338            ];
17339            assert_eq!(
17340                observed, expected,
17341                "PlacementStrategy::{variant:?} is_* predicates must partition \
17342                 the arm set (single_node, replicated, sharded); got {observed:?}"
17343            );
17344        }
17345    }
17346
17347    #[test]
17348    fn placement_strategy_is_variant_predicates_are_const_fn() {
17349        // The [`gen_platform::IsVariant`] derive emits `const fn`
17350        // predicates on the peer [`crate::CaixaKind`] +
17351        // [`crate::upgrade::UpgradeInstruction`] +
17352        // [`crate::supervisor::RestartStrategy`] +
17353        // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
17354        // pin the same posture on [`PlacementStrategy`] so a future
17355        // accidental downgrade to non-`const` (an added runtime helper
17356        // reachable only from a non-`const` context, a manual hand-rolled
17357        // `impl` that shadows the derive-generated method) trips at
17358        // caixa-core build time rather than surfacing as a downstream
17359        // `const`-context regression far from the derive declaration.
17360        //
17361        // The pin lives inside a `const { assert!(..) }` block so the
17362        // compiler enforces both halves (arm predicate is `const`-
17363        // callable AND returns `true` for the matching arm) at
17364        // caixa-core compile time — peer to the sibling
17365        // [`crate::CaixaKind::is_*`] + [`WitTarget::is_*`] const-block
17366        // pins on the closed-set typed enum arm-predicate const-
17367        // callability axis.
17368        const {
17369            assert!(PlacementStrategy::SingleNode.is_single_node());
17370            assert!(PlacementStrategy::Replicated.is_replicated());
17371            assert!(PlacementStrategy::Sharded.is_sharded());
17372        }
17373    }
17374
17375    #[test]
17376    fn placement_strategy_requires_shard_key_partitions_the_arm_set() {
17377        // Fail-before-pass-after pin on the substrate-lifted
17378        // [`PlacementStrategy::requires_shard_key`] cross-slot-invariant
17379        // per-arm predicate: for each variant in the closed accept-set the
17380        // predicate returns `true` iff the variant consumes the paired
17381        // [`Placement::shard_key`] axis under
17382        // [`AplicacaoSpec::validate_placement`]'s `Sharded` ↔ non-`Sharded`
17383        // partition. Today the accept-set is the singleton `{Sharded}` —
17384        // `Sharded` is the Akka-style hash-keyed distribution arm
17385        // (MESH-COMPOSITION §II.4), `SingleNode` (Erlang/OTP takeover —
17386        // §II.1) and `Replicated` (active-active) refuse the axis through
17387        // [`AplicacaoError::ShardKeyOnNonSharded`].
17388        //
17389        // Pins the per-arm truth-table so a future arm addition (an
17390        // `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint the
17391        // roadmap names, a `WeightedShard` promotion the future M5
17392        // adaptive-placement engine acknowledges) that landed a variant
17393        // without extending this predicate's arm-set would surface as a
17394        // caixa-core build-time exhaustiveness error at the
17395        // `match self { … }` arm-fan below rather than a silent per-consumer
17396        // mis-classification at renderer emit time. The paired
17397        // [`Self::is_sharded`] `gen_platform::IsVariant`-derived arm-identity
17398        // predicate stays a distinct question — arm-identity (which the
17399        // sibling
17400        // [`placement_strategy_is_variant_predicates_partition_the_arm_set`]
17401        // pin already locks) is not cross-slot-invariant consumption; today
17402        // they trip on the same singleton but the pair migrates through
17403        // one caixa-core edit on any future arm addition.
17404        //
17405        // Peer of the sibling per-arm classifier pins
17406        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
17407        // (7b97d26) on the [`WitContract`] pre-projection WIT-shape axis
17408        // and the [`WitTarget::is_capability`] `gen_platform::IsVariant`-
17409        // derived paired predicate on the post-projection typed-view axis
17410        // — same "per-arm semantic-classification predicate paired with
17411        // the arm-identity predicate the derive already emits" discipline
17412        // extended onto the M3 mesh-slot `:placement :estrategia` ↔
17413        // `:placement :shard-key` cross-slot-invariant axis.
17414        let rows: [(PlacementStrategy, bool); 3] = [
17415            (PlacementStrategy::SingleNode, false),
17416            (PlacementStrategy::Replicated, false),
17417            (PlacementStrategy::Sharded, true),
17418        ];
17419        for (variant, expected) in rows {
17420            assert_eq!(
17421                variant.requires_shard_key(),
17422                expected,
17423                "PlacementStrategy::{variant:?}.requires_shard_key() must \
17424                 be {expected} (the substrate-canonical cross-slot invariant \
17425                 on the :placement :shard-key axis; today `Sharded` is the \
17426                 singleton consuming arm — MESH-COMPOSITION §II.4)",
17427            );
17428        }
17429    }
17430
17431    #[test]
17432    fn placement_strategy_requires_shard_key_is_const_fn() {
17433        // The [`PlacementStrategy::requires_shard_key`] cross-slot-
17434        // invariant per-arm predicate is declared `#[must_use] pub const
17435        // fn` — pin the `const`-eval posture here so a future accidental
17436        // downgrade to non-`const` (an added runtime helper reachable
17437        // only from a non-`const` context, a manual hand-rolled `impl`
17438        // that shadows the current three-arm `match self { … }` dispatch)
17439        // trips at caixa-core build time rather than surfacing as a
17440        // downstream `const`-context regression far from the declaration.
17441        // Same shape as the sibling
17442        // [`placement_strategy_is_variant_predicates_are_const_fn`] pin on
17443        // the peer [`gen_platform::IsVariant`]-derived arm-identity
17444        // predicate axis, but here the load-bearing assertions live in
17445        // module-scope `const _: () = assert!(…)` items so a violation
17446        // fails at compile time (const-eval trip) rather than test time —
17447        // strictly stronger than the runtime `assert!(CONST)` pattern the
17448        // sibling pin uses, and side-steps the
17449        // `clippy::assertions_on_constants` lint the runtime pattern
17450        // otherwise accumulates on the module baseline.
17451        //
17452        // The test body simply witnesses that the module-scope items
17453        // compiled and the runtime dispatch agrees with the const-eval
17454        // dispatch on every arm — the runtime read gives the test a
17455        // failure surface (rather than an empty test body clippy would
17456        // flag as a no-op).
17457        const REQUIRES_SINGLE_NODE: bool = PlacementStrategy::SingleNode.requires_shard_key();
17458        const REQUIRES_REPLICATED: bool = PlacementStrategy::Replicated.requires_shard_key();
17459        const REQUIRES_SHARDED: bool = PlacementStrategy::Sharded.requires_shard_key();
17460        assert_eq!(
17461            [REQUIRES_SINGLE_NODE, REQUIRES_REPLICATED, REQUIRES_SHARDED,],
17462            [
17463                PlacementStrategy::SingleNode.requires_shard_key(),
17464                PlacementStrategy::Replicated.requires_shard_key(),
17465                PlacementStrategy::Sharded.requires_shard_key(),
17466            ],
17467            "runtime and const-eval dispatch on \
17468             PlacementStrategy::requires_shard_key must agree on every arm",
17469        );
17470    }
17471
17472    #[test]
17473    fn placement_estrategia_accessor_is_const_fn() {
17474        // The [`Placement::estrategia`] per-`:placement` distribution-
17475        // strategy `Copy`-return scalar accessor is declared
17476        // `#[must_use] pub const fn` — matching the peer M3 mesh-slot
17477        // `Copy`-return accessor family ([`MeshPolicy::timeout`] /
17478        // [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
17479        // [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`]
17480        // on the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`]
17481        // / [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
17482        // [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
17483        // [`RateLimit`], every one a `pub const fn`). Pin the
17484        // `const`-eval posture here so a future accidental downgrade to
17485        // non-`const` (an added runtime helper reachable only from a
17486        // non-`const` context, a slot promotion to a non-`Copy` return
17487        // that would silently drop the `const` qualifier, a manual
17488        // hand-rolled shadow) trips at caixa-core build time rather
17489        // than surfacing as a downstream `const`-context regression far
17490        // from the declaration.
17491        //
17492        // Same shape as the sibling
17493        // [`placement_strategy_requires_shard_key_is_const_fn`] pin on
17494        // the peer [`PlacementStrategy::requires_shard_key`] `const fn`
17495        // predicate axis — the load-bearing witness lives in the
17496        // module-scope `const fn` wrapper `estrategia_via_const_fn`
17497        // below: a body that calls [`Placement::estrategia`] under a
17498        // `const fn` signature is well-formed only when the callee is
17499        // itself `const fn`, so any future accidental downgrade of
17500        // [`Placement::estrategia`] to non-`const` fails at caixa-core
17501        // build time (const-eval E0015 / E0658 depending on the arm),
17502        // strictly stronger than a runtime `assert!(CONST)` and
17503        // side-stepping the destructor-in-const restriction that
17504        // blocks direct `const _: PlacementStrategy = FIXTURE.estrategia()`
17505        // items on `Placement`'s `Vec<String>` / `Option<String>`
17506        // carriers.
17507        //
17508        // The runtime body witnesses that the const-eval-shaped
17509        // wrapper agrees with a direct call on every closed-set arm.
17510        const fn estrategia_via_const_fn(p: &Placement) -> PlacementStrategy {
17511            p.estrategia()
17512        }
17513        for estrategia in [
17514            PlacementStrategy::SingleNode,
17515            PlacementStrategy::Replicated,
17516            PlacementStrategy::Sharded,
17517        ] {
17518            let placement = Placement {
17519                estrategia,
17520                clusters: Vec::new(),
17521                affinity: None,
17522                shard_key: None,
17523            };
17524            assert_eq!(
17525                estrategia_via_const_fn(&placement),
17526                placement.estrategia(),
17527                "const-fn-wrapped and direct dispatch on \
17528                 Placement::estrategia must agree for {estrategia:?}",
17529            );
17530        }
17531    }
17532
17533    #[test]
17534    fn entrada_port_accessor_is_const_fn() {
17535        // The [`Entrada::port`] per-`:entrada` L4-port `Copy`-return
17536        // scalar accessor is declared `#[must_use] pub const fn` —
17537        // matching the peer M3 mesh-slot `Copy`-return accessor family
17538        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`] /
17539        // [`MeshPolicy::mtls_required`] / [`MeshPolicy::rate_limit`] /
17540        // [`MeshPolicy::circuit_breaker`] on the parent [`MeshPolicy`],
17541        // [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
17542        // on the sibling [`CircuitBreaker`], [`RateLimit::rate`] /
17543        // [`RateLimit::window`] on the sibling [`RateLimit`], the
17544        // sibling per-`:placement` [`Placement::estrategia`] pinned by
17545        // [`placement_estrategia_accessor_is_const_fn`] above — every
17546        // one a `pub const fn`). Pin the `const`-eval posture here so
17547        // a future accidental downgrade to non-`const` (an added
17548        // runtime helper reachable only from a non-`const` context, an
17549        // `Option<u16>`-shape migration once the substrate grows
17550        // per-`:membros` heterogeneous listener ports that would
17551        // silently drop the `const` qualifier, a manual hand-rolled
17552        // shadow) trips at caixa-core build time rather than surfacing
17553        // as a downstream `const`-context regression far from the
17554        // declaration.
17555        //
17556        // Same shape as the sibling
17557        // [`placement_estrategia_accessor_is_const_fn`] pin above — the
17558        // load-bearing witness lives in the module-scope `const fn`
17559        // wrapper `port_via_const_fn`: a body that calls
17560        // [`Entrada::port`] under a `const fn` signature is well-formed
17561        // only when the callee is itself `const fn`, side-stepping the
17562        // destructor-in-const restriction that would otherwise block a
17563        // direct `const _: u16 = FIXTURE.port()` item on `Entrada`'s
17564        // `String` / `Vec<String>` carriers.
17565        //
17566        // The runtime body sweeps a representative port set spanning
17567        // the [`SERVICO_PORT_MIN`] floor, the substrate-canonical
17568        // [`DEFAULT_SERVICO_PORT`] default, and the top-edge `u16::MAX`
17569        // ceiling — the const-fn-wrapped call must agree with a direct
17570        // call on every fixture (a violation trips the test) and every
17571        // returned scalar must byte-equal the input `port` (a violation
17572        // means the accessor stopped being a raw field-return copy).
17573        const fn port_via_const_fn(e: &Entrada) -> u16 {
17574            e.port()
17575        }
17576        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, u16::MAX] {
17577            let entrada = Entrada {
17578                host: String::new(),
17579                para: String::new(),
17580                port,
17581                paths: Vec::new(),
17582            };
17583            assert_eq!(
17584                port_via_const_fn(&entrada),
17585                entrada.port(),
17586                "const-fn-wrapped and direct dispatch on Entrada::port \
17587                 must agree for port={port}",
17588            );
17589            assert_eq!(
17590                entrada.port(),
17591                port,
17592                "Entrada::port must return the storage-side u16 verbatim \
17593                 for port={port}",
17594            );
17595        }
17596    }
17597
17598    #[test]
17599    fn validate_placement_admits_paired_shape_iff_strategy_requires_shard_key() {
17600        // Load-bearing cross-slot-partition pin closing the loop between
17601        // the substrate-lifted
17602        // [`PlacementStrategy::requires_shard_key`] per-arm predicate on
17603        // the closed-set typed enum and the actual
17604        // [`AplicacaoSpec::validate_placement`] runtime behavior across
17605        // the paired `:placement :shard-key` axis: every validated
17606        // [`Placement`] past [`AplicacaoSpec::validate_placement`]
17607        // satisfies `placement.shard_key().is_some() ==
17608        // placement.estrategia().requires_shard_key()`. The four-cell
17609        // shape witness sweeps every combination of (variant in the
17610        // closed accept-set, `:shard-key` Some/None) and pins:
17611        //
17612        //   * variant.requires_shard_key() && shard_key.is_some() →
17613        //     validate() passes; the paired shape is the sole
17614        //     `requires_shard_key` arm-family accepted shape.
17615        //   * variant.requires_shard_key() && shard_key.is_none() →
17616        //     validate() fails with [`AplicacaoError::ShardedWithoutKey`];
17617        //     the paired shape is the refused missing-key shape on
17618        //     Sharded-family arms.
17619        //   * !variant.requires_shard_key() && shard_key.is_some() →
17620        //     validate() fails with
17621        //     [`AplicacaoError::ShardKeyOnNonSharded`]; the paired shape
17622        //     is the refused declared-but-inert shape on non-Sharded-
17623        //     family arms.
17624        //   * !variant.requires_shard_key() && shard_key.is_none() →
17625        //     validate() passes; the paired shape is the sole
17626        //     non-`requires_shard_key` arm-family accepted shape.
17627        //
17628        // The compile-time-exhaustive `match p.estrategia()` dispatch at
17629        // [`AplicacaoSpec::validate_placement`] preserves its structural
17630        // arm-fan (a future arm addition still surfaces a build-time
17631        // exhaustiveness error there); this pin closes the semantic loop
17632        // between the arm-fan's shape-gate cascades and the substrate-
17633        // canonical predicate every downstream consumer of the paired
17634        // shape reads through. Fail-before-pass-after locally verified by
17635        // mutating the predicate's `Sharded => true` arm to `false` — the
17636        // truthy `expects_ok` cell for `Sharded` + `Some` trips the
17637        // `validate() must pass` assertion; restoring passes. Same "close
17638        // the loop between the typed predicate and the runtime behavior"
17639        // discipline as the sibling
17640        // [`wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant`]
17641        // (7b97d26) cross-projection pin on the peer [`WitTarget`]
17642        // per-arm classifier axis.
17643        for variant in [
17644            PlacementStrategy::SingleNode,
17645            PlacementStrategy::Replicated,
17646            PlacementStrategy::Sharded,
17647        ] {
17648            for present in [false, true] {
17649                let mut spec = three_member_spec();
17650                spec.placement.estrategia = variant;
17651                spec.placement.shard_key = present.then(|| "tenantId".into());
17652                let expects_ok = variant.requires_shard_key() == present;
17653                let result = spec.validate();
17654                match (expects_ok, &result) {
17655                    (true, Ok(())) => {}
17656                    (false, Err(err)) => {
17657                        // Cross-check the refusal diagnostic names the
17658                        // right cell of the four-cell shape witness — the
17659                        // `requires_shard_key && !present` cell must trip
17660                        // [`AplicacaoError::ShardedWithoutKey`]; the
17661                        // `!requires_shard_key && present` cell must trip
17662                        // [`AplicacaoError::ShardKeyOnNonSharded`].
17663                        match (variant.requires_shard_key(), present, err) {
17664                            (true, false, AplicacaoError::ShardedWithoutKey) => {}
17665                            (
17666                                false,
17667                                true,
17668                                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. },
17669                            ) => {
17670                                assert_eq!(
17671                                    *e, variant,
17672                                    "ShardKeyOnNonSharded.estrategia must byte-equal \
17673                                     the paired PlacementStrategy",
17674                                );
17675                            }
17676                            _ => panic!(
17677                                "unexpected refusal for estrategia={variant:?} \
17678                                 present={present}: {err:?}"
17679                            ),
17680                        }
17681                    }
17682                    (true, Err(err)) => panic!(
17683                        "validate() must pass for estrategia={variant:?} \
17684                         present={present} (requires_shard_key={} == present={present}), \
17685                         got {err:?}",
17686                        variant.requires_shard_key(),
17687                    ),
17688                    (false, Ok(())) => panic!(
17689                        "validate() must fail for estrategia={variant:?} \
17690                         present={present} (requires_shard_key={} != present={present})",
17691                        variant.requires_shard_key(),
17692                    ),
17693                }
17694            }
17695        }
17696    }
17697
17698    #[test]
17699    fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
17700        // Pin the M3 diagnostic template routes through the typed
17701        // [`PlacementStrategy`] Display byte-string (rebound from the
17702        // prior `{estrategia:?}` `Debug` route). Pre-lift the two
17703        // routes emitted identical bytes (the `Debug` derive on a
17704        // unit variant emits the variant name verbatim, exactly what
17705        // `as_str` returns), but the two paths were structurally
17706        // independent — a future `#[serde(rename_all = "…")]`
17707        // attribute or variant rename would coordinate the wire /
17708        // `Display` / `as_str` triple through the lifted const but
17709        // leave the `Debug` route on the compiler-derived variant name,
17710        // silently desynchronizing the diagnostic byte-string from the
17711        // wire byte-string. Rebinding the template onto `Display`
17712        // ties the diagnostic to the same lifted
17713        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
17714        // emits — drift becomes structurally impossible. Pin the
17715        // byte-string here so a future edit that reverts the template
17716        // to `{estrategia:?}` is caught at caixa-core test time, not
17717        // at consumer dispatch time.
17718        for (variant, expected_scalar) in [
17719            (
17720                PlacementStrategy::SingleNode,
17721                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
17722            ),
17723            (
17724                PlacementStrategy::Replicated,
17725                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
17726            ),
17727            (
17728                PlacementStrategy::Sharded,
17729                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
17730            ),
17731        ] {
17732            let err = AplicacaoError::PlacementWithoutClusters {
17733                estrategia: variant,
17734            };
17735            let msg = err.to_string();
17736            assert!(
17737                msg.starts_with(&format!(":placement {expected_scalar} requires")),
17738                "PlacementWithoutClusters diagnostic for {variant:?} must open \
17739                 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
17740            );
17741        }
17742    }
17743
17744    #[test]
17745    fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
17746        // Peer of
17747        // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
17748        // on the second M3 diagnostic that carries the typed
17749        // [`PlacementStrategy`] in its `#[error(…)]` template. Both
17750        // diagnostics now route the strategy scalar through the same
17751        // [`std::fmt::Display`] surface, tying the diagnostic
17752        // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
17753        // const set the wire format also emits. The two non-Sharded
17754        // arms are exercised here (the diagnostic exists to flag a
17755        // `:shard-key` slot the current strategy will never consume);
17756        // the peer `Sharded` arm never reaches this diagnostic (the
17757        // `Sharded` strategy consumes `:shard-key` — the
17758        // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
17759        // slot instead).
17760        for (variant, expected_scalar) in [
17761            (
17762                PlacementStrategy::SingleNode,
17763                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
17764            ),
17765            (
17766                PlacementStrategy::Replicated,
17767                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
17768            ),
17769        ] {
17770            let err = AplicacaoError::ShardKeyOnNonSharded {
17771                estrategia: variant,
17772                shard_key: "$tenantId".into(),
17773            };
17774            let msg = err.to_string();
17775            assert!(
17776                msg.starts_with(&format!(":placement {expected_scalar} carries")),
17777                "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
17778                 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
17779            );
17780        }
17781    }
17782
17783    #[test]
17784    fn placement_strategy_all_enumerates_every_variant_once() {
17785        // Fail-before-pass-after pin on the [`PlacementStrategy::ALL`]
17786        // exhaustive-iteration surface: every variant appears exactly
17787        // once, and the slice length matches the arm count of the
17788        // closed set. Every consumer that walks the accepted-strategy
17789        // set (a future `feira app placement --list` CLI-side surfacing,
17790        // a future M4 admission-webhook's rejection body naming the
17791        // accepted-strategy list, the [`PlacementStrategy::from_wire`]
17792        // reverse-projection consumers that iterate the accept-set for
17793        // a "did you mean" hint) reads through this slice, so a future
17794        // variant addition (an `Anycast` mesh-anycast arm the
17795        // MESH-COMPOSITION §II.5 hint names as a trajectory item) that
17796        // grows the enum but forgets to grow [`Self::ALL`] silently
17797        // truncates every downstream consumer's accept-set at the same
17798        // pre-addition boundary — this pin fails at caixa-core build
17799        // time on the pairwise-distinct + arm-count invariants.
17800        //
17801        // Peer of the sibling [`RateLimitUnit::ALL`] (6bce03d) /
17802        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
17803        // pins on the peer closed-set typed-enum axes.
17804        let all: &[PlacementStrategy] = PlacementStrategy::ALL;
17805        assert_eq!(
17806            all.len(),
17807            3,
17808            "PlacementStrategy::ALL must enumerate every variant of the \
17809             three-arm closed set (SingleNode, Replicated, Sharded); got {all:?}"
17810        );
17811        for (i, a) in all.iter().enumerate() {
17812            for (j, b) in all.iter().enumerate() {
17813                if i != j {
17814                    assert_ne!(
17815                        a, b,
17816                        "PlacementStrategy::ALL must carry every variant exactly \
17817                         once — got duplicate {a:?} at indices {i} and {j}"
17818                    );
17819                }
17820            }
17821        }
17822        for variant in [
17823            PlacementStrategy::SingleNode,
17824            PlacementStrategy::Replicated,
17825            PlacementStrategy::Sharded,
17826        ] {
17827            assert!(
17828                all.contains(&variant),
17829                "PlacementStrategy::ALL must contain {variant:?} — a future variant \
17830                 addition that grows the enum but forgets to grow the ALL slice \
17831                 silently truncates every downstream consumer's accept-set at the \
17832                 pre-addition boundary"
17833            );
17834        }
17835    }
17836
17837    #[test]
17838    fn placement_strategy_from_wire_accepts_every_lifted_constant() {
17839        // Fail-before-pass-after pin on the forward accept-set of the
17840        // [`PlacementStrategy::from_wire`] reverse projection: every
17841        // canonical [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
17842        // constant the [`PlacementStrategy::as_str`] emitter walks
17843        // parses back to its paired variant. Any future arm addition
17844        // that grows the emitter's `as_str` match but forgets to grow
17845        // the parser's `from_str` match silently splits the two halves
17846        // of the round-trip — the wire byte-string one non-serde
17847        // consumer parses from the one the emitter wrote — with the
17848        // failure surfacing at parse time far from the rebrand commit.
17849        // Pinning the three-arm accept-set here catches the drift at
17850        // caixa-core build time.
17851        //
17852        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
17853        // + [`RateLimitUnit::from_suffix`] accept-set pins on the peer
17854        // closed-set typed-enum `str → Self` axes.
17855        for (wire, expected) in [
17856            (
17857                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
17858                PlacementStrategy::SingleNode,
17859            ),
17860            (
17861                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
17862                PlacementStrategy::Replicated,
17863            ),
17864            (
17865                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
17866                PlacementStrategy::Sharded,
17867            ),
17868        ] {
17869            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
17870                panic!(
17871                    "PlacementStrategy::from_wire({wire:?}) must accept every \
17872                     M3_PLACEMENT_ESTRATEGIA_* constant — got None for the \
17873                     lifted canonical byte-string that PlacementStrategy::{expected:?} \
17874                     serializes as under M3_PLACEMENT_KEY_ESTRATEGIA"
17875                )
17876            });
17877            assert_eq!(
17878                parsed, expected,
17879                "PlacementStrategy::from_wire({wire:?}) must return \
17880                 PlacementStrategy::{expected:?}; got PlacementStrategy::{parsed:?}"
17881            );
17882        }
17883    }
17884
17885    #[test]
17886    fn placement_strategy_from_wire_round_trips_through_as_str() {
17887        // Fail-before-pass-after pin on the closed round-trip between
17888        // the forward [`PlacementStrategy::as_str`] emitter and the
17889        // reverse [`PlacementStrategy::from_wire`] parser: for every
17890        // variant in [`PlacementStrategy::ALL`], parsing the emitter's
17891        // output must return exactly the same variant. Any per-arm
17892        // divergence — a future arm added to `as_str` but not
17893        // `from_str`, an accidental copy-paste flip in one but not the
17894        // other — silently splits the emit and parse halves and the
17895        // failure surfaces at consumer parse time far from the drift
17896        // site. The `ALL`-iterating shape means a future variant
17897        // addition picks up the coverage by construction.
17898        //
17899        // Peer of the sibling [`crate::kind::tests`] round-trip pin on
17900        // [`crate::CaixaKind::from_wire`] and the
17901        // [`super::tests::rate_limit_unit_from_suffix_round_trips_through_as_suffix`]
17902        // sibling round-trip pin on [`RateLimitUnit`].
17903        for &variant in PlacementStrategy::ALL {
17904            let wire = variant.as_str();
17905            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
17906                panic!(
17907                    "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
17908                     must be Some({variant:?}) — the two halves of the round-trip \
17909                     dispatch on the same lifted M3_PLACEMENT_ESTRATEGIA_* consts; \
17910                     got None on wire byte-string {wire:?}"
17911                )
17912            });
17913            assert_eq!(
17914                parsed, variant,
17915                "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
17916                 must round-trip to the same variant; got {parsed:?}"
17917            );
17918        }
17919    }
17920
17921    #[test]
17922    fn placement_strategy_from_wire_rejects_unknown_byte_strings() {
17923        // Fail-before-pass-after pin on the closed-set refusal
17924        // discipline of [`PlacementStrategy::from_wire`]: every
17925        // byte-string outside the three-arm accept-set returns `None`
17926        // rather than silently collapsing onto the [`Default`]
17927        // (`Replicated`) arm or an arbitrary neighbor. The refusal set
17928        // exercised here sweeps the load-bearing drift shapes: the
17929        // empty string (a stripped serde-attribute drift), an all-
17930        // whitespace string (the canonical text-editor accidental
17931        // padding shape), the lowercased kebab-case forms a future
17932        // `#[serde(rename_all = "kebab-case")]` attribute would emit
17933        // (`"single-node"`, `"replicated"`, `"sharded"` — the last two
17934        // coincidentally match the accepted canonical scalars, so only
17935        // `"single-node"` fires as a refusal, but pinning the case-
17936        // sensitivity of the accepted arms via the peer [`SingleNode`]
17937        // assertion in the round-trip pin makes the discipline
17938        // structurally clear), the lowercased single-word forms
17939        // (`"singlenode"`), the padded canonical scalar
17940        // (`" Sharded "`), the trailing-comma / trailing-newline shapes
17941        // (`"Sharded\n"`), and a pointer-different `&'static str` that
17942        // happens to alias a canonical byte-string by content but not
17943        // by identity (validated implicitly by the emitter's routing
17944        // through `crate::render::M3_PLACEMENT_ESTRATEGIA_*`, whose
17945        // identity a paired [`crate::assert_str_reexport_identity`] pin
17946        // in caixa-core's per-const declaration surface would catch).
17947        //
17948        // Peer of the sibling
17949        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
17950        // (2aa6d23) refusal pin on [`crate::CaixaKind::from_wire`].
17951        for bad in [
17952            "",
17953            " ",
17954            "\n",
17955            "\t",
17956            "single-node",
17957            "singlenode",
17958            "SingleNodes",
17959            "single_node",
17960            "single node",
17961            "SINGLENODE",
17962            "SingleNode ",
17963            " SingleNode",
17964            " Sharded ",
17965            "Sharded\n",
17966            "replicated ",
17967            "sharded",
17968            "REPLICATED",
17969            "Anycast",
17970            "Global",
17971            "?",
17972        ] {
17973            assert!(
17974                PlacementStrategy::from_wire(bad).is_none(),
17975                "PlacementStrategy::from_wire({bad:?}) must return None — the \
17976                 parser's accept-set is exactly the three PlacementStrategy::as_str \
17977                 outputs (SingleNode, Replicated, Sharded), and this byte-string \
17978                 is outside that closed set"
17979            );
17980        }
17981    }
17982
17983    #[test]
17984    fn placement_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
17985        // Fail-before-pass-after pin on the third path of the four-path
17986        // convergence: `from_str` (the reverse projection) inverts the
17987        // `Serialize` derive's wire byte-string on every variant.
17988        // Together with the pre-existing three-path convergence
17989        // (`Display` + `as_str` + `Serialize` all resolve to the same
17990        // lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const, pinned by
17991        // the peer
17992        // [`placement_strategy_display_matches_serialized_wire_byte_string`])
17993        // this closes the round-trip: the wire byte-string the
17994        // `Serialize` derive emits parses back to the same variant
17995        // through `from_str`, so any future serde-attribute or variant-
17996        // rename drift on the emit half now surfaces as a matched drift
17997        // on the parse half at caixa-core build time — the two halves
17998        // migrate as a unit through the lifted consts on any future
17999        // rename, and the round-trip cannot silently split.
18000        //
18001        // Peer of the sibling
18002        // [`placement_strategy_display_matches_serialized_wire_byte_string`]
18003        // wire-format pin — extends the three-path convergence
18004        // (`Display` + `as_str` + `Serialize`) onto the fourth path
18005        // (`from_str`), closing the `str ↔ Self` round-trip on the
18006        // M3 `:placement :estrategia` closed-set axis.
18007        for &variant in PlacementStrategy::ALL {
18008            let wire = serde_json::to_string(&variant).unwrap();
18009            let unquoted = wire
18010                .strip_prefix('"')
18011                .and_then(|s| s.strip_suffix('"'))
18012                .expect("serialized PlacementStrategy is a JSON string");
18013            let parsed = PlacementStrategy::from_wire(unquoted).unwrap_or_else(|| {
18014                panic!(
18015                    "PlacementStrategy::from_wire({unquoted:?}) must accept the \
18016                     Serialize derive's wire byte-string for \
18017                     PlacementStrategy::{variant:?} — the four-path convergence \
18018                     (Display + as_str + Serialize + from_str) resolves through \
18019                     the same lifted M3_PLACEMENT_ESTRATEGIA_* const; got None"
18020                )
18021            });
18022            assert_eq!(
18023                parsed, variant,
18024                "PlacementStrategy::from_wire of the Serialize derive's wire \
18025                 byte-string for PlacementStrategy::{variant:?} must round-trip \
18026                 to the same variant; got {parsed:?}"
18027            );
18028        }
18029    }
18030
18031    #[test]
18032    fn rejects_zero_policy_timeout() {
18033        let mut s = three_member_spec();
18034        s.politicas.timeout = Some(Duration::ZERO);
18035        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
18036    }
18037
18038    #[test]
18039    fn rejects_zero_policy_retries() {
18040        let mut s = three_member_spec();
18041        s.politicas.retries = Some(0);
18042        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
18043    }
18044
18045    #[test]
18046    fn rejects_policy_retries_above_cap() {
18047        // The fail-before-pass-after pin: `Some(11)` is structurally
18048        // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
18049        // passed validate on every pre-gate codebase because the
18050        // typed slot's only check was the zero-floor arm. The
18051        // thundering-herd amplification vector only surfaced at the
18052        // runtime substrate (Envoy / Cilium L7 retry overlay)
18053        // far from the source caixa.lisp with no field naming the
18054        // offending policy.
18055        let mut s = three_member_spec();
18056        s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
18057        assert_eq!(
18058            s.validate().unwrap_err(),
18059            AplicacaoError::PolicyRetriesExceedsCap {
18060                retries: POLICY_RETRIES_MAX + 1
18061            }
18062        );
18063    }
18064
18065    #[test]
18066    fn rejects_policy_retries_far_above_cap() {
18067        // The `u32::MAX` worst case — the four-billion-retry policy
18068        // a typo (`(:retries 4294967295)`) or struct-literal
18069        // copy-paste lands in the slot. Pin the cap arm's coverage
18070        // explicitly across the full `u32` overflow so a future
18071        // relaxation that drops the upper bound surfaces here.
18072        let mut s = three_member_spec();
18073        s.politicas.retries = Some(u32::MAX);
18074        assert_eq!(
18075            s.validate().unwrap_err(),
18076            AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
18077        );
18078    }
18079
18080    #[test]
18081    fn accepts_policy_retries_at_cap() {
18082        // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
18083        // must validate. The cap is inclusive on the top edge,
18084        // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
18085        // discipline on the sibling [`crate::LimitsSpec::memory`]
18086        // axis. Pin the boundary explicitly so a future off-by-one
18087        // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
18088        // surfaces here as a test failure rather than a silent
18089        // contract narrowing.
18090        let mut s = three_member_spec();
18091        s.politicas.retries = Some(POLICY_RETRIES_MAX);
18092        s.validate()
18093            .expect("retries == POLICY_RETRIES_MAX must validate");
18094    }
18095
18096    #[test]
18097    fn accepts_policy_retries_typical_values() {
18098        // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
18099        // every value in the validated set must pass. The
18100        // Envoy / Istio production-playbook recommendation band
18101        // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
18102        // (`maxRetries ≤ 10`) both lie within this set.
18103        for r in 1..=POLICY_RETRIES_MAX {
18104            let mut s = three_member_spec();
18105            s.politicas.retries = Some(r);
18106            s.validate()
18107                .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
18108        }
18109    }
18110
18111    #[test]
18112    fn policy_retries_zero_takes_precedence_over_cap() {
18113        // The cross-arm ordering pin: `Some(0)` is structurally
18114        // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
18115        // (cap), but the zero-floor diagnostic is the more
18116        // self-locating one (it directly names the omit-axis
18117        // remediation), so the validate gate must fire on zero
18118        // first. Pin the order so a future refactor that reorders
18119        // the arms surfaces here as a test failure rather than a
18120        // silent diagnostic regression. Same shape every other
18121        // zero-then-shape ordering on this surface uses
18122        // ([`AplicacaoError::PolicyTimeoutZero`] then
18123        // [`AplicacaoError::PolicyTimeoutNotCanonical`];
18124        // [`AplicacaoError::PolicyBreakerZeroWindow`] then
18125        // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
18126        let mut s = three_member_spec();
18127        s.politicas.retries = Some(0);
18128        assert_eq!(
18129            s.validate().unwrap_err(),
18130            AplicacaoError::PolicyRetriesZero,
18131            "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
18132        );
18133    }
18134
18135    #[test]
18136    fn policy_retries_cap_diagnostic_carries_offending_value() {
18137        // The diagnostic-shape pin: the offending `u32` is carried
18138        // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
18139        // variant so the surfaced error message names the value the
18140        // author wrote (`":politicas :retries (47) exceeds the
18141        // mesh-policy ceiling …"`), not just the cap. Same
18142        // self-locating diagnostic shape every other typed-cap arm
18143        // on this surface carries
18144        // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
18145        // offending byte count verbatim).
18146        let mut s = three_member_spec();
18147        s.politicas.retries = Some(47);
18148        let err = s.validate().unwrap_err();
18149        assert!(
18150            matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
18151            "got {err:?}"
18152        );
18153        let msg = err.to_string();
18154        assert!(
18155            msg.contains("47"),
18156            ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
18157        );
18158    }
18159
18160    #[test]
18161    fn policy_retries_cap_is_aws_app_mesh_aligned() {
18162        // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
18163        // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
18164        // schema cap — the only upstream mesh-policy schema that
18165        // documents an explicit hard cap. Pinning the literal value
18166        // here surfaces a future drift (a relaxation to 20, a
18167        // tightening to 5) as a deliberate test edit, not a silent
18168        // contract narrowing.
18169        assert_eq!(POLICY_RETRIES_MAX, 10);
18170    }
18171
18172    #[test]
18173    fn rejects_circuit_breaker_zero_max_failures() {
18174        let mut s = three_member_spec();
18175        s.politicas.circuit_breaker = Some(CircuitBreaker {
18176            max_failures: 0,
18177            window: Duration::from_secs(60),
18178        });
18179        assert_eq!(
18180            s.validate().unwrap_err(),
18181            AplicacaoError::PolicyBreakerZeroFailures
18182        );
18183    }
18184
18185    #[test]
18186    fn rejects_circuit_breaker_max_failures_above_cap() {
18187        // The fail-before-pass-after pin: `1001` is structurally one
18188        // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
18189        // silently passed validate on every pre-gate codebase
18190        // because the typed slot's only check was the zero-floor
18191        // arm. The breaker-no-op vector only surfaced at the runtime
18192        // substrate (Envoy / Cilium L7 outlier-detection overlay)
18193        // far from the source caixa.lisp with no field naming the
18194        // offending policy.
18195        let mut s = three_member_spec();
18196        s.politicas.circuit_breaker = Some(CircuitBreaker {
18197            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
18198            window: Duration::from_secs(60),
18199        });
18200        assert_eq!(
18201            s.validate().unwrap_err(),
18202            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
18203                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
18204            }
18205        );
18206    }
18207
18208    #[test]
18209    fn rejects_circuit_breaker_max_failures_far_above_cap() {
18210        // The `u32::MAX` worst case — the four-billion-failure
18211        // threshold a typo (`(:max-failures 4294967295)`) or a
18212        // struct-literal copy-paste lands in the slot. Pin the cap
18213        // arm's coverage explicitly across the full `u32` overflow
18214        // so a future relaxation that drops the upper bound surfaces
18215        // here.
18216        let mut s = three_member_spec();
18217        s.politicas.circuit_breaker = Some(CircuitBreaker {
18218            max_failures: u32::MAX,
18219            window: Duration::from_secs(60),
18220        });
18221        assert_eq!(
18222            s.validate().unwrap_err(),
18223            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
18224                max_failures: u32::MAX,
18225            }
18226        );
18227    }
18228
18229    #[test]
18230    fn accepts_circuit_breaker_max_failures_at_cap() {
18231        // The boundary value — exactly
18232        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
18233        // cap is inclusive on the top edge, matching the
18234        // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
18235        // discipline on the sibling capped axes. Pin the boundary
18236        // explicitly so a future off-by-one tightening
18237        // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
18238        // surfaces here as a test failure rather than a silent
18239        // contract narrowing.
18240        let mut s = three_member_spec();
18241        s.politicas.circuit_breaker = Some(CircuitBreaker {
18242            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
18243            window: Duration::from_secs(60),
18244        });
18245        s.validate()
18246            .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
18247    }
18248
18249    #[test]
18250    fn accepts_circuit_breaker_max_failures_typical_values() {
18251        // The documented production-playbook band positive-control
18252        // sweep — every value Hystrix / Istio / Envoy / Polly /
18253        // Resilience4j recommend (5..=50) must pass, plus a sweep
18254        // through the hyperscale band (100, 500, 1000) the cap
18255        // accepts. Pin the inclusive validated set explicitly so a
18256        // future tightening of the ceiling surfaces here.
18257        //
18258        // Clears the fixture's `:retries` (which is `Some(3)`) so this
18259        // per-axis sweep is pure: the sibling cross-axis
18260        // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
18261        // gate rejects any `max_failures <= retries` pair, so the
18262        // `max_failures = 1` boundary at the head of the sweep would
18263        // otherwise trip on the fixture-inherited retry policy rather
18264        // than the per-axis boundary this test names. Same discipline
18265        // the sibling per-axis `accepts_circuit_breaker_window_*`
18266        // sweeps take against the fixture's `:timeout` for the
18267        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`]
18268        // cross-axis arm.
18269        for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
18270            let mut s = three_member_spec();
18271            s.politicas.retries = None;
18272            s.politicas.circuit_breaker = Some(CircuitBreaker {
18273                max_failures: n,
18274                window: Duration::from_secs(60),
18275            });
18276            s.validate()
18277                .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
18278        }
18279    }
18280
18281    #[test]
18282    fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
18283        // The cross-arm ordering pin: `0` is structurally outside
18284        // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
18285        // (cap), but the zero-floor diagnostic is the more
18286        // self-locating one (it directly names the omit-axis
18287        // remediation), so the validate gate must fire on zero
18288        // first. Same shape every other zero-then-shape ordering on
18289        // this surface uses
18290        // ([`AplicacaoError::PolicyRetriesZero`] then
18291        // [`AplicacaoError::PolicyRetriesExceedsCap`];
18292        // [`AplicacaoError::PolicyTimeoutZero`] then
18293        // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
18294        let mut s = three_member_spec();
18295        s.politicas.circuit_breaker = Some(CircuitBreaker {
18296            max_failures: 0,
18297            window: Duration::from_secs(60),
18298        });
18299        assert_eq!(
18300            s.validate().unwrap_err(),
18301            AplicacaoError::PolicyBreakerZeroFailures,
18302            "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
18303        );
18304    }
18305
18306    #[test]
18307    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
18308        // The cross-arm ordering pin between the cap and the
18309        // sibling `:window` gates (zero-window, canonical-window).
18310        // A breaker carrying both an over-cap `max_failures` AND a
18311        // structurally invalid window (zero, sub-ms) must surface
18312        // the cap diagnostic first — the cap arm is wired
18313        // immediately after the zero-failure arm and strictly
18314        // before the window arms, so the offending value the
18315        // diagnostic names matches the order the author would
18316        // discover the gates by reading top-to-bottom through
18317        // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
18318        // future refactor that reorders the arms surfaces here as a
18319        // test failure rather than a silent diagnostic regression.
18320        let mut s = three_member_spec();
18321        s.politicas.circuit_breaker = Some(CircuitBreaker {
18322            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
18323            window: Duration::ZERO,
18324        });
18325        assert_eq!(
18326            s.validate().unwrap_err(),
18327            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
18328                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
18329            },
18330            "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
18331        );
18332    }
18333
18334    #[test]
18335    fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
18336        // The diagnostic-shape pin: the offending `u32` is carried
18337        // verbatim into the
18338        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
18339        // variant so the surfaced error message names the value the
18340        // author wrote (`":politicas :circuit-breaker :max-failures
18341        // (50000) exceeds the mesh-policy ceiling …"`), not just
18342        // the cap. Same self-locating diagnostic shape every other
18343        // typed-cap arm on this surface carries
18344        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
18345        // offending retry count verbatim,
18346        // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
18347        // offending byte count verbatim).
18348        let mut s = three_member_spec();
18349        s.politicas.circuit_breaker = Some(CircuitBreaker {
18350            max_failures: 50_000,
18351            window: Duration::from_secs(60),
18352        });
18353        let err = s.validate().unwrap_err();
18354        assert!(
18355            matches!(
18356                err,
18357                AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
18358                    max_failures: 50_000
18359                }
18360            ),
18361            "got {err:?}"
18362        );
18363        let msg = err.to_string();
18364        assert!(
18365            msg.contains("50000"),
18366            ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
18367        );
18368    }
18369
18370    #[test]
18371    fn policy_breaker_max_failures_cap_pins_canonical_value() {
18372        // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
18373        // value at 1000 — an order of magnitude above every
18374        // documented production-playbook recommendation band
18375        // (Hystrix `requestVolumeThreshold` default 20, Istio
18376        // `outlierDetection.consecutive5xxErrors` default 5, Envoy
18377        // `outlier_detection.consecutive_5xx` default 5, Polly /
18378        // Resilience4j typical 5..=50) and below the
18379        // clearly-pathological "effectively no protection" floor
18380        // (10_000, 100_000, u32::MAX). Pinning the literal value
18381        // here surfaces a future drift (a relaxation to 10_000, a
18382        // tightening to 100) as a deliberate test edit, not a
18383        // silent contract narrowing.
18384        assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
18385    }
18386
18387    #[test]
18388    fn rejects_circuit_breaker_zero_window() {
18389        let mut s = three_member_spec();
18390        s.politicas.circuit_breaker = Some(CircuitBreaker {
18391            max_failures: 5,
18392            window: Duration::ZERO,
18393        });
18394        assert_eq!(
18395            s.validate().unwrap_err(),
18396            AplicacaoError::PolicyBreakerZeroWindow
18397        );
18398    }
18399
18400    #[test]
18401    fn rejects_zero_rate_limit() {
18402        let mut s = three_member_spec();
18403        s.politicas.rate_limit = Some(RateLimit {
18404            rate: 0,
18405            window: Duration::from_secs(1),
18406        });
18407        assert_eq!(
18408            s.validate().unwrap_err(),
18409            AplicacaoError::PolicyRateLimitZero
18410        );
18411    }
18412
18413    #[test]
18414    fn rejects_rate_limit_zero_window() {
18415        // `RateLimit { rate: 100, window: Duration::ZERO }` is
18416        // constructible programmatically (the typed `Duration` field
18417        // imposes no nonzero invariant) but renders through
18418        // `rate_limit_codec::render` as `"100/0s"` — a fragment the
18419        // codec's `parse` rejects as `unknown rate-limit window unit
18420        // "0s"`. Until this validate-time gate landed the typed slot
18421        // accepted the value silently and the round-trip break only
18422        // surfaced at deserialize time (potentially in a downstream
18423        // consumer that never re-validates). Pin the rejection at
18424        // `AplicacaoSpec::validate` so the typed slot's valid set
18425        // matches the codec's round-trippable set structurally.
18426        let mut s = three_member_spec();
18427        s.politicas.rate_limit = Some(RateLimit {
18428            rate: 100,
18429            window: Duration::ZERO,
18430        });
18431        assert_eq!(
18432            s.validate().unwrap_err(),
18433            AplicacaoError::PolicyRateLimitWindowNotCanonical {
18434                window: Duration::ZERO
18435            }
18436        );
18437    }
18438
18439    #[test]
18440    fn rejects_rate_limit_arbitrary_seconds_window() {
18441        // 45 seconds is a valid `Duration` but not one of the three
18442        // canonical rate-limit windows the codec round-trips
18443        // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
18444        // refuses on round-trip — same round-trip-break shape the
18445        // zero-window arm above pins, with a non-zero magnitude to
18446        // guard against a future "reject only zero" half-measure.
18447        let mut s = three_member_spec();
18448        let window = Duration::from_secs(45);
18449        s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
18450        assert_eq!(
18451            s.validate().unwrap_err(),
18452            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
18453        );
18454    }
18455
18456    #[test]
18457    fn rejects_rate_limit_two_minute_window() {
18458        // 120 seconds = 2 minutes is a "looks-canonical" but
18459        // not-canonical window: it's a clean integer multiple of the
18460        // minute unit, but the codec only round-trips the
18461        // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
18462        // A `Duration::from_secs(120)` window renders as `"100/120s"`
18463        // which the parser rejects. Pinning this case rules out a
18464        // future "accept any clean multiple of s/m/h" relaxation
18465        // that would silently break the codec contract.
18466        let mut s = three_member_spec();
18467        let window = Duration::from_secs(120);
18468        s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
18469        assert_eq!(
18470            s.validate().unwrap_err(),
18471            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
18472        );
18473    }
18474
18475    #[test]
18476    fn rejects_rate_limit_subsecond_window() {
18477        // A sub-second window (e.g. 500ms) is a valid `Duration` but
18478        // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
18479        // Pin the rejection so a future relaxation can't silently
18480        // admit fractional-second windows that the codec can't
18481        // round-trip.
18482        let mut s = three_member_spec();
18483        let window = Duration::from_millis(500);
18484        s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
18485        assert_eq!(
18486            s.validate().unwrap_err(),
18487            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
18488        );
18489    }
18490
18491    #[test]
18492    fn rejects_policy_rate_limit_above_cap() {
18493        // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
18494        // is structurally one past the cap and silently passed
18495        // validate on every pre-gate codebase because the typed slot's
18496        // only `rate` check was the zero-floor arm. The no-op-limiter
18497        // shape only surfaced at the runtime substrate (Envoy's
18498        // `local_rate_limit.token_bucket.max_tokens`, the future
18499        // Cilium L7 rate-limit overlay) far from the source caixa.lisp
18500        // with no field naming the offending policy.
18501        let mut s = three_member_spec();
18502        s.politicas.rate_limit = Some(RateLimit {
18503            rate: POLICY_RATE_LIMIT_MAX + 1,
18504            window: Duration::from_secs(1),
18505        });
18506        assert_eq!(
18507            s.validate().unwrap_err(),
18508            AplicacaoError::PolicyRateLimitExceedsCap {
18509                rate: POLICY_RATE_LIMIT_MAX + 1
18510            }
18511        );
18512    }
18513
18514    #[test]
18515    fn rejects_policy_rate_limit_far_above_cap() {
18516        // The `u32::MAX` worst case — the four-billion-token rate-limit
18517        // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
18518        // copy-paste lands in the slot. Pin the cap arm's coverage
18519        // explicitly across the full `u32` overflow so a future
18520        // relaxation that drops the upper bound surfaces here. Peer to
18521        // `rejects_policy_retries_far_above_cap` on the sibling
18522        // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
18523        // on the sibling `:max-failures` axis.
18524        let mut s = three_member_spec();
18525        s.politicas.rate_limit = Some(RateLimit {
18526            rate: u32::MAX,
18527            window: Duration::from_secs(1),
18528        });
18529        assert_eq!(
18530            s.validate().unwrap_err(),
18531            AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
18532        );
18533    }
18534
18535    #[test]
18536    fn accepts_policy_rate_limit_at_cap() {
18537        // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
18538        // must validate. The cap is inclusive on the top edge, matching
18539        // every other typed upper bound in this crate
18540        // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
18541        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
18542        // across all three canonical windows so a future off-by-one
18543        // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
18544        // window-conditional cap surfaces here as a test failure rather
18545        // than a silent contract narrowing.
18546        for secs in [1u64, 60, 3600] {
18547            let mut s = three_member_spec();
18548            s.politicas.rate_limit = Some(RateLimit {
18549                rate: POLICY_RATE_LIMIT_MAX,
18550                window: Duration::from_secs(secs),
18551            });
18552            s.validate().unwrap_or_else(|e| {
18553                panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
18554            });
18555        }
18556    }
18557
18558    #[test]
18559    fn accepts_policy_rate_limit_typical_values() {
18560        // The documented production-playbook recommendation band —
18561        // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
18562        // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
18563        // Enterprise ~1M per-hour. Every value in the validated set
18564        // must pass; pin the band explicitly so a future tightening
18565        // surfaces here.
18566        //
18567        // Clears the fixture's `:retries` (which is `Some(3)`) so this
18568        // per-axis sweep is pure: the sibling cross-axis
18569        // [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] gate
18570        // rejects any `rate <= retries` pair, so the `rate = 1`
18571        // boundary at the head of the sweep would otherwise trip on the
18572        // fixture-inherited retry policy rather than the per-axis
18573        // boundary this test names. Same discipline the sibling per-axis
18574        // `accepts_circuit_breaker_max_failures_typical_values` sweep
18575        // takes against the fixture's `:retries` for the peer cross-axis
18576        // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
18577        // arm.
18578        for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
18579            for secs in [1u64, 60, 3600] {
18580                let mut s = three_member_spec();
18581                s.politicas.retries = None;
18582                s.politicas.rate_limit = Some(RateLimit {
18583                    rate,
18584                    window: Duration::from_secs(secs),
18585                });
18586                s.validate().unwrap_or_else(|e| {
18587                    panic!("rate={rate} window={secs}s must validate; got {e:?}")
18588                });
18589            }
18590        }
18591    }
18592
18593    #[test]
18594    fn policy_rate_limit_zero_takes_precedence_over_cap() {
18595        // The cross-arm ordering pin: `rate == 0` is structurally
18596        // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
18597        // (cap), but the zero-floor diagnostic is the more
18598        // self-locating one (it directly names the omit-axis
18599        // remediation). Pin the order so a future refactor that
18600        // reorders the arms surfaces here as a test failure rather
18601        // than a silent diagnostic regression. Same shape every other
18602        // zero-then-cap ordering on this surface uses
18603        // ([`AplicacaoError::PolicyRetriesZero`] then
18604        // [`AplicacaoError::PolicyRetriesExceedsCap`];
18605        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
18606        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
18607        let mut s = three_member_spec();
18608        s.politicas.rate_limit = Some(RateLimit {
18609            rate: 0,
18610            window: Duration::from_secs(1),
18611        });
18612        assert_eq!(
18613            s.validate().unwrap_err(),
18614            AplicacaoError::PolicyRateLimitZero,
18615            "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
18616        );
18617    }
18618
18619    #[test]
18620    fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
18621        // Two-axis-bad pin: rate above cap *and* window non-canonical.
18622        // The validate gate must fire on the rate cap first — the
18623        // amplification-shape (no-op limiter) diagnostic is the more
18624        // fundamental one; the window-canonical diagnostic is the
18625        // narrower codec-round-trip shape. Pin the ordering so a future
18626        // refactor that reorders the rate-then-window check arms
18627        // surfaces here as a test failure rather than a silent
18628        // diagnostic regression.
18629        let mut s = three_member_spec();
18630        s.politicas.rate_limit = Some(RateLimit {
18631            rate: POLICY_RATE_LIMIT_MAX + 1,
18632            window: Duration::from_secs(45),
18633        });
18634        assert_eq!(
18635            s.validate().unwrap_err(),
18636            AplicacaoError::PolicyRateLimitExceedsCap {
18637                rate: POLICY_RATE_LIMIT_MAX + 1
18638            },
18639            "above-cap rate must surface the cap diagnostic, not the window diagnostic"
18640        );
18641    }
18642
18643    #[test]
18644    fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
18645        // The diagnostic-shape pin: the offending `u32` is carried
18646        // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
18647        // variant so the surfaced error message names the value the
18648        // author wrote (`":politicas :rate-limit rate (5000000) exceeds
18649        // the mesh-policy ceiling …"`), not just the cap. Same
18650        // self-locating diagnostic shape every other typed-cap arm on
18651        // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
18652        // carries the offending retries count verbatim,
18653        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
18654        // the offending failure count verbatim).
18655        let mut s = three_member_spec();
18656        s.politicas.rate_limit = Some(RateLimit {
18657            rate: 5_000_000,
18658            window: Duration::from_secs(1),
18659        });
18660        let err = s.validate().unwrap_err();
18661        assert!(
18662            matches!(
18663                err,
18664                AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
18665            ),
18666            "got {err:?}"
18667        );
18668        let msg = err.to_string();
18669        assert!(
18670            msg.contains("5000000"),
18671            ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
18672        );
18673    }
18674
18675    #[test]
18676    fn policy_rate_limit_cap_pins_canonical_value() {
18677        // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
18678        // 1_000_000 — two-to-three orders of magnitude above every
18679        // documented production-playbook recommendation band (Envoy /
18680        // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
18681        // Gateway 10_000..=100_000 per-minute) and below the
18682        // clearly-pathological "paste-from-binary blob" floor
18683        // (100_000_000, u32::MAX). Pinning the literal value here
18684        // surfaces a future drift (a relaxation to 10_000_000, a
18685        // tightening to 100_000) as a deliberate test edit, not a
18686        // silent contract narrowing.
18687        assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
18688    }
18689
18690    #[test]
18691    fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
18692        // Both axes are invalid here: rate == 0 *and* window is
18693        // non-canonical. The validate gate must fire on rate first
18694        // (matching the existing `rejects_zero_rate_limit` ordering),
18695        // so the existing diagnostic continues to lead with the
18696        // simpler "zero rate" framing. Pinning the order of checks
18697        // so a future refactor that reorders the arms surfaces here
18698        // as a test failure rather than a silent diagnostic
18699        // regression.
18700        let mut s = three_member_spec();
18701        s.politicas.rate_limit = Some(RateLimit {
18702            rate: 0,
18703            window: Duration::from_secs(45),
18704        });
18705        assert_eq!(
18706            s.validate().unwrap_err(),
18707            AplicacaoError::PolicyRateLimitZero
18708        );
18709    }
18710
18711    #[test]
18712    fn rate_limit_canonical_windows_validate() {
18713        // The three canonical windows the codec round-trips
18714        // losslessly — 1s / 60s / 3600s — must all pass `validate()`
18715        // unchanged. Pin the full canonical set as a positive case
18716        // (the existing `rate_limit_round_trip_seconds` /
18717        // `rate_limit_round_trip_minutes` tests pin the
18718        // serialize-then-deserialize property at the codec layer; this
18719        // test pins the validate-side complement so a future tightening
18720        // of the canonical set — e.g. dropping `:hour` — surfaces here
18721        // as a test failure rather than a silent contract narrowing).
18722        for secs in [1u64, 60, 3600] {
18723            let mut s = three_member_spec();
18724            s.politicas.rate_limit = Some(RateLimit {
18725                rate: 100,
18726                window: Duration::from_secs(secs),
18727            });
18728            s.validate().expect("canonical window must validate");
18729        }
18730    }
18731
18732    #[test]
18733    fn rate_limit_validated_value_round_trips_through_codec() {
18734        // The structural property the validate gate enforces:
18735        // every `RateLimit` past `AplicacaoSpec::validate` round-trips
18736        // losslessly through the `rate_limit_codec` (serialize → string
18737        // → deserialize → equal value). Pin this end-to-end so a future
18738        // change to either side (the validate gate's accepted window
18739        // set, the codec's parse/render unit set) that breaks the
18740        // alignment surfaces here. The previous-state shape (typed
18741        // slot accepts arbitrary `Duration`, codec only round-trips
18742        // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
18743        // window — the validate gate now forecloses that.
18744        for secs in [1u64, 60, 3600] {
18745            let mut s = three_member_spec();
18746            s.politicas.rate_limit = Some(RateLimit {
18747                rate: 250,
18748                window: Duration::from_secs(secs),
18749            });
18750            s.validate().unwrap();
18751            let json = serde_json::to_string(&s.politicas).unwrap();
18752            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
18753            assert_eq!(
18754                back.rate_limit, s.politicas.rate_limit,
18755                "every validated :rate-limit must round-trip losslessly through the codec"
18756            );
18757        }
18758    }
18759
18760    #[test]
18761    fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
18762        // The hour-window canonical form (`"<n>/h"`) was missing from
18763        // the prior `rate_limit_round_trip_seconds` / `_minutes` test
18764        // pair. Now that the validate gate pins 3600s as part of the
18765        // canonical set, pin its serialize-side render shape too so
18766        // the third leg of the s/m/h tripod is explicitly tested.
18767        let policy = MeshPolicy {
18768            rate_limit: Some(RateLimit {
18769                rate: 10000,
18770                window: Duration::from_secs(3600),
18771            }),
18772            ..Default::default()
18773        };
18774        let json = serde_json::to_string(&policy).unwrap();
18775        assert!(
18776            json.contains("\"10000/h\""),
18777            "hour-window canonical form must render with `h` suffix (got: {json})"
18778        );
18779        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
18780        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
18781    }
18782
18783    #[test]
18784    fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
18785        // Pin the substrate-primitive [`RateLimit::canonical_unit`]
18786        // typed accessor's accepted-window set against the codec's
18787        // accepted set explicitly. A future addition to the codec
18788        // (e.g. accepting `:day`/`:week` as authoring units) must be
18789        // accompanied by a parallel addition here, and a regression
18790        // that drops one of the three canonical units from either
18791        // side surfaces as a test failure. The accessor is the
18792        // single source of truth for the canonical-window set —
18793        // [`AplicacaoSpec::validate_politicas`]'s canonical-window
18794        // gate and [`rate_limit_codec::render`]'s canonical arm both
18795        // read through it — this test enshrines that its
18796        // `Duration → Option<RateLimitUnit>` projection matches the
18797        // codec's parse / render arms' accepted-window set exactly.
18798        //
18799        // Predecessor: this pin previously read the module-private
18800        // free helper `is_canonical_rate_limit_window` — a delegate
18801        // that composed [`RateLimitUnit::from_window`] with `.is_some()`
18802        // — but the helper had no production consumers left after the
18803        // validate-gate migration onto [`RateLimit::canonical_unit`]
18804        // and was deleted; the closed-set arm-window bijection now
18805        // lives on exactly one typed dispatch on the substrate
18806        // primitive.
18807        let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
18808            RateLimit { rate: 1, window }.canonical_unit()
18809        };
18810        assert!(canonical_unit(Duration::from_secs(1)).is_some());
18811        assert!(canonical_unit(Duration::from_secs(60)).is_some());
18812        assert!(canonical_unit(Duration::from_secs(3600)).is_some());
18813        // Non-canonical windows the accessor rejects.
18814        assert!(canonical_unit(Duration::ZERO).is_none());
18815        assert!(canonical_unit(Duration::from_secs(2)).is_none());
18816        assert!(canonical_unit(Duration::from_secs(30)).is_none());
18817        assert!(canonical_unit(Duration::from_secs(120)).is_none());
18818        assert!(canonical_unit(Duration::from_secs(86400)).is_none());
18819        // Sub-second windows: even `Duration::from_millis(1000)` is
18820        // exactly 1s and accepted; `Duration::from_millis(500)` is
18821        // sub-second and rejected.
18822        assert!(canonical_unit(Duration::from_millis(1000)).is_some());
18823        assert!(canonical_unit(Duration::from_millis(500)).is_none());
18824        assert!(canonical_unit(Duration::from_millis(1500)).is_none());
18825    }
18826
18827    #[test]
18828    fn rate_limit_unit_table_projections_are_mutual_inverses() {
18829        // Bidirection pin against the closed-set typed enum
18830        // [`RateLimitUnit`] arm-table (the canonical
18831        // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
18832        // of the rate-limit unit surface reads from). The two
18833        // projection directions [`RateLimitUnit::from_suffix`] /
18834        // [`RateLimitUnit::window`] (str → Duration, exposed as one
18835        // typed dispatch through [`RateLimitUnit::window_from_suffix`])
18836        // and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
18837        // (Duration → str, exposed as one typed dispatch through
18838        // [`RateLimit::canonical_unit`] composed with
18839        // [`RateLimitUnit::as_suffix`]) are the substrate primitives the
18840        // codec's parse arm ([`rate_limit_codec::parse`] via
18841        // [`RateLimitUnit::window_from_suffix`]), the codec's render arm
18842        // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
18843        // and the validate gate ([`AplicacaoSpec::validate_politicas`]
18844        // via [`RateLimit::canonical_unit`]) all key off. A future
18845        // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
18846        // sub-second window) is one variant + one arm per method on the
18847        // closed-set enum; the compiler-enforced exhaustiveness on
18848        // every consumer's `match self` arms picks it up by
18849        // construction. This pin enshrines that both projection
18850        // directions agree on every canonical arm row and neither
18851        // leaks a spurious entry the other doesn't recognize.
18852        //
18853        // Predecessor: this test previously read the two vestigial
18854        // module-private free helpers `rate_limit_window_unit` and
18855        // `rate_limit_window_from_unit` on the `Duration → &str` and
18856        // `&str → Duration` axes; the former was deleted after its
18857        // sole production consumer ([`rate_limit_codec::render`])
18858        // migrated onto [`RateLimit::canonical_unit`] (61421a6), and
18859        // the latter is folded here into the substrate primitive
18860        // [`RateLimitUnit::window_from_suffix`] so both projection
18861        // directions live on the closed-set enum's arm-table.
18862        for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
18863            let window = super::RateLimitUnit::window_from_suffix(unit)
18864                .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
18865            assert_eq!(
18866                window,
18867                Duration::from_secs(secs),
18868                "unit {unit:?} must resolve to {secs}s"
18869            );
18870            let projected_suffix = RateLimit { rate: 1, window }
18871                .canonical_unit()
18872                .map(super::RateLimitUnit::as_suffix);
18873            assert_eq!(
18874                projected_suffix,
18875                Some(unit),
18876                "Duration({secs}s) must render as {unit:?} \
18877                 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
18878            );
18879        }
18880        // Non-table units yield None on the `unit → Duration`
18881        // projection — a future `"d"` addition to the table would
18882        // flip this arm; today it pins the current three-row table's
18883        // rejection semantics.
18884        assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
18885        assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
18886        assert!(super::RateLimitUnit::window_from_suffix("").is_none());
18887        // Non-table Durations yield None on the `Duration → unit`
18888        // projection — pins that the two projections agree on the
18889        // "not in the table" semantic too, so a drift where the
18890        // parse-side accepts a value the render-side can't emit is
18891        // a build error at the two-arm pair, not a silent codec
18892        // round-trip break.
18893        let projected_suffix = |window: Duration| -> Option<&'static str> {
18894            RateLimit { rate: 1, window }
18895                .canonical_unit()
18896                .map(super::RateLimitUnit::as_suffix)
18897        };
18898        assert!(projected_suffix(Duration::from_secs(2)).is_none());
18899        assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
18900        assert!(projected_suffix(Duration::from_millis(1500)).is_none());
18901    }
18902
18903    #[test]
18904    fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
18905        // Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
18906        // substrate-primitive `&str → Duration` associated method the
18907        // codec's parse arm ([`rate_limit_codec::parse`]) now routes
18908        // through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
18909        // to the same [`Duration`] the two-step composition
18910        // [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
18911        // returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
18912        // `"MIN"`) must project to [`None`] on both paths. A future
18913        // implementation of `window_from_suffix` that took a shortcut
18914        // through a per-suffix `match` table (bypassing the arm-table's
18915        // `Self::from_suffix` scan and the arm-table's `Self::window`
18916        // dispatch) would silently split the accept-set — the parse
18917        // arm would accept a suffix the enum's arm-table doesn't know,
18918        // or reject a suffix the enum's arm-table does; this pin
18919        // surfaces that drift at caixa-core build time rather than at a
18920        // downstream serde round-trip audit on a live `MeshPolicy`.
18921        //
18922        // Same byte-parity discipline the sibling
18923        // [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
18924        // pin carries on the peer `Duration → RateLimitUnit` axis via
18925        // [`RateLimit::canonical_unit`], and the peer
18926        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
18927        // carries on the bidirectional arm-table axis — extended here
18928        // onto the fifth (and last unlifted) projection axis on the
18929        // closed-set enum's arm-table.
18930        let composition = |suffix: &str| -> Option<Duration> {
18931            super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
18932        };
18933        for suffix in ["s", "m", "h"] {
18934            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
18935            let via_composition = composition(suffix);
18936            assert_eq!(
18937                via_method, via_composition,
18938                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
18939                 from_suffix({suffix:?}).map(window) — the substrate-primitive \
18940                 method must delegate to the arm-table's two typed dispatches, \
18941                 not shortcut through a per-suffix match table"
18942            );
18943            assert!(
18944                via_method.is_some(),
18945                "canonical suffix {suffix:?} must resolve to Some(Duration) via \
18946                 RateLimitUnit::window_from_suffix"
18947            );
18948        }
18949        for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
18950            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
18951            let via_composition = composition(suffix);
18952            assert_eq!(
18953                via_method, via_composition,
18954                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
18955                 from_suffix({suffix:?}).map(window) on the non-arm rejection \
18956                 axis too"
18957            );
18958            assert!(
18959                via_method.is_none(),
18960                "non-arm suffix {suffix:?} must project to None via \
18961                 RateLimitUnit::window_from_suffix — a future extension that \
18962                 accepted this suffix without a corresponding arm on the enum \
18963                 would split the codec's parse-accepted set from the enum's \
18964                 arm-table"
18965            );
18966        }
18967        // And the codec's parse arm now reads through this method: a
18968        // canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
18969        // the same `Duration` the method returns for its unit, closing
18970        // the two-consumer drift surface (the codec's parse arm and the
18971        // enum's arm-table) with one typed dispatch on the substrate
18972        // primitive.
18973        for suffix in ["s", "m", "h"] {
18974            let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
18975            let mp: MeshPolicy = serde_json::from_str(&wire)
18976                .unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
18977            let parsed = mp.rate_limit().expect("rate_limit payload present");
18978            let via_method = super::RateLimitUnit::window_from_suffix(suffix)
18979                .unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
18980            assert_eq!(
18981                parsed.window(),
18982                via_method,
18983                "codec parse arm on {wire:?} must resolve the window through \
18984                 RateLimitUnit::window_from_suffix, not a divergent path"
18985            );
18986        }
18987    }
18988
18989    #[test]
18990    fn rate_limit_unit_all_enumerates_every_arm_once() {
18991        // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
18992        // enumerate every arm of the closed-set enum exactly once, in
18993        // the canonical shortest-to-longest window order (Second before
18994        // Minute before Hour) — the same order the sibling
18995        // [`crate::supervisor::RestartStrategy`] /
18996        // [`crate::supervisor::RestartPolicy`] /
18997        // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
18998        // typed enums carry (the arm declared first is the arm listed
18999        // first). A future variant addition that extends the enum
19000        // without appending to [`RateLimitUnit::ALL`] leaves the
19001        // exhaustive iteration surface silently short one arm — the
19002        // codec's parse arm would then reject the new suffix even
19003        // though the enum knows it. This pin closes the drift.
19004        assert_eq!(
19005            super::RateLimitUnit::ALL,
19006            &[
19007                super::RateLimitUnit::Second,
19008                super::RateLimitUnit::Minute,
19009                super::RateLimitUnit::Hour,
19010            ],
19011            "RateLimitUnit::ALL must enumerate every arm exactly once, \
19012             in canonical shortest-to-longest window order"
19013        );
19014    }
19015
19016    #[test]
19017    fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
19018        // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
19019        // every arm's [`RateLimitUnit::as_suffix`] output must parse
19020        // back through [`RateLimitUnit::from_suffix`] to the same
19021        // variant. A future arm addition that lands `as_suffix` but
19022        // forgets `from_suffix` (`from_suffix` iterates
19023        // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
19024        // is the load-bearing carrier of the round-trip; the sibling
19025        // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
19026        // the `ALL` half) trips here at caixa-core build time rather
19027        // than surfacing as a codec round-trip miss (a `render` emit
19028        // that lands a suffix the paired `parse` cannot decode).
19029        for unit in super::RateLimitUnit::ALL {
19030            let suffix = unit.as_suffix();
19031            let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
19032                panic!(
19033                    "RateLimitUnit::from_suffix({suffix:?}) must accept every \
19034                     RateLimitUnit::as_suffix output — got None for {unit:?}"
19035                )
19036            });
19037            assert_eq!(
19038                parsed, *unit,
19039                "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
19040                 must return RateLimitUnit::{unit:?}"
19041            );
19042        }
19043    }
19044
19045    #[test]
19046    fn rate_limit_unit_from_window_and_window_round_trip() {
19047        // Total round-trip pin on the `(from_window, window)` pair:
19048        // every arm's [`RateLimitUnit::window`] output must parse back
19049        // through [`RateLimitUnit::from_window`] to the same variant.
19050        // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
19051        // on the peer `Duration` axis — the two round-trip pins
19052        // together enshrine that both projections of the typed
19053        // canonical-unit bijection are total on the arm-set.
19054        for unit in super::RateLimitUnit::ALL {
19055            let window = unit.window();
19056            let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
19057                panic!(
19058                    "RateLimitUnit::from_window({window:?}) must accept every \
19059                     RateLimitUnit::window output — got None for {unit:?}"
19060                )
19061            });
19062            assert_eq!(
19063                parsed, *unit,
19064                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
19065                 must return RateLimitUnit::{unit:?}"
19066            );
19067        }
19068    }
19069
19070    #[test]
19071    fn rate_limit_unit_from_window_accessor_is_const_fn() {
19072        // Fail-before-pass-after pin: witnesses the
19073        // [`RateLimitUnit::from_window`] `const`-eval posture via a
19074        // `const fn` wrapper `from_window_via_const_fn(window: Duration)
19075        // -> Option<RateLimitUnit>` whose body calls
19076        // `RateLimitUnit::from_window(window)`, well-formed only when
19077        // the callee is itself `const fn` (any future downgrade to
19078        // non-`const` fails at caixa-core build time with E0015 `cannot
19079        // call non-const function`, strictly stronger than a runtime
19080        // `assert!`, side-stepping the destructor-in-const restriction
19081        // that blocks direct `const _: Option<RateLimitUnit> =
19082        // RateLimitUnit::from_window(...)` items on `Duration`'s
19083        // carrier). The runtime body sweeps every closed-set
19084        // [`RateLimitUnit::ALL`] arm plus a representative non-canonical
19085        // rejection sample (`Duration::from_millis(500)` sub-second
19086        // residue) and asserts the wrapped and direct dispatches agree
19087        // — a violation means the wrapper stopped compiling under a
19088        // future `const`-posture downgrade, or the reverse resolver's
19089        // arm-set silently split from the peer `Self::window` emitter's
19090        // arm-set. Peer of the sibling
19091        // [`crate::supervisor::tests::child_spec_restart_accessor_is_const_fn`]
19092        // (152c868) /
19093        // [`crate::supervisor::tests::supervisor_spec_estrategia_accessor_is_const_fn`]
19094        // (152c868) /
19095        // [`entrada_port_accessor_is_const_fn`] (bafa004) /
19096        // [`placement_estrategia_accessor_is_const_fn`] (bafa004)
19097        // `const`-eval-surface pins on the peer M2 / M3 substrate-
19098        // primitive `Copy`-return accessor axes, extended onto the
19099        // reverse `Duration → RateLimitUnit` projection axis on the
19100        // M3 mesh-slot rate-limit closed-set typed enum.
19101        const fn from_window_via_const_fn(window: Duration) -> Option<super::RateLimitUnit> {
19102            super::RateLimitUnit::from_window(window)
19103        }
19104        for unit in super::RateLimitUnit::ALL {
19105            let window = unit.window();
19106            let via_wrapper = from_window_via_const_fn(window);
19107            let direct = super::RateLimitUnit::from_window(window);
19108            assert_eq!(
19109                via_wrapper, direct,
19110                "RateLimitUnit::from_window({window:?}) via const fn \
19111                 wrapper must agree with direct dispatch for {unit:?}"
19112            );
19113            assert_eq!(
19114                via_wrapper,
19115                Some(*unit),
19116                "RateLimitUnit::from_window({window:?}) via const fn \
19117                 wrapper must return Some({unit:?}) for the peer \
19118                 window() output"
19119            );
19120        }
19121        assert!(from_window_via_const_fn(Duration::from_millis(500)).is_none());
19122        assert!(from_window_via_const_fn(Duration::from_secs(30)).is_none());
19123    }
19124
19125    #[test]
19126    fn rate_limit_unit_from_window_composes_through_window_accessor() {
19127        // Composition-witness pin on the routing-through-peer discipline:
19128        // [`RateLimitUnit::from_window`]'s per-arm probes each dispatch
19129        // through the peer `pub const fn` [`RateLimitUnit::window`]
19130        // canonical-`Duration` projection rather than a hand-authored
19131        // per-arm second-magnitude literal — a future arm-magnitude edit
19132        // on the sibling `window()` accessor (a `Second → 2s` typo, a
19133        // `Hour → 3599s` off-by-one) must therefore reach this reverse
19134        // resolver by construction. A pin that hard-coded the three
19135        // second-magnitudes here would silently split from the peer
19136        // emitter on any such edit; instead, this pin asserts the
19137        // composition invariant `from_window(u.window()) == Some(u)`
19138        // holds byte-for-byte on every closed-set [`RateLimitUnit::ALL`]
19139        // arm — a violation means either the peer `Self::window`
19140        // accessor drifted (breaking every downstream consumer that
19141        // reads through it), or the reverse resolver stopped routing
19142        // through the peer (introducing a hand-authored literal that
19143        // silently disagrees with the emitter). Either failure is a
19144        // caixa-core-build-time surface, not a downstream renderer
19145        // round-trip regression.
19146        //
19147        // Peer of the sibling
19148        // [`crate::render::assert_str_reexport_identity`] discipline on
19149        // the substrate-primitive `&'static str` re-export axis and the
19150        // [`rate_limit_unit_from_window_and_window_round_trip`]
19151        // round-trip pin on the peer projection direction; extends the
19152        // one-canonical-dispatch-per-projection discipline onto the
19153        // reverse-resolver's per-arm probe axis.
19154        for unit in super::RateLimitUnit::ALL {
19155            let window_via_peer = unit.window();
19156            let resolved = super::RateLimitUnit::from_window(window_via_peer);
19157            assert_eq!(
19158                resolved,
19159                Some(*unit),
19160                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
19161                 must return Some({unit:?}) — the reverse resolver's per-arm \
19162                 probes must route through the peer `Self::window` accessor \
19163                 so any future arm-magnitude edit reaches both projection \
19164                 directions by construction"
19165            );
19166        }
19167    }
19168
19169    #[test]
19170    fn rate_limit_canonical_unit_accessor_is_const_fn() {
19171        // Fail-before-pass-after pin: witnesses the
19172        // [`RateLimit::canonical_unit`] `const`-eval posture via a
19173        // `const fn` wrapper
19174        // `canonical_unit_via_const_fn(rl: &RateLimit) -> Option<RateLimitUnit>`
19175        // whose body calls `rl.canonical_unit()`, well-formed only when
19176        // the callee is itself `const fn` (any future downgrade to
19177        // non-`const` fails at caixa-core build time with E0015 `cannot
19178        // call non-const method`). The runtime body sweeps every
19179        // closed-set [`RateLimitUnit::ALL`] arm — for each arm,
19180        // constructs a typed [`RateLimit`] with the peer `Self::window`
19181        // canonical `Duration`, then asserts both the wrapper and the
19182        // direct dispatch agree and both return `Some(unit)`. Composes
19183        // with the sibling
19184        // [`rate_limit_unit_from_window_accessor_is_const_fn`] pin: the
19185        // typed [`RateLimit`] projection layer's `const`-posture is
19186        // load-bearing on the reverse resolver's `const`-posture, and
19187        // both must migrate together (a downgrade of either surface
19188        // splits the paired `const`-eval-surface pass on the M3
19189        // mesh-slot rate-limit `Duration ↔ Self` bijection).
19190        const fn canonical_unit_via_const_fn(
19191            rl: &super::RateLimit,
19192        ) -> Option<super::RateLimitUnit> {
19193            rl.canonical_unit()
19194        }
19195        for unit in super::RateLimitUnit::ALL {
19196            let rl = super::RateLimit {
19197                rate: 1,
19198                window: unit.window(),
19199            };
19200            let via_wrapper = canonical_unit_via_const_fn(&rl);
19201            let direct = rl.canonical_unit();
19202            assert_eq!(
19203                via_wrapper, direct,
19204                "RateLimit::canonical_unit() via const fn wrapper must \
19205                 agree with direct dispatch for {unit:?}"
19206            );
19207            assert_eq!(
19208                via_wrapper,
19209                Some(*unit),
19210                "RateLimit::canonical_unit() via const fn wrapper must \
19211                 return Some({unit:?}) for a RateLimit whose window is \
19212                 the peer RateLimitUnit::{unit:?}.window() output"
19213            );
19214        }
19215    }
19216
19217    #[test]
19218    fn rate_limit_unit_projections_are_pairwise_distinct() {
19219        // Distinctness pin: [`RateLimitUnit::as_suffix`] and
19220        // [`RateLimitUnit::window`] outputs must be pairwise distinct
19221        // across every arm — an accidental copy-paste flip that
19222        // reroutes one arm's suffix or window to also match another
19223        // silently collapses two arms onto one, so
19224        // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
19225        // (both using `find` on `Self::ALL`) would return whichever
19226        // arm the linear scan lands on first — a match-arm-ordering-
19227        // dependent outcome the closed-set typed-enum shape is meant
19228        // to rule out structurally. Peer of the sibling
19229        // `caixa_kind_wire_consts_are_pairwise_distinct` /
19230        // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
19231        // other closed-set typed-enum discriminator axes.
19232        let all = super::RateLimitUnit::ALL;
19233        for (i, a) in all.iter().enumerate() {
19234            for (j, b) in all.iter().enumerate() {
19235                if i != j {
19236                    assert_ne!(
19237                        a.as_suffix(),
19238                        b.as_suffix(),
19239                        "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
19240                         must be distinct — a collision silently collapses two \
19241                         arms onto one under from_suffix's linear scan"
19242                    );
19243                    assert_ne!(
19244                        a.window(),
19245                        b.window(),
19246                        "RateLimitUnit::{a:?}.window() and {b:?}.window() \
19247                         must be distinct — a collision silently collapses two \
19248                         arms onto one under from_window's linear scan"
19249                    );
19250                }
19251            }
19252        }
19253    }
19254
19255    #[test]
19256    fn rate_limit_unit_display_routes_through_as_suffix() {
19257        // Route pin: [`std::fmt::Display`] must byte-equal
19258        // [`RateLimitUnit::as_suffix`] on every arm — the single
19259        // source of truth for the canonical suffix. A future
19260        // reimplementation that hand-rolls the arms instead of
19261        // delegating to [`RateLimitUnit::as_suffix`] would silently
19262        // desynchronize `format!("{u}")` from the codec's parse arm
19263        // (which uses `as_suffix` to compare suffixes). Peer of the
19264        // sibling `caixa_kind_display_routes_through_as_str_helper` /
19265        // `placement_strategy_display_routes_through_as_str_helper`
19266        // pins on the peer closed-set typed-enum Display axes.
19267        for unit in super::RateLimitUnit::ALL {
19268            assert_eq!(
19269                unit.to_string(),
19270                unit.as_suffix(),
19271                "RateLimitUnit::{unit:?} Display must route through \
19272                 as_suffix (single source of truth: the canonical suffix \
19273                 the codec parses and renders)"
19274            );
19275        }
19276    }
19277
19278    #[test]
19279    fn rate_limit_unit_from_window_rejects_non_canonical() {
19280        // Rejection pin on the parser's accept-set: any Duration
19281        // outside the three-arm [`RateLimitUnit::window`] output set
19282        // (sub-second residue, or a second-magnitude outside `{1, 60,
19283        // 3600}`) must return `None`. A future accidental widening of
19284        // the accept-set (rounding down sub-second residue to the
19285        // nearest arm, admitting `Duration::from_secs(30)` as a
19286        // half-minute unit) would silently drift the parser's accept-
19287        // set from the emitter's — a validated slot with a
19288        // non-canonical window would then round-trip through the
19289        // codec to a canonical form the author never wrote.
19290        assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
19291        assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
19292        assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
19293        assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
19294        assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
19295        assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
19296        assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
19297    }
19298
19299    #[test]
19300    fn rate_limit_unit_from_suffix_rejects_unknown() {
19301        // Rejection pin on the suffix parser's accept-set: any string
19302        // outside the three-arm [`RateLimitUnit::as_suffix`] output
19303        // set must return `None`. Peer of the sibling
19304        // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
19305        // the [`crate::CaixaKind`] `from_wire` accept-set.
19306        for bad in [
19307            "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
19308            " s",
19309        ] {
19310            assert!(
19311                super::RateLimitUnit::from_suffix(bad).is_none(),
19312                "RateLimitUnit::from_suffix({bad:?}) must return None — the \
19313                 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
19314                 outputs"
19315            );
19316        }
19317    }
19318
19319    #[test]
19320    fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
19321        // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
19322        // every canonical `:window` magnitude the validate gate
19323        // accepts must map to the paired [`RateLimitUnit`] arm through
19324        // this accessor. A future validate-gate rebrand that widened
19325        // the accepted-window set without extending [`RateLimitUnit`]
19326        // would silently split the accessor's `Some`-return set from
19327        // the validate gate's accept-set — a slot that satisfies
19328        // validate would land at the accessor with `None`, so a
19329        // consumer past validate that pattern-matches on the returned
19330        // `Some` would silently miss the newly-accepted magnitude.
19331        for (window_secs, expected) in [
19332            (1u64, super::RateLimitUnit::Second),
19333            (60, super::RateLimitUnit::Minute),
19334            (3600, super::RateLimitUnit::Hour),
19335        ] {
19336            let rl = RateLimit {
19337                rate: 100,
19338                window: Duration::from_secs(window_secs),
19339            };
19340            assert_eq!(
19341                rl.canonical_unit(),
19342                Some(expected),
19343                "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
19344                 must return Some({expected:?})"
19345            );
19346        }
19347        // Non-canonical windows the validate gate rejects also return
19348        // None here — the accessor is the typed-enum projection of
19349        // the sibling `is_canonical_rate_limit_window` predicate.
19350        let bad = RateLimit {
19351            rate: 100,
19352            window: Duration::from_secs(30),
19353        };
19354        assert!(
19355            bad.canonical_unit().is_none(),
19356            "RateLimit with a non-canonical window must return None from \
19357             canonical_unit — the validate gate rejects the same set"
19358        );
19359    }
19360
19361    #[test]
19362    fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
19363        // Fail-before-pass-after byte-parity pin: for every canonical
19364        // window the [`rate_limit_codec::render`] arm's emitted string
19365        // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
19366        // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
19367        // the vestigial free helper [`rate_limit_window_unit`] (a
19368        // `find_map`-walked `Duration → &'static str` delegate) onto the
19369        // substrate primitive [`RateLimit::canonical_unit`] typed method
19370        // (a closed-set `match self.window` arm on
19371        // [`RateLimitUnit::from_window`], projected through
19372        // [`RateLimitUnit::as_suffix`] via the enum's
19373        // [`std::fmt::Display`] impl). A future re-routing of the render
19374        // arm through a differently-computed unit projection would break
19375        // this pin at build time rather than as a silent per-consumer
19376        // codec round-trip drift far from the substrate primitive edit.
19377        //
19378        // Sibling to the peer
19379        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
19380        // on the free-helper axis: that pin locks the two projections
19381        // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
19382        // on the closed-set arm table; this pin locks the codec's render
19383        // arm reads through the typed accessor rather than the free
19384        // helper. Two production consumers of the canonical-unit axis
19385        // now key off one typed dispatch on the substrate primitive.
19386        for (window_secs, unit) in [
19387            (1u64, super::RateLimitUnit::Second),
19388            (60, super::RateLimitUnit::Minute),
19389            (3600, super::RateLimitUnit::Hour),
19390        ] {
19391            let rl = RateLimit {
19392                rate: 42,
19393                window: Duration::from_secs(window_secs),
19394            };
19395            let policy = MeshPolicy {
19396                rate_limit: Some(rl),
19397                ..Default::default()
19398            };
19399            let json = serde_json::to_string(&policy).unwrap();
19400            let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
19401            assert!(
19402                json.contains(&expected),
19403                "rate_limit_codec::render must emit {expected} (via \
19404                 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
19405                 for a {window_secs}s window; serialized MeshPolicy was: {json}"
19406            );
19407            // And the accessor route resolves to the same typed unit
19408            // the render arm's Display formatting is asked to produce —
19409            // so a future edit that split the two paths (one through
19410            // the accessor, one through a re-introduced free helper)
19411            // trips this pin.
19412            assert_eq!(
19413                rl.canonical_unit(),
19414                Some(unit),
19415                "RateLimit::canonical_unit must return Some({unit:?}) for a \
19416                 {window_secs}s window; the codec render arm reads the same \
19417                 typed unit through this accessor"
19418            );
19419        }
19420    }
19421
19422    #[test]
19423    fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
19424        // Fail-before-pass-after byte-parity pin on the validate gate's
19425        // canonical-window shape probe: every non-canonical `:window`
19426        // the free-helper predicate [`is_canonical_rate_limit_window`]
19427        // rejects is also rejected by the substrate primitive
19428        // [`RateLimit::canonical_unit`] `.is_none()` route the validate
19429        // gate now reads through, and vice versa on the accepted set
19430        // (the three canonical windows). Locks the migration from the
19431        // free helper onto the substrate primitive: a future re-routing
19432        // of one of the two paths through a differently-computed unit
19433        // projection would silently split the codec's accepted set from
19434        // the validate gate's accepted set — a two-consumer drift the
19435        // codec-round-trip pin
19436        // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
19437        // above closes on the render arm and this pin closes on the
19438        // validate arm.
19439        for canonical_window_secs in [1u64, 60, 3600] {
19440            let mut s = three_member_spec();
19441            let rl = RateLimit {
19442                rate: 100,
19443                window: Duration::from_secs(canonical_window_secs),
19444            };
19445            s.politicas.rate_limit = Some(rl);
19446            assert!(
19447                s.validate().is_ok(),
19448                "canonical {canonical_window_secs}s window must pass \
19449                 validate_politicas — the validate gate now reads \
19450                 RateLimit::canonical_unit().is_none() and the accessor \
19451                 returns Some on every canonical arm"
19452            );
19453            assert!(
19454                rl.canonical_unit().is_some(),
19455                "canonical {canonical_window_secs}s window must resolve to \
19456                 Some on RateLimit::canonical_unit — the validate gate reads \
19457                 this accessor directly"
19458            );
19459        }
19460        for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
19461            let mut s = three_member_spec();
19462            let rl = RateLimit {
19463                rate: 100,
19464                window: Duration::from_secs(non_canonical_window_secs),
19465            };
19466            s.politicas.rate_limit = Some(rl);
19467            assert_eq!(
19468                s.validate().unwrap_err(),
19469                AplicacaoError::PolicyRateLimitWindowNotCanonical {
19470                    window: rl.window(),
19471                },
19472                "non-canonical {non_canonical_window_secs}s window must be \
19473                 rejected by validate_politicas — the validate gate now \
19474                 keys off RateLimit::canonical_unit().is_none()"
19475            );
19476            assert!(
19477                rl.canonical_unit().is_none(),
19478                "non-canonical {non_canonical_window_secs}s window must \
19479                 resolve to None on RateLimit::canonical_unit — the two \
19480                 paths (the free helper the validate gate previously read \
19481                 and the substrate primitive the validate gate now reads) \
19482                 must agree on the same rejected set"
19483            );
19484        }
19485        // And the substrate-primitive [`RateLimit::canonical_unit`]
19486        // accessor's accepted-window set matches the codec's parse arm's
19487        // accepted-suffix set on every canonical / non-canonical shape,
19488        // so a future silent drift between the codec's accepted set and
19489        // the validate gate's accepted set is a build error at test time
19490        // (both consumers key off the same closed-set enum's `match self`
19491        // arms). The predecessor free helper `is_canonical_rate_limit_window`
19492        // — a delegate that composed [`RateLimitUnit::from_window`] with
19493        // `.is_some()` — was deleted after this migration; the
19494        // canonical-window set now lives on exactly one typed dispatch
19495        // on the substrate primitive.
19496        for (secs, expected) in [
19497            (1u64, true),
19498            (60, true),
19499            (3600, true),
19500            (2, false),
19501            (30, false),
19502            (86_400, false),
19503        ] {
19504            let window = Duration::from_secs(secs);
19505            let rl = RateLimit { rate: 1, window };
19506            assert_eq!(
19507                rl.canonical_unit().is_some(),
19508                expected,
19509                "RateLimit::canonical_unit().is_some() must agree with the \
19510                 codec-accepted canonical-window set on {secs}s"
19511            );
19512            let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
19513                1 => "s",
19514                60 => "m",
19515                3600 => "h",
19516                _ => return,
19517            })
19518            .is_some_and(|d| d == window);
19519            if expected {
19520                assert!(
19521                    suffix_from_axis,
19522                    "the codec's `&str → Duration` axis \
19523                     ({secs}s) must round-trip to the same Duration the \
19524                     substrate primitive's accessor returns Some on"
19525                );
19526            }
19527        }
19528    }
19529
19530    #[test]
19531    fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
19532        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
19533        // derive: for each of the three variants, exactly one of the
19534        // generated `is_second` / `is_minute` / `is_hour` predicates
19535        // returns `true` and the other two return `false`. Peer of
19536        // the sibling
19537        // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
19538        // sibling `IsVariant`-derived closed-set typed-enum pins.
19539        let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
19540            (super::RateLimitUnit::Second, [true, false, false]),
19541            (super::RateLimitUnit::Minute, [false, true, false]),
19542            (super::RateLimitUnit::Hour, [false, false, true]),
19543        ];
19544        for (variant, expected) in rows {
19545            let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
19546            assert_eq!(
19547                observed, expected,
19548                "RateLimitUnit::{variant:?} is_* predicates must partition \
19549                 the arm set (second, minute, hour); got {observed:?}"
19550            );
19551        }
19552    }
19553
19554    #[test]
19555    fn rejects_policy_timeout_sub_millisecond() {
19556        // A purely sub-millisecond `Duration` (`from_micros(500)` =
19557        // 500_000 ns) is not the zero `Duration` — the `is_zero()`
19558        // arm passes — but `as_millis() == 0`, so the shared codec's
19559        // `render` arm returns the literal `"0s"`, which the
19560        // codec's `parse` arm then deserializes as `Duration::ZERO`
19561        // and the `PolicyTimeoutZero` zero-floor gate would reject
19562        // on re-validate. Pin the rejection at the typed slot's
19563        // canonical-floor gate so the round-trip break surfaces at
19564        // validate time, naming the offending `Duration`, rather
19565        // than at the next serialize → deserialize round-trip far
19566        // from the source `caixa.lisp`.
19567        let mut s = three_member_spec();
19568        let timeout = Duration::from_micros(500);
19569        s.politicas.timeout = Some(timeout);
19570        assert_eq!(
19571            s.validate().unwrap_err(),
19572            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
19573        );
19574    }
19575
19576    #[test]
19577    fn rejects_policy_timeout_non_integer_millisecond() {
19578        // A `Duration` with non-integer-millisecond residue
19579        // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
19580        // through the shared codec's `render` arm as `"1ms"` (the
19581        // `as_millis()` floor truncates), which the codec's `parse`
19582        // arm then deserializes as `Duration::from_millis(1)` =
19583        // 1_000_000 ns — silently *different* from the original.
19584        // Pin the rejection so this round-trip break surfaces at
19585        // validate time, where the offending `Duration` is named,
19586        // rather than as a silent value-laundered round-trip on the
19587        // next codec round-trip.
19588        let mut s = three_member_spec();
19589        let timeout = Duration::from_micros(1500);
19590        s.politicas.timeout = Some(timeout);
19591        assert_eq!(
19592            s.validate().unwrap_err(),
19593            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
19594        );
19595    }
19596
19597    #[test]
19598    fn accepts_policy_timeout_integer_millisecond_forms() {
19599        // The codec's accepted set — integer multiples of 1ms — is
19600        // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
19601        // `1h` all pass the canonical gate. Pin the canonical-forms
19602        // sweep so a future tightening of the codec's grammar (e.g.
19603        // dropping `:ms`) surfaces here as a test failure rather
19604        // than a silent contract narrowing on the typed slot.
19605        for timeout in [
19606            Duration::from_millis(1),
19607            Duration::from_millis(500),
19608            Duration::from_millis(1500),
19609            Duration::from_secs(30),
19610            Duration::from_secs(120),
19611            Duration::from_secs(3600),
19612        ] {
19613            let mut s = three_member_spec();
19614            s.politicas.timeout = Some(timeout);
19615            s.validate()
19616                .expect("integer-millisecond :timeout must validate");
19617        }
19618    }
19619
19620    #[test]
19621    fn policy_timeout_zero_takes_precedence_over_canonical() {
19622        // `Duration::ZERO` carries `subsec_nanos() == 0` and would
19623        // pass the canonical-millisecond gate; the more self-locating
19624        // `PolicyTimeoutZero` arm (which names the omit-axis
19625        // remediation directly) must fire first. Pin the ordering so
19626        // a future refactor that reorders the arms surfaces here as a
19627        // test failure rather than a silent diagnostic regression.
19628        let mut s = three_member_spec();
19629        s.politicas.timeout = Some(Duration::ZERO);
19630        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
19631    }
19632
19633    #[test]
19634    fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
19635        // The diagnostic envelope carries the offending `Duration`
19636        // verbatim so the author can grep their `caixa.lisp` for
19637        // `:timeout "<value>"` and fix it in one edit. Same
19638        // diagnostic shape every other typed-slot canonical-form
19639        // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
19640        // peer `:rate-limit :window` axis.
19641        let mut s = three_member_spec();
19642        let timeout = Duration::from_nanos(1_000_001);
19643        s.politicas.timeout = Some(timeout);
19644        match s.validate().unwrap_err() {
19645            AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
19646                assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
19647            }
19648            other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
19649        }
19650    }
19651
19652    #[test]
19653    fn rejects_policy_timeout_above_cap() {
19654        // The fail-before-pass-after pin: 3601s = 1h + 1s is
19655        // structurally one canonical-tick past the
19656        // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
19657        // integer-millisecond magnitude the canonical-form arm above
19658        // accepts cleanly, that the codec round-trips losslessly as
19659        // `"3601s"`, and that silently passed validate on every
19660        // pre-gate codebase because the typed slot's only checks were
19661        // the zero-floor and canonical-form arms. The mesh-level
19662        // deadline degenerates only at the runtime substrate (Envoy
19663        // / Cilium L7 timeout overlay) far from the source
19664        // `caixa.lisp` with no field naming the offending policy.
19665        let mut s = three_member_spec();
19666        let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
19667        s.politicas.timeout = Some(timeout);
19668        assert_eq!(
19669            s.validate().unwrap_err(),
19670            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
19671        );
19672    }
19673
19674    #[test]
19675    fn rejects_policy_timeout_one_millisecond_above_cap() {
19676        // Boundary case: exactly 1ms past the cap (the granularity
19677        // the canonical-form gate enforces). Catches a future
19678        // "strictly less than" half-measure and pins the diagnostic
19679        // to name the offending `Duration` verbatim. Peer of
19680        // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
19681        // boundary pin on the sibling `:limits :memory` top edge.
19682        let mut s = three_member_spec();
19683        let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
19684        s.politicas.timeout = Some(timeout);
19685        assert_eq!(
19686            s.validate().unwrap_err(),
19687            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
19688        );
19689    }
19690
19691    #[test]
19692    fn rejects_policy_timeout_far_above_cap() {
19693        // The "obvious authoring footgun" case: a `(:timeout "24h")`
19694        // or `(:timeout "86400s")` — values the canonical-form arm
19695        // accepts as integer-millisecond magnitudes, the codec
19696        // round-trips losslessly through serde, but the mesh-level
19697        // policy cannot honor (a 24-hour synchronous-`:contratos`
19698        // deadline is operationally indistinguishable from
19699        // omit-the-axis). Until this gate landed validate accepted
19700        // it. Pin both common above-cap values (24h, 7d) so a future
19701        // relaxation that drops the upper bound surfaces here.
19702        for timeout in [
19703            Duration::from_secs(86_400),    // 24h
19704            Duration::from_secs(604_800),   // 7d
19705            Duration::from_secs(1_000_000), // ~11.5 days
19706        ] {
19707            let mut s = three_member_spec();
19708            s.politicas.timeout = Some(timeout);
19709            assert_eq!(
19710                s.validate().unwrap_err(),
19711                AplicacaoError::PolicyTimeoutExceedsCap { timeout }
19712            );
19713        }
19714    }
19715
19716    #[test]
19717    fn accepts_policy_timeout_at_cap() {
19718        // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
19719        // must validate. The cap is inclusive on the top edge,
19720        // matching the [`POLICY_RETRIES_MAX`] /
19721        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
19722        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
19723        // sibling capped axes. Pin the boundary explicitly so a
19724        // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
19725        // instead of `>`) surfaces here as a test failure rather
19726        // than a silent contract narrowing.
19727        let mut s = three_member_spec();
19728        s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
19729        s.validate()
19730            .expect("timeout == POLICY_TIMEOUT_MAX must validate");
19731    }
19732
19733    #[test]
19734    fn accepts_policy_timeout_typical_values() {
19735        // The documented production-playbook band positive-control
19736        // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
19737        // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
19738        // plus a sweep through the long-running-workflow band
19739        // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
19740        // validated set explicitly so a future tightening of the
19741        // ceiling surfaces here as a deliberate test edit, not a
19742        // silent contract narrowing.
19743        for timeout in [
19744            Duration::from_millis(1),
19745            Duration::from_millis(500),
19746            Duration::from_secs(1),
19747            Duration::from_secs(10),
19748            Duration::from_secs(15), // Envoy default
19749            Duration::from_secs(30),
19750            Duration::from_secs(60), // AWS App Mesh typical
19751            Duration::from_secs(300),
19752            Duration::from_secs(900),
19753            Duration::from_secs(1800),
19754            Duration::from_secs(3600), // exactly 1h, the cap
19755        ] {
19756            let mut s = three_member_spec();
19757            s.politicas.timeout = Some(timeout);
19758            s.validate()
19759                .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
19760        }
19761    }
19762
19763    #[test]
19764    fn policy_timeout_zero_takes_precedence_over_cap() {
19765        // The cross-arm ordering pin: `Duration::ZERO` is
19766        // structurally outside both `>= 1ms` (zero-floor) and
19767        // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
19768        // diagnostic is the more self-locating one (it directly
19769        // names the omit-axis remediation), so the validate gate
19770        // must fire on zero first. Same shape every other
19771        // zero-then-shape ordering on this surface uses
19772        // ([`AplicacaoError::PolicyRetriesZero`] then
19773        // [`AplicacaoError::PolicyRetriesExceedsCap`];
19774        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
19775        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
19776        let mut s = three_member_spec();
19777        s.politicas.timeout = Some(Duration::ZERO);
19778        assert_eq!(
19779            s.validate().unwrap_err(),
19780            AplicacaoError::PolicyTimeoutZero,
19781            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
19782        );
19783    }
19784
19785    #[test]
19786    fn policy_timeout_canonical_takes_precedence_over_cap() {
19787        // The cross-arm ordering pin: a `Duration` that is *both*
19788        // sub-millisecond (non-canonical-form) and structurally
19789        // above the cap surfaces the canonical-form diagnostic
19790        // first, because the round-trip-shape break is the more
19791        // fundamental issue (the value can't even round-trip
19792        // through the codec, so the cap diagnostic naming
19793        // `1ms..=1h` would be misleading — there's no integer-ms
19794        // form of the offending value). Pin the order so a future
19795        // refactor that reorders the arms surfaces here as a test
19796        // failure rather than a silent diagnostic regression.
19797        let mut s = three_member_spec();
19798        // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
19799        // *and* total magnitude above the 1h cap.
19800        let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
19801        s.politicas.timeout = Some(timeout);
19802        assert_eq!(
19803            s.validate().unwrap_err(),
19804            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
19805            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
19806        );
19807    }
19808
19809    #[test]
19810    fn policy_timeout_cap_diagnostic_carries_offending_value() {
19811        // The diagnostic-shape pin: the offending `Duration` is
19812        // carried verbatim into the
19813        // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
19814        // surfaced error message names the value the author wrote
19815        // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
19816        // exceeds the mesh-policy ceiling …"`), not just the cap.
19817        // Same self-locating diagnostic shape every other typed-cap
19818        // arm on this surface carries
19819        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
19820        // offending retry count verbatim).
19821        let mut s = three_member_spec();
19822        let timeout = Duration::from_secs(7200); // 2h
19823        s.politicas.timeout = Some(timeout);
19824        let err = s.validate().unwrap_err();
19825        assert!(
19826            matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
19827            "got {err:?}"
19828        );
19829        let msg = err.to_string();
19830        assert!(
19831            msg.contains("7200"),
19832            ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
19833        );
19834    }
19835
19836    #[test]
19837    fn policy_timeout_cap_pins_canonical_value() {
19838        // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
19839        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
19840        // the shared duration codec emits as a clean canonical
19841        // string (`"<n>h"`). Pinning the literal value here surfaces
19842        // a future drift (a relaxation to 24h, a tightening to 5m)
19843        // as a deliberate test edit, not a silent contract
19844        // narrowing. Same shape every other typed-cap value pin on
19845        // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
19846        assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
19847        assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
19848    }
19849
19850    #[test]
19851    fn policy_timeout_cap_value_round_trips_through_codec() {
19852        // The codec round-trip property the cap arm preserves: the
19853        // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
19854        // the shared duration codec — every value at the cap renders
19855        // to a clean canonical string (`"1h"`) and parses back to
19856        // the same `Duration`. Pin this so a future drift between
19857        // the cap constant and the codec's largest emitted unit
19858        // surfaces here. Same shape every other typed boundary pin
19859        // on this surface uses
19860        // (`wasm32_memory_cap_matches_parsed_4_gib`).
19861        let policy = MeshPolicy {
19862            timeout: Some(POLICY_TIMEOUT_MAX),
19863            ..Default::default()
19864        };
19865        let json = serde_json::to_string(&policy).unwrap();
19866        // The codec emits `"1h"` for the canonical 1-hour magnitude.
19867        assert!(
19868            json.contains("\"1h\""),
19869            "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
19870        );
19871        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
19872        assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
19873    }
19874
19875    #[test]
19876    fn rejects_circuit_breaker_window_sub_millisecond() {
19877        // Peer of the `:timeout` sub-millisecond arm on the second
19878        // typed-`Duration` `:politicas` axis: a purely sub-ms
19879        // `Duration` (`from_micros(500)`) renders through the shared
19880        // codec as `"0s"`, which the codec parses back to
19881        // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
19882        // zero-floor gate then rejects on re-validate.
19883        let mut s = three_member_spec();
19884        let window = Duration::from_micros(500);
19885        s.politicas.circuit_breaker = Some(CircuitBreaker {
19886            max_failures: 5,
19887            window,
19888        });
19889        assert_eq!(
19890            s.validate().unwrap_err(),
19891            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
19892        );
19893    }
19894
19895    #[test]
19896    fn rejects_circuit_breaker_window_non_integer_millisecond() {
19897        // Peer of the `:timeout` non-integer-ms arm: a `Duration`
19898        // with non-integer-millisecond residue renders through the
19899        // shared codec as the truncated `"<n>ms"` form, parsing back
19900        // to a *different* `Duration` on the next round-trip.
19901        let mut s = three_member_spec();
19902        let window = Duration::from_micros(1500);
19903        s.politicas.circuit_breaker = Some(CircuitBreaker {
19904            max_failures: 5,
19905            window,
19906        });
19907        assert_eq!(
19908            s.validate().unwrap_err(),
19909            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
19910        );
19911    }
19912
19913    #[test]
19914    fn accepts_circuit_breaker_window_integer_millisecond_forms() {
19915        // The canonical-forms sweep on the breaker axis: every
19916        // integer-ms multiple the codec round-trips losslessly
19917        // passes the canonical gate.
19918        //
19919        // Clears `:timeout` from the fixture so this per-axis sweep
19920        // covers windows shorter than the fixture's 30s timeout
19921        // (1ms, 500ms, 1500ms) — the sub-timeout arm is a
19922        // structurally-inert breaker
19923        // ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]) that
19924        // the cross-axis gate at the end of
19925        // [`AplicacaoSpec::validate_politicas`] rejects on the paired
19926        // `(:timeout, :window)` shape, not on the per-axis
19927        // integer-millisecond canonical-form shape this test pins.
19928        // The paired shape is covered by
19929        // `rejects_circuit_breaker_window_below_timeout`.
19930        for window in [
19931            Duration::from_millis(1),
19932            Duration::from_millis(500),
19933            Duration::from_millis(1500),
19934            Duration::from_secs(30),
19935            Duration::from_secs(60),
19936            Duration::from_secs(3600),
19937        ] {
19938            let mut s = three_member_spec();
19939            s.politicas.timeout = None;
19940            s.politicas.circuit_breaker = Some(CircuitBreaker {
19941                max_failures: 5,
19942                window,
19943            });
19944            s.validate()
19945                .expect("integer-millisecond :circuit-breaker :window must validate");
19946        }
19947    }
19948
19949    #[test]
19950    fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
19951        // `Duration::ZERO` would pass the canonical-ms gate (the
19952        // sub-ns residue is zero) but must surface the narrower
19953        // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
19954        // remediation.
19955        let mut s = three_member_spec();
19956        s.politicas.circuit_breaker = Some(CircuitBreaker {
19957            max_failures: 5,
19958            window: Duration::ZERO,
19959        });
19960        assert_eq!(
19961            s.validate().unwrap_err(),
19962            AplicacaoError::PolicyBreakerZeroWindow
19963        );
19964    }
19965
19966    #[test]
19967    fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
19968        // Both axes invalid: max_failures == 0 *and* window is
19969        // sub-ms. The validate gate must fire on max_failures first
19970        // (matching the existing ordering pin
19971        // `rejects_circuit_breaker_zero_max_failures` enshrines), so
19972        // the existing diagnostic continues to lead with the simpler
19973        // "zero threshold" framing.
19974        let mut s = three_member_spec();
19975        s.politicas.circuit_breaker = Some(CircuitBreaker {
19976            max_failures: 0,
19977            window: Duration::from_micros(500),
19978        });
19979        assert_eq!(
19980            s.validate().unwrap_err(),
19981            AplicacaoError::PolicyBreakerZeroFailures
19982        );
19983    }
19984
19985    #[test]
19986    fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
19987        let mut s = three_member_spec();
19988        let window = Duration::from_nanos(60_000_000_001);
19989        s.politicas.circuit_breaker = Some(CircuitBreaker {
19990            max_failures: 5,
19991            window,
19992        });
19993        match s.validate().unwrap_err() {
19994            AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
19995                assert_eq!(w, window, "diagnostic must carry the offending Duration");
19996            }
19997            other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
19998        }
19999    }
20000
20001    #[test]
20002    fn rejects_circuit_breaker_window_above_cap() {
20003        // The fail-before-pass-after pin: 3601s = 1h + 1s is
20004        // structurally one canonical-tick past the
20005        // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
20006        // integer-millisecond magnitude the canonical-form arm above
20007        // accepts cleanly, that the codec round-trips losslessly as
20008        // `"3601s"`, and that silently passed validate on every
20009        // pre-gate codebase because the typed slot's only checks were
20010        // the zero-floor and canonical-form arms. The
20011        // rolling-window-to-lifetime-counter degeneration surfaces
20012        // only at the runtime substrate (Envoy's outlier_detection
20013        // interval, the future CiliumClusterwideEnvoyConfig overlay)
20014        // far from the source `caixa.lisp` with no field naming the
20015        // offending policy.
20016        let mut s = three_member_spec();
20017        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
20018        s.politicas.circuit_breaker = Some(CircuitBreaker {
20019            max_failures: 5,
20020            window,
20021        });
20022        assert_eq!(
20023            s.validate().unwrap_err(),
20024            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
20025        );
20026    }
20027
20028    #[test]
20029    fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
20030        // Boundary case: exactly 1ms past the cap (the granularity the
20031        // canonical-form gate enforces). Catches a future "strictly
20032        // less than" half-measure and pins the diagnostic to name the
20033        // offending `Duration` verbatim. Peer of
20034        // `rejects_policy_timeout_one_millisecond_above_cap` on the
20035        // sibling duration-typed `:politicas :timeout` top edge.
20036        let mut s = three_member_spec();
20037        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
20038        s.politicas.circuit_breaker = Some(CircuitBreaker {
20039            max_failures: 5,
20040            window,
20041        });
20042        assert_eq!(
20043            s.validate().unwrap_err(),
20044            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
20045        );
20046    }
20047
20048    #[test]
20049    fn rejects_circuit_breaker_window_far_above_cap() {
20050        // The "obvious authoring footgun" case: a `(:window "24h")` or
20051        // `(:window "86400s")` — values the canonical-form arm
20052        // accepts as integer-millisecond magnitudes, the codec
20053        // round-trips losslessly through serde, but the
20054        // rolling-window breaker contract cannot honor (a 24-hour
20055        // rolling failure window is operationally a lifetime counter).
20056        // Until this gate landed validate accepted it. Pin both common
20057        // above-cap values (24h, 7d) so a future relaxation that
20058        // drops the upper bound surfaces here.
20059        for window in [
20060            Duration::from_secs(86_400),    // 24h
20061            Duration::from_secs(604_800),   // 7d
20062            Duration::from_secs(1_000_000), // ~11.5 days
20063        ] {
20064            let mut s = three_member_spec();
20065            s.politicas.circuit_breaker = Some(CircuitBreaker {
20066                max_failures: 5,
20067                window,
20068            });
20069            assert_eq!(
20070                s.validate().unwrap_err(),
20071                AplicacaoError::PolicyBreakerWindowExceedsCap { window }
20072            );
20073        }
20074    }
20075
20076    #[test]
20077    fn accepts_circuit_breaker_window_at_cap() {
20078        // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
20079        // (1h) — must validate. The cap is inclusive on the top edge,
20080        // matching the [`POLICY_TIMEOUT_MAX`] /
20081        // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
20082        // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
20083        // sibling capped axes. Pin the boundary explicitly so a
20084        // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
20085        // instead of `>`) surfaces here as a test failure rather than
20086        // a silent contract narrowing.
20087        let mut s = three_member_spec();
20088        s.politicas.circuit_breaker = Some(CircuitBreaker {
20089            max_failures: 5,
20090            window: POLICY_BREAKER_WINDOW_MAX,
20091        });
20092        s.validate()
20093            .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
20094    }
20095
20096    #[test]
20097    fn accepts_circuit_breaker_window_typical_values() {
20098        // The documented production-playbook band positive-control
20099        // sweep — every value Hystrix / resilience4j / Istio / Envoy
20100        // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
20101        // through the long-tail failure-detection band (15m, 30m, 1h)
20102        // the cap accepts. Pin the inclusive validated set explicitly
20103        // so a future tightening of the ceiling surfaces here as a
20104        // deliberate test edit, not a silent contract narrowing.
20105        //
20106        // Clears `:timeout` from the fixture so this per-axis sweep
20107        // covers windows shorter than the fixture's 30s timeout
20108        // (Hystrix's 10s default, resilience4j's 30s, and the
20109        // sub-second warm-up band) — every such value is a
20110        // structurally-inert breaker under the cross-axis gate at the
20111        // end of [`AplicacaoSpec::validate_politicas`]
20112        // ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]), and
20113        // the paired `(:timeout, :window)` shape is covered by
20114        // `rejects_circuit_breaker_window_below_timeout`; this
20115        // per-axis pin ranges only over the per-axis-bracket accept set.
20116        for window in [
20117            Duration::from_millis(1),
20118            Duration::from_millis(500),
20119            Duration::from_secs(1),
20120            Duration::from_secs(10), // Hystrix / Istio / Envoy default
20121            Duration::from_secs(30),
20122            Duration::from_secs(60),  // resilience4j typical
20123            Duration::from_secs(300), // AWS App Mesh typical
20124            Duration::from_secs(900),
20125            Duration::from_secs(1800),
20126            Duration::from_secs(3600), // exactly 1h, the cap
20127        ] {
20128            let mut s = three_member_spec();
20129            s.politicas.timeout = None;
20130            s.politicas.circuit_breaker = Some(CircuitBreaker {
20131                max_failures: 5,
20132                window,
20133            });
20134            s.validate()
20135                .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
20136        }
20137    }
20138
20139    #[test]
20140    fn circuit_breaker_zero_window_takes_precedence_over_cap() {
20141        // The cross-arm ordering pin: `Duration::ZERO` is structurally
20142        // outside both `>= 1ms` (zero-floor) and
20143        // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
20144        // diagnostic is the more self-locating one (it directly names
20145        // the omit-axis remediation), so the validate gate must fire
20146        // on zero first. Same shape every other zero-then-cap
20147        // ordering on this surface uses
20148        // ([`AplicacaoError::PolicyTimeoutZero`] then
20149        // [`AplicacaoError::PolicyTimeoutExceedsCap`];
20150        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
20151        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
20152        let mut s = three_member_spec();
20153        s.politicas.circuit_breaker = Some(CircuitBreaker {
20154            max_failures: 5,
20155            window: Duration::ZERO,
20156        });
20157        assert_eq!(
20158            s.validate().unwrap_err(),
20159            AplicacaoError::PolicyBreakerZeroWindow,
20160            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
20161        );
20162    }
20163
20164    #[test]
20165    fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
20166        // The cross-arm ordering pin: a `Duration` that is *both*
20167        // sub-millisecond (non-canonical-form) and structurally above
20168        // the cap surfaces the canonical-form diagnostic first,
20169        // because the round-trip-shape break is the more fundamental
20170        // issue (the value can't even round-trip through the codec, so
20171        // the cap diagnostic naming `1ms..=1h` would be misleading —
20172        // there's no integer-ms form of the offending value). Pin the
20173        // order so a future refactor that reorders the arms surfaces
20174        // here as a test failure rather than a silent diagnostic
20175        // regression. Peer of
20176        // `policy_timeout_canonical_takes_precedence_over_cap` on the
20177        // sibling duration-typed `:politicas :timeout` axis.
20178        let mut s = three_member_spec();
20179        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
20180        s.politicas.circuit_breaker = Some(CircuitBreaker {
20181            max_failures: 5,
20182            window,
20183        });
20184        assert_eq!(
20185            s.validate().unwrap_err(),
20186            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
20187            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
20188        );
20189    }
20190
20191    #[test]
20192    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
20193        // The cross-arm ordering pin between the two breaker axes: a
20194        // `CircuitBreaker` whose *both* `max_failures` is above its
20195        // cap *and* `window` is above its cap surfaces the
20196        // max-failures cap diagnostic first, because the validate
20197        // gate visits the failures arm before the window arm. Pin the
20198        // order so a future refactor that reorders the breaker arms
20199        // surfaces here.
20200        let mut s = three_member_spec();
20201        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
20202        s.politicas.circuit_breaker = Some(CircuitBreaker {
20203            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
20204            window,
20205        });
20206        assert_eq!(
20207            s.validate().unwrap_err(),
20208            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
20209                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
20210            },
20211            "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
20212        );
20213    }
20214
20215    #[test]
20216    fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
20217        // The diagnostic-shape pin: the offending `Duration` is
20218        // carried verbatim into the
20219        // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
20220        // the surfaced error message names the value the author wrote
20221        // (`":politicas :circuit-breaker :window (Duration { secs:
20222        // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
20223        // just the cap. Same self-locating diagnostic shape every
20224        // other typed-cap arm on this surface carries
20225        // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
20226        // offending `Duration` verbatim).
20227        let mut s = three_member_spec();
20228        let window = Duration::from_secs(7200); // 2h
20229        s.politicas.circuit_breaker = Some(CircuitBreaker {
20230            max_failures: 5,
20231            window,
20232        });
20233        let err = s.validate().unwrap_err();
20234        assert!(
20235            matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
20236            "got {err:?}"
20237        );
20238        let msg = err.to_string();
20239        assert!(
20240            msg.contains("7200"),
20241            ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
20242        );
20243    }
20244
20245    #[test]
20246    fn circuit_breaker_window_cap_pins_canonical_value() {
20247        // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
20248        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
20249        // shared duration codec emits as a clean canonical string
20250        // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
20251        // the sibling duration-typed `:politicas :timeout` axis (the
20252        // two duration-typed `:politicas` axes share a uniform top
20253        // edge). Pinning the literal value here surfaces a future
20254        // drift (a relaxation to 24h, a tightening to 5m) as a
20255        // deliberate test edit, not a silent contract narrowing. Same
20256        // shape every other typed-cap value pin on this surface uses
20257        // (`policy_timeout_cap_pins_canonical_value`).
20258        assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
20259        assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
20260        assert_eq!(
20261            POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
20262            "the two duration-typed `:politicas` caps share the same top edge"
20263        );
20264    }
20265
20266    #[test]
20267    fn circuit_breaker_window_cap_value_round_trips_through_codec() {
20268        // The codec round-trip property the cap arm preserves: the
20269        // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
20270        // through the shared duration codec — every value at the cap
20271        // renders to a clean canonical string (`"1h"`) and parses back
20272        // to the same `Duration`. Pin this so a future drift between
20273        // the cap constant and the codec's largest emitted unit
20274        // surfaces here. Same shape every other typed boundary pin on
20275        // this surface uses
20276        // (`policy_timeout_cap_value_round_trips_through_codec`).
20277        let policy = MeshPolicy {
20278            circuit_breaker: Some(CircuitBreaker {
20279                max_failures: 5,
20280                window: POLICY_BREAKER_WINDOW_MAX,
20281            }),
20282            ..Default::default()
20283        };
20284        let json = serde_json::to_string(&policy).unwrap();
20285        // The codec emits `"1h"` for the canonical 1-hour magnitude.
20286        assert!(
20287            json.contains("\"1h\""),
20288            "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
20289        );
20290        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
20291        assert_eq!(
20292            back.circuit_breaker.unwrap().window,
20293            POLICY_BREAKER_WINDOW_MAX
20294        );
20295    }
20296
20297    #[test]
20298    fn is_integer_millisecond_duration_predicate_tracks_codec() {
20299        // Pin the predicate's accepted set against the codec's
20300        // accepted set explicitly. The codec parses
20301        // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
20302        // accepted value is an integer-millisecond multiple — so the
20303        // predicate must accept exactly that set. Same shape every
20304        // other predicate-on-the-typed-slot helper carries
20305        // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
20306        // Read directly from the codec-owned predicate — the crate's
20307        // single source of truth every typed-`Duration` axis now routes
20308        // through via
20309        // [`crate::render::require_positive_canonical_bounded_duration`].
20310        use super::supervisor::duration_codec::is_integer_millisecond_duration;
20311        assert!(is_integer_millisecond_duration(Duration::ZERO));
20312        assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
20313        assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
20314        assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
20315        assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
20316        assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
20317        // Non-integer-millisecond residue: rejected.
20318        assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
20319        assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
20320        assert!(!is_integer_millisecond_duration(Duration::from_micros(
20321            1500
20322        )));
20323        assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
20324        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
20325            999_999
20326        )));
20327        // The 1-ns-past-1ms boundary: rejected (no longer a clean
20328        // integer-millisecond multiple).
20329        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
20330            1_000_001
20331        )));
20332    }
20333
20334    #[test]
20335    fn policy_timeout_validated_value_round_trips_through_codec() {
20336        // The structural property the canonical-ms gate enforces:
20337        // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
20338        // round-trips losslessly through the shared `duration_codec`
20339        // (serialize → string → deserialize → equal value). Pin this
20340        // end-to-end so a future change to either side (the validate
20341        // gate's accepted granularity, the codec's parse/render unit
20342        // set) that breaks the alignment surfaces here. The
20343        // previous-state shape (typed slot accepts arbitrary
20344        // `Duration`, codec only round-trips integer-ms) would fail
20345        // this test for any `Duration::from_micros(1500)` timeout —
20346        // the validate gate now forecloses that.
20347        for timeout in [
20348            Duration::from_millis(1),
20349            Duration::from_millis(1500),
20350            Duration::from_secs(30),
20351            Duration::from_secs(3600),
20352        ] {
20353            let mut s = three_member_spec();
20354            s.politicas.timeout = Some(timeout);
20355            s.validate().unwrap();
20356            let json = serde_json::to_string(&s.politicas).unwrap();
20357            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
20358            assert_eq!(
20359                back.timeout, s.politicas.timeout,
20360                "every validated :timeout must round-trip losslessly through the codec"
20361            );
20362        }
20363    }
20364
20365    #[test]
20366    fn circuit_breaker_window_validated_value_round_trips_through_codec() {
20367        // Peer of the `:timeout` round-trip property on the breaker
20368        // axis.
20369        //
20370        // Clears `:timeout` from the fixture so the round-trip pin
20371        // ranges over sub-timeout `Duration` values (1ms, 1500ms) the
20372        // cross-axis gate would otherwise reject as structurally-inert
20373        // breakers ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]);
20374        // the paired `(:timeout, :window)` cross-axis relation is
20375        // pinned separately by
20376        // `rejects_circuit_breaker_window_below_timeout`, and this
20377        // property is a pure serde-codec round-trip on the per-axis
20378        // slot.
20379        for window in [
20380            Duration::from_millis(1),
20381            Duration::from_millis(1500),
20382            Duration::from_secs(30),
20383            Duration::from_secs(3600),
20384        ] {
20385            let mut s = three_member_spec();
20386            s.politicas.timeout = None;
20387            s.politicas.circuit_breaker = Some(CircuitBreaker {
20388                max_failures: 5,
20389                window,
20390            });
20391            s.validate().unwrap();
20392            let json = serde_json::to_string(&s.politicas).unwrap();
20393            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
20394            assert_eq!(
20395                back.circuit_breaker.unwrap().window,
20396                window,
20397                "every validated :circuit-breaker :window must round-trip losslessly"
20398            );
20399        }
20400    }
20401
20402    #[test]
20403    fn rejects_circuit_breaker_window_below_timeout() {
20404        // The fail-before-pass-after pin on the cross-axis
20405        // `(:timeout, :circuit-breaker :window)` invariant. Each axis
20406        // is individually well-formed under its own per-axis bracket
20407        // (both integer-millisecond, both above the zero floor, both
20408        // below the cap), but the pair is a structurally-inert
20409        // breaker: a call dispatched at t=0 is declared failed at
20410        // t=30s, by which point the 10s rolling window open at
20411        // dispatch has already rolled twice, so no window can hold
20412        // a timeout-derived failure however high the call volume.
20413        //
20414        // Envoy's `outlier_detection.interval` against the per-route
20415        // request timeout carries the identical relation; Hystrix
20416        // ships the canonical ratio in its defaults (10s window
20417        // against a 1s timeout — a 10× ratio, not a 3× under-ratio).
20418        //
20419        // Pin both the diagnostic arm and the payload values so a
20420        // future re-shape of the arm surfaces here as a deliberate
20421        // test edit.
20422        let mut s = three_member_spec();
20423        s.politicas.timeout = Some(Duration::from_secs(30));
20424        s.politicas.circuit_breaker = Some(CircuitBreaker {
20425            max_failures: 5,
20426            window: Duration::from_secs(10),
20427        });
20428        assert_eq!(
20429            s.validate().unwrap_err(),
20430            AplicacaoError::PolicyBreakerWindowBelowTimeout {
20431                window: Duration::from_secs(10),
20432                timeout: Duration::from_secs(30),
20433            }
20434        );
20435    }
20436
20437    #[test]
20438    fn accepts_circuit_breaker_window_equal_to_timeout() {
20439        // Boundary pin: `:window == :timeout` is the smallest window
20440        // that structurally admits at least one full timeout-derived
20441        // failure before the rolling interval closes (the invariant
20442        // is `:window >= :timeout`, not strict inequality). Catches
20443        // a future off-by-one tightening that would drift the accept
20444        // set away from the codified [`MeshPolicy::breaker_window_
20445        // observes_timeout`] predicate.
20446        let mut s = three_member_spec();
20447        s.politicas.timeout = Some(Duration::from_secs(30));
20448        s.politicas.circuit_breaker = Some(CircuitBreaker {
20449            max_failures: 5,
20450            window: Duration::from_secs(30),
20451        });
20452        s.validate()
20453            .expect("window == timeout is the boundary accept case");
20454    }
20455
20456    #[test]
20457    fn accepts_circuit_breaker_window_above_timeout() {
20458        // Positive-control sweep across the production-playbook band —
20459        // Hystrix (1s timeout / 10s window, 10× ratio), Istio (5s /
20460        // 30s, 6×), Envoy (10s / 60s, 6×), resilience4j (30s / 300s,
20461        // 10×), AWS App Mesh (60s / 300s, 5×). Every pair a real
20462        // playbook recommends must validate under the cross-axis gate.
20463        for (timeout, window) in [
20464            (Duration::from_secs(1), Duration::from_secs(10)),
20465            (Duration::from_secs(5), Duration::from_secs(30)),
20466            (Duration::from_secs(10), Duration::from_secs(60)),
20467            (Duration::from_secs(30), Duration::from_secs(300)),
20468            (Duration::from_secs(60), Duration::from_secs(300)),
20469        ] {
20470            let mut s = three_member_spec();
20471            s.politicas.timeout = Some(timeout);
20472            s.politicas.circuit_breaker = Some(CircuitBreaker {
20473                max_failures: 5,
20474                window,
20475            });
20476            s.validate().unwrap_or_else(|e| {
20477                panic!(
20478                    "production-playbook pair timeout={timeout:?}/window={window:?} must \
20479                     validate; got {e:?}"
20480                )
20481            });
20482        }
20483    }
20484
20485    #[test]
20486    fn circuit_breaker_window_below_timeout_by_one_millisecond_rejected() {
20487        // Off-by-one boundary pin: a window exactly 1ms shy of the
20488        // timeout is still structurally inert under the invariant
20489        // (the dispatch-to-report lag is `timeout`, so the window
20490        // must span at least one such lag). Catches a future
20491        // strict-inequality relaxation that would silently drift
20492        // the accept boundary.
20493        let timeout = Duration::from_secs(30);
20494        let window = Duration::from_millis(29_999);
20495        let mut s = three_member_spec();
20496        s.politicas.timeout = Some(timeout);
20497        s.politicas.circuit_breaker = Some(CircuitBreaker {
20498            max_failures: 5,
20499            window,
20500        });
20501        assert_eq!(
20502            s.validate().unwrap_err(),
20503            AplicacaoError::PolicyBreakerWindowBelowTimeout { window, timeout }
20504        );
20505    }
20506
20507    #[test]
20508    fn cross_axis_gate_vacuous_when_timeout_absent() {
20509        // The predicate is vacuously `true` when `:timeout` is None —
20510        // a `:circuit-breaker` alone declares no relation to a
20511        // substrate-imposed deadline (the failure signal reaches the
20512        // breaker from the transport's own error surface, so no
20513        // dispatch-to-report lag is knowable at author time). Pin so
20514        // a future tightening that made the gate opinionated on
20515        // half-declared pairs surfaces here.
20516        let mut s = three_member_spec();
20517        s.politicas.timeout = None;
20518        s.politicas.circuit_breaker = Some(CircuitBreaker {
20519            max_failures: 5,
20520            window: Duration::from_millis(1),
20521        });
20522        s.validate().expect(
20523            "cross-axis gate must be vacuous when :timeout is None, however small :window is",
20524        );
20525    }
20526
20527    #[test]
20528    fn cross_axis_gate_vacuous_when_circuit_breaker_absent() {
20529        // Peer of the sibling `:timeout`-absent case: a `:timeout`
20530        // without a `:circuit-breaker` declares a per-call deadline
20531        // without any rolling-window failure accounting, so the pair
20532        // is undeclared and the cross-axis gate has nothing to check.
20533        let mut s = three_member_spec();
20534        s.politicas.timeout = Some(Duration::from_secs(3600));
20535        s.politicas.circuit_breaker = None;
20536        s.validate().expect(
20537            "cross-axis gate must be vacuous when :circuit-breaker is None, \
20538             however large :timeout is",
20539        );
20540    }
20541
20542    #[test]
20543    fn cross_axis_gate_runs_after_per_axis_brackets() {
20544        // Ordering pin: a pair whose window is *both* zero-floor-
20545        // violating and structurally below the timeout must surface
20546        // the per-axis zero-floor arm first — the zero-floor
20547        // diagnostic is more self-locating (its omit-axis remediation
20548        // is directly named), where the cross-axis arm would send the
20549        // author to reconcile two values one of which is not a
20550        // meaningful window at all. Same ordering discipline every
20551        // per-axis bracket carries internally (zero-floor before
20552        // canonical-form before cap).
20553        let mut s = three_member_spec();
20554        s.politicas.timeout = Some(Duration::from_secs(30));
20555        s.politicas.circuit_breaker = Some(CircuitBreaker {
20556            max_failures: 5,
20557            window: Duration::ZERO,
20558        });
20559        assert_eq!(
20560            s.validate().unwrap_err(),
20561            AplicacaoError::PolicyBreakerZeroWindow,
20562            "per-axis zero-floor arm must fire before the cross-axis gate"
20563        );
20564    }
20565
20566    #[test]
20567    fn breaker_window_observes_timeout_predicate_matches_gate_semantic() {
20568        // Equivalence pin: the substrate-canonical
20569        // [`MeshPolicy::breaker_window_observes_timeout`] predicate
20570        // and the [`AplicacaoSpec::validate_politicas`] cross-axis
20571        // arm must discriminate the same set on every pair covered
20572        // by their shared invariant. A future refactor of either
20573        // side that breaks the equivalence trips here rather than as
20574        // a divergence between the predicate's Boolean answer and
20575        // the validate gate's Ok/Err arm — the same
20576        // predicate-vs-gate coherence discipline the peer
20577        // [`PlacementStrategy::is_shard_keyed`] predicate carries
20578        // against `AplicacaoSpec::validate_placement`. The sweep
20579        // covers both arms of the invariant (below, equal, above)
20580        // and both vacuous arms (None `:timeout`, None
20581        // `:circuit-breaker`), so the equivalence holds
20582        // exhaustively over the axis-covered accept and reject sets.
20583        let cases: &[(Option<Duration>, Option<Duration>)] = &[
20584            (Some(Duration::from_secs(30)), Some(Duration::from_secs(10))),
20585            (Some(Duration::from_secs(30)), Some(Duration::from_secs(29))),
20586            (Some(Duration::from_secs(30)), Some(Duration::from_secs(30))),
20587            (Some(Duration::from_secs(30)), Some(Duration::from_secs(60))),
20588            (Some(Duration::from_secs(1)), Some(Duration::from_secs(10))),
20589            (None, Some(Duration::from_secs(1))),
20590            (Some(Duration::from_secs(30)), None),
20591            (None, None),
20592        ];
20593        for (timeout, window) in cases.iter().copied() {
20594            let politicas = MeshPolicy {
20595                timeout,
20596                circuit_breaker: window.map(|w| CircuitBreaker {
20597                    max_failures: 5,
20598                    window: w,
20599                }),
20600                ..Default::default()
20601            };
20602            let predicate = politicas.breaker_window_observes_timeout();
20603
20604            let mut s = three_member_spec();
20605            s.politicas = politicas.clone();
20606            let gate_ok = !matches!(
20607                s.validate(),
20608                Err(AplicacaoError::PolicyBreakerWindowBelowTimeout { .. })
20609            );
20610
20611            assert_eq!(
20612                predicate, gate_ok,
20613                "predicate must agree with validate arm on pair \
20614                 (timeout={timeout:?}, window={window:?})"
20615            );
20616        }
20617    }
20618
20619    #[test]
20620    fn rejects_rate_limit_starves_circuit_breaker() {
20621        // The fail-before-pass-after pin on the cross-axis
20622        // `(:rate-limit, :circuit-breaker)` invariant. Each axis is
20623        // individually well-formed under its own per-axis bracket
20624        // (both above the zero floor, both below the cap, rate-limit
20625        // window canonical), but the pair is a structurally-inert
20626        // breaker: the token bucket admits `1 × 10s / 3600s` ≈ 0
20627        // calls per rolling breaker window, so no window can
20628        // accumulate five failures however catastrophic the upstream
20629        // failure rate.
20630        //
20631        // Envoy's `outlier_detection.consecutive_5xx` paired against
20632        // `local_rate_limit.token_bucket.max_tokens` /
20633        // `fill_interval` carries the identical relation; every
20634        // production playbook that pairs the two axes (Envoy, Istio,
20635        // AWS App Mesh, Kong) sizes the rate at or above the
20636        // breaker's minimum-request-volume threshold for exactly this
20637        // reason.
20638        //
20639        // Pin both the diagnostic arm and the payload values so a
20640        // future re-shape of the arm surfaces here as a deliberate
20641        // test edit. Clears `:timeout` so the sibling
20642        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] gate
20643        // does not fire first on the ordering-precedent it holds
20644        // over this arm.
20645        let mut s = three_member_spec();
20646        s.politicas.timeout = None;
20647        s.politicas.circuit_breaker = Some(CircuitBreaker {
20648            max_failures: 5,
20649            window: Duration::from_secs(10),
20650        });
20651        s.politicas.rate_limit = Some(RateLimit {
20652            rate: 1,
20653            window: Duration::from_secs(3600),
20654        });
20655        assert_eq!(
20656            s.validate().unwrap_err(),
20657            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
20658                rate: 1,
20659                rl_window: Duration::from_secs(3600),
20660                max_failures: 5,
20661                cb_window: Duration::from_secs(10),
20662            }
20663        );
20664    }
20665
20666    #[test]
20667    fn accepts_rate_limit_can_trip_circuit_breaker() {
20668        // Positive-control sweep across the production-playbook band
20669        // — every pair a real playbook recommends where the rate
20670        // clearly admits enough calls per breaker window to reach
20671        // `:max-failures` must validate. Envoy default 5 failures
20672        // in 10s with 100/s (1000 calls / window, 200× the threshold),
20673        // Istio 5 in 30s with 50/s (1500 calls, 300×), Hystrix 20 in
20674        // 10s with 1000/s (10000 calls, 500×), AWS App Mesh 5 in
20675        // 300s with 10/s (3000 calls, 600×). Clears `:timeout` so
20676        // the sibling cross-axis arm is vacuous on this sweep.
20677        for (rate, rl_window, max_failures, cb_window) in [
20678            (
20679                100u32,
20680                Duration::from_secs(1),
20681                5u32,
20682                Duration::from_secs(10),
20683            ),
20684            (50, Duration::from_secs(1), 5, Duration::from_secs(30)),
20685            (1000, Duration::from_secs(1), 20, Duration::from_secs(10)),
20686            (10, Duration::from_secs(1), 5, Duration::from_secs(300)),
20687            (5000, Duration::from_secs(60), 50, Duration::from_secs(60)),
20688        ] {
20689            let mut s = three_member_spec();
20690            s.politicas.timeout = None;
20691            s.politicas.circuit_breaker = Some(CircuitBreaker {
20692                max_failures,
20693                window: cb_window,
20694            });
20695            s.politicas.rate_limit = Some(RateLimit {
20696                rate,
20697                window: rl_window,
20698            });
20699            s.validate().unwrap_or_else(|e| {
20700                panic!(
20701                    "production-playbook pair rate={rate}/{rl_window:?} \
20702                     max_failures={max_failures}/{cb_window:?} must validate; got {e:?}"
20703                )
20704            });
20705        }
20706    }
20707
20708    #[test]
20709    fn accepts_rate_limit_exactly_at_trip_threshold_per_cb_window() {
20710        // Boundary pin: `rate × cb_window == max_failures × rl_window`
20711        // is the smallest bucket capacity that structurally admits
20712        // exactly `max_failures` calls per rolling breaker window
20713        // (the invariant is `≥`, not strict inequality). Catches a
20714        // future off-by-one tightening to strict inequality that
20715        // would drift the accept set away from the codified
20716        // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicate.
20717        // 5 calls/s over a 1s breaker window == 5 max_failures.
20718        let mut s = three_member_spec();
20719        s.politicas.timeout = None;
20720        s.politicas.circuit_breaker = Some(CircuitBreaker {
20721            max_failures: 5,
20722            window: Duration::from_secs(1),
20723        });
20724        s.politicas.rate_limit = Some(RateLimit {
20725            rate: 5,
20726            window: Duration::from_secs(1),
20727        });
20728        s.validate()
20729            .expect("rate × cb_window == max_failures × rl_window is the boundary accept case");
20730    }
20731
20732    #[test]
20733    fn rejects_rate_limit_one_call_short_per_cb_window() {
20734        // Off-by-one boundary pin: exactly one call short of the trip
20735        // threshold per breaker window is still structurally inert
20736        // (the invariant is `≥`, so `<` refuses even a one-call
20737        // shortfall). 4 calls/s over a 1s window == 4 admissible
20738        // failures, one shy of the 5-`max_failures` threshold.
20739        // Catches a future strict-inequality relaxation that would
20740        // silently drift the accept boundary.
20741        let mut s = three_member_spec();
20742        s.politicas.timeout = None;
20743        s.politicas.circuit_breaker = Some(CircuitBreaker {
20744            max_failures: 5,
20745            window: Duration::from_secs(1),
20746        });
20747        s.politicas.rate_limit = Some(RateLimit {
20748            rate: 4,
20749            window: Duration::from_secs(1),
20750        });
20751        assert_eq!(
20752            s.validate().unwrap_err(),
20753            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
20754                rate: 4,
20755                rl_window: Duration::from_secs(1),
20756                max_failures: 5,
20757                cb_window: Duration::from_secs(1),
20758            }
20759        );
20760    }
20761
20762    #[test]
20763    fn cross_axis_starve_gate_vacuous_when_rate_limit_absent() {
20764        // The predicate is vacuously `true` when `:rate-limit` is
20765        // None — a `:circuit-breaker` alone declares no relation to
20766        // a substrate-imposed call rate (the failure signal reaches
20767        // the breaker from the transport's own error surface, at
20768        // whatever rate upstream callers push traffic). Pin so a
20769        // future tightening that made the gate opinionated on
20770        // half-declared pairs surfaces here.
20771        let mut s = three_member_spec();
20772        s.politicas.timeout = None;
20773        s.politicas.circuit_breaker = Some(CircuitBreaker {
20774            max_failures: 1000,
20775            window: Duration::from_millis(1),
20776        });
20777        s.politicas.rate_limit = None;
20778        s.validate().expect(
20779            "cross-axis starve gate must be vacuous when :rate-limit is None, \
20780             however high :max-failures and however small :window are",
20781        );
20782    }
20783
20784    #[test]
20785    fn cross_axis_starve_gate_vacuous_when_circuit_breaker_absent() {
20786        // Peer of the sibling `:rate-limit`-absent case: a
20787        // `:rate-limit` without a `:circuit-breaker` declares a
20788        // per-edge token-bucket rate without any failure counter to
20789        // starve, so the pair is undeclared and the cross-axis gate
20790        // has nothing to check.
20791        //
20792        // Also clears the fixture's `:retries` (which is `Some(3)`) so
20793        // the sibling cross-axis
20794        // [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] arm
20795        // (which reasons across the paired `(:retries, :rate-limit)`
20796        // pair independent of `:circuit-breaker`) is vacuous on this
20797        // pin — this test names the *starve* arm's vacuity on the
20798        // `:circuit-breaker`-absent case, not the burst arm's.
20799        let mut s = three_member_spec();
20800        s.politicas.timeout = None;
20801        s.politicas.retries = None;
20802        s.politicas.circuit_breaker = None;
20803        s.politicas.rate_limit = Some(RateLimit {
20804            rate: 1,
20805            window: Duration::from_secs(3600),
20806        });
20807        s.validate().expect(
20808            "cross-axis starve gate must be vacuous when :circuit-breaker is None, \
20809             however low :rate is",
20810        );
20811    }
20812
20813    #[test]
20814    fn cross_axis_starve_gate_runs_after_per_axis_brackets() {
20815        // Ordering pin: a pair whose rate is *both* zero-floor-
20816        // violating and structurally below the trip threshold must
20817        // surface the per-axis zero-floor arm first — the zero-floor
20818        // diagnostic is more self-locating (its omit-axis remediation
20819        // is directly named), where the cross-axis arm would send the
20820        // author to reconcile four values one of which is not a
20821        // meaningful rate at all. Same ordering discipline every
20822        // per-axis bracket carries internally (zero-floor before
20823        // canonical-form before cap), and the sibling cross-axis
20824        // `PolicyBreakerZeroWindow`-before-`PolicyBreakerWindowBelowTimeout`
20825        // ordering pins on the `(:timeout, :window)` pair.
20826        let mut s = three_member_spec();
20827        s.politicas.timeout = None;
20828        s.politicas.circuit_breaker = Some(CircuitBreaker {
20829            max_failures: 5,
20830            window: Duration::from_secs(10),
20831        });
20832        s.politicas.rate_limit = Some(RateLimit {
20833            rate: 0,
20834            window: Duration::from_secs(1),
20835        });
20836        assert_eq!(
20837            s.validate().unwrap_err(),
20838            AplicacaoError::PolicyRateLimitZero,
20839            "per-axis rate zero-floor arm must fire before the cross-axis starve gate"
20840        );
20841    }
20842
20843    #[test]
20844    fn cross_axis_starve_gate_runs_after_sibling_window_below_timeout_gate() {
20845        // Cross-axis ordering pin: a `:politicas` whose axes trip
20846        // BOTH cross-axis arms — `:window < :timeout` (the sibling
20847        // `PolicyBreakerWindowBelowTimeout` invariant) AND
20848        // `:rate-limit` starves the breaker within `:window` (this
20849        // arm) — must surface the timeout-relation diagnostic first.
20850        // The timeout arm is the per-call-deadline invariant every
20851        // synchronous edge carries whether or not `:rate-limit` is
20852        // declared, so its diagnostic is more self-locating; the
20853        // starve arm needs the reader to reason across three axes,
20854        // where the timeout arm names only two.
20855        //
20856        // A `{ timeout: 30s, window: 10s, rate: 1/h, max_failures: 5 }`
20857        // pair trips both: the window is below the timeout, and the
20858        // rate (1 call/hour) admits far fewer than 5 calls per 10s
20859        // breaker window.
20860        let mut s = three_member_spec();
20861        s.politicas.timeout = Some(Duration::from_secs(30));
20862        s.politicas.circuit_breaker = Some(CircuitBreaker {
20863            max_failures: 5,
20864            window: Duration::from_secs(10),
20865        });
20866        s.politicas.rate_limit = Some(RateLimit {
20867            rate: 1,
20868            window: Duration::from_secs(3600),
20869        });
20870        assert_eq!(
20871            s.validate().unwrap_err(),
20872            AplicacaoError::PolicyBreakerWindowBelowTimeout {
20873                window: Duration::from_secs(10),
20874                timeout: Duration::from_secs(30),
20875            },
20876            "sibling :window<:timeout cross-axis arm must fire before the \
20877             starve arm when both apply"
20878        );
20879    }
20880
20881    #[test]
20882    fn breaker_can_trip_under_rate_limit_predicate_matches_gate_semantic() {
20883        // Equivalence pin: the substrate-canonical
20884        // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicate
20885        // and the [`AplicacaoSpec::validate_politicas`] cross-axis
20886        // arm must discriminate the same set on every pair covered
20887        // by their shared invariant. A future refactor of either
20888        // side that breaks the equivalence trips here rather than as
20889        // a divergence between the predicate's Boolean answer and
20890        // the validate gate's Ok/Err arm — the same
20891        // predicate-vs-gate coherence discipline the sibling
20892        // [`MeshPolicy::breaker_window_observes_timeout`] predicate
20893        // carries against `AplicacaoSpec::validate_politicas`. The
20894        // sweep covers both arms of the invariant (strictly below,
20895        // exactly at, strictly above) and both vacuous arms (None
20896        // `:rate-limit`, None `:circuit-breaker`), so the
20897        // equivalence holds exhaustively over the axis-covered
20898        // accept and reject sets. Clears `:timeout` throughout so
20899        // the sibling `:window<:timeout` gate is vacuous on every
20900        // input.
20901        let rl = |rate: u32, secs: u64| {
20902            Some(RateLimit {
20903                rate,
20904                window: Duration::from_secs(secs),
20905            })
20906        };
20907        let cb = |max_failures: u32, secs: u64| {
20908            Some(CircuitBreaker {
20909                max_failures,
20910                window: Duration::from_secs(secs),
20911            })
20912        };
20913        let cases: &[(Option<RateLimit>, Option<CircuitBreaker>)] = &[
20914            // starving pairs (predicate = false, gate = Err)
20915            (rl(1, 3600), cb(5, 10)),
20916            (rl(4, 1), cb(5, 1)),
20917            // boundary + coherent pairs (predicate = true, gate = Ok)
20918            (rl(5, 1), cb(5, 1)),
20919            (rl(100, 1), cb(5, 10)),
20920            // vacuous arms
20921            (None, cb(5, 10)),
20922            (rl(1, 3600), None),
20923            (None, None),
20924        ];
20925        for (rate_limit, circuit_breaker) in cases.iter().copied() {
20926            let politicas = MeshPolicy {
20927                circuit_breaker,
20928                rate_limit,
20929                ..Default::default()
20930            };
20931            let predicate = politicas.breaker_can_trip_under_rate_limit();
20932
20933            let mut s = three_member_spec();
20934            s.politicas = politicas.clone();
20935            s.politicas.timeout = None;
20936            let gate_ok = !matches!(
20937                s.validate(),
20938                Err(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit { .. })
20939            );
20940
20941            assert_eq!(
20942                predicate, gate_ok,
20943                "predicate must agree with validate arm on pair \
20944                 (rate_limit={rate_limit:?}, circuit_breaker={circuit_breaker:?})"
20945            );
20946        }
20947    }
20948
20949    #[test]
20950    fn rejects_retries_saturate_breaker_trip_threshold() {
20951        // The fail-before-pass-after pin on the cross-axis
20952        // `(:retries, :circuit-breaker :max-failures)` invariant. Each
20953        // axis is individually well-formed under its own per-axis
20954        // bracket (both above the zero floor, both below the cap), but
20955        // the pair is a structurally-truncated retry policy: one
20956        // client's `retries + 1 = 4` failing attempts hit the trip
20957        // threshold on the third attempt, the breaker opens, and the
20958        // fourth attempt (the last declared retry) is blocked by the
20959        // open breaker — the substrate declared four attempts and
20960        // structurally allows three.
20961        //
20962        // Envoy's `retry_policy.num_retries` paired against
20963        // `outlier_detection.consecutive_5xx` carries the identical
20964        // relation; every production playbook that pairs the two axes
20965        // (Envoy, Istio, resilience4j, Hystrix) sizes the breaker's
20966        // trip threshold strictly above any single client's retry
20967        // budget so the breaker distinguishes one persistently-failing
20968        // client from sustained multi-client failure.
20969        //
20970        // Pin both the diagnostic arm and the payload values so a
20971        // future re-shape of the arm surfaces here as a deliberate
20972        // test edit. Clears `:timeout` and `:rate-limit` so the
20973        // sibling cross-axis
20974        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] /
20975        // [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`]
20976        // arms do not fire first on the ordering-precedent they hold
20977        // over this arm.
20978        let mut s = three_member_spec();
20979        s.politicas.timeout = None;
20980        s.politicas.retries = Some(3);
20981        s.politicas.circuit_breaker = Some(CircuitBreaker {
20982            max_failures: 3,
20983            window: Duration::from_secs(1),
20984        });
20985        s.politicas.rate_limit = None;
20986        assert_eq!(
20987            s.validate().unwrap_err(),
20988            AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
20989                retries: 3,
20990                max_failures: 3,
20991            }
20992        );
20993    }
20994
20995    #[test]
20996    fn accepts_retries_below_breaker_trip_threshold() {
20997        // Positive-control sweep across the production-playbook band
20998        // — every pair a real playbook recommends where the breaker's
20999        // trip threshold is strictly above the client's retry budget
21000        // must validate. Envoy default `num_retries: 3` with
21001        // `consecutive_5xx: 5` (breaker admits one client's 4 attempts,
21002        // opens on multi-client failures beyond that); Istio
21003        // `attempts: 3` with `consecutive5xxErrors: 5`; Hystrix
21004        // `execution.isolation.thread.timeoutInMilliseconds` + 3
21005        // retries with `requestVolumeThreshold: 20`; AWS App Mesh
21006        // `maxRetries: 5` with a `maxEjectionPercent`-derived threshold
21007        // of 10; resilience4j 2 retries with `slidingWindowSize: 10`.
21008        // Clears `:timeout` and `:rate-limit` so the sibling cross-axis
21009        // arms are vacuous on this sweep.
21010        for (retries, max_failures) in [(1u32, 5u32), (3, 5), (3, 20), (5, 10), (2, 10), (10, 1000)]
21011        {
21012            let mut s = three_member_spec();
21013            s.politicas.timeout = None;
21014            s.politicas.retries = Some(retries);
21015            s.politicas.circuit_breaker = Some(CircuitBreaker {
21016                max_failures,
21017                window: Duration::from_secs(60),
21018            });
21019            s.politicas.rate_limit = None;
21020            s.validate().unwrap_or_else(|e| {
21021                panic!(
21022                    "production-playbook pair retries={retries} \
21023                     max_failures={max_failures} must validate; got {e:?}"
21024                )
21025            });
21026        }
21027    }
21028
21029    #[test]
21030    fn accepts_retries_exactly_at_boundary_below_trip_threshold() {
21031        // Boundary pin: `max_failures == retries + 1` is the smallest
21032        // trip threshold that admits one client's exhausted retries
21033        // through completion (the R+1th failure — the last declared
21034        // retry — trips the breaker exactly as it completes, so
21035        // retries fully executed). The invariant is `>`, not `>=`,
21036        // stated in the coherent direction `max_failures > retries`.
21037        // Catches a future off-by-one tightening to
21038        // `max_failures > retries + 1` that would drift the accept set
21039        // away from the codified
21040        // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]
21041        // predicate.
21042        let mut s = three_member_spec();
21043        s.politicas.timeout = None;
21044        s.politicas.retries = Some(3);
21045        s.politicas.circuit_breaker = Some(CircuitBreaker {
21046            max_failures: 4,
21047            window: Duration::from_secs(60),
21048        });
21049        s.politicas.rate_limit = None;
21050        s.validate()
21051            .expect("max_failures == retries + 1 is the boundary accept case");
21052    }
21053
21054    #[test]
21055    fn rejects_retries_equal_to_breaker_trip_threshold() {
21056        // Off-by-one boundary pin: exactly at the trip threshold is
21057        // still structurally truncating (the invariant is `>`, so `<=`
21058        // refuses even the tight boundary). `retries = 3` with
21059        // `max_failures = 3` means the breaker trips on the third
21060        // failure — the last declared retry attempt is blocked.
21061        // Catches a future relaxation to `>=` that would silently
21062        // drift the accept boundary.
21063        let mut s = three_member_spec();
21064        s.politicas.timeout = None;
21065        s.politicas.retries = Some(3);
21066        s.politicas.circuit_breaker = Some(CircuitBreaker {
21067            max_failures: 3,
21068            window: Duration::from_secs(60),
21069        });
21070        s.politicas.rate_limit = None;
21071        assert_eq!(
21072            s.validate().unwrap_err(),
21073            AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
21074                retries: 3,
21075                max_failures: 3,
21076            }
21077        );
21078    }
21079
21080    #[test]
21081    fn cross_axis_retries_gate_vacuous_when_retries_absent() {
21082        // The predicate is vacuously `true` when `:retries` is None —
21083        // a `:circuit-breaker` alone declares a failure counter whose
21084        // per-client attempt count is unconstrained by the substrate,
21085        // so no per-client saturation bound on failures-per-client-call
21086        // is knowable at author time. The substrate takes no position
21087        // on whether an omitted `:retries` axis means zero retries or
21088        // "the client picks its own retry policy" — either way, the
21089        // pair is undeclared and the cross-axis gate has nothing to
21090        // check. Pin so a future tightening that made the gate
21091        // opinionated on half-declared pairs surfaces here.
21092        let mut s = three_member_spec();
21093        s.politicas.timeout = None;
21094        s.politicas.retries = None;
21095        s.politicas.circuit_breaker = Some(CircuitBreaker {
21096            max_failures: 1,
21097            window: Duration::from_secs(60),
21098        });
21099        s.politicas.rate_limit = None;
21100        s.validate().expect(
21101            "cross-axis retries gate must be vacuous when :retries is None, \
21102             however low :max-failures is",
21103        );
21104    }
21105
21106    #[test]
21107    fn cross_axis_retries_gate_vacuous_when_circuit_breaker_absent() {
21108        // Peer of the sibling `:retries`-absent case: a `:retries`
21109        // without a `:circuit-breaker` declares a client-retry policy
21110        // with no failure counter to trip, so the pair is undeclared
21111        // and the cross-axis gate has nothing to check.
21112        let mut s = three_member_spec();
21113        s.politicas.timeout = None;
21114        s.politicas.retries = Some(POLICY_RETRIES_MAX);
21115        s.politicas.circuit_breaker = None;
21116        s.politicas.rate_limit = None;
21117        s.validate().expect(
21118            "cross-axis retries gate must be vacuous when :circuit-breaker is None, \
21119             however high :retries is",
21120        );
21121    }
21122
21123    #[test]
21124    fn cross_axis_retries_gate_runs_after_per_axis_brackets() {
21125        // Ordering pin: a pair whose retries is *both* zero-floor-
21126        // violating and structurally at-or-below the trip threshold
21127        // must surface the per-axis zero-floor arm first — the
21128        // zero-floor diagnostic is more self-locating (its omit-axis
21129        // remediation is directly named), where the cross-axis arm
21130        // would send the author to reconcile two values one of which
21131        // is not a meaningful retry count at all. Same ordering
21132        // discipline every per-axis bracket carries internally
21133        // (zero-floor before canonical-form before cap), and the
21134        // sibling cross-axis
21135        // `PolicyRateLimitZero`-before-`PolicyBreakerCannotTripUnderRateLimit`
21136        // ordering pins on the `(:rate-limit, :circuit-breaker)` pair.
21137        let mut s = three_member_spec();
21138        s.politicas.timeout = None;
21139        s.politicas.retries = Some(0);
21140        s.politicas.circuit_breaker = Some(CircuitBreaker {
21141            max_failures: 3,
21142            window: Duration::from_secs(60),
21143        });
21144        s.politicas.rate_limit = None;
21145        assert_eq!(
21146            s.validate().unwrap_err(),
21147            AplicacaoError::PolicyRetriesZero,
21148            "per-axis retries zero-floor arm must fire before the cross-axis retries gate"
21149        );
21150    }
21151
21152    #[test]
21153    fn cross_axis_retries_gate_runs_after_sibling_starve_gate() {
21154        // Cross-axis ordering pin: a `:politicas` whose axes trip
21155        // BOTH cross-axis arms — `:rate-limit` starves the breaker
21156        // within `:window` (the sibling
21157        // `PolicyBreakerCannotTripUnderRateLimit` invariant) AND
21158        // `:retries + 1` saturates `:max-failures` (this arm) — must
21159        // surface the rate-limit-starve diagnostic first. The
21160        // rate-limit-starve arm reasons across the token-bucket
21161        // admission axis every rate-limited edge carries whether or
21162        // not `:retries` is declared, so its diagnostic is more
21163        // self-locating; the retries-saturate arm reasons across a
21164        // per-client retry-policy budget the starve arm does not
21165        // touch.
21166        //
21167        // A `{ retries: 5, rate: 1/h, max_failures: 5, cb_window: 10s }`
21168        // pair trips both: the rate structurally cannot deliver 5
21169        // failures per 10s breaker window, and simultaneously
21170        // one client's `retries + 1 = 6` attempts alone would
21171        // saturate the 5-`max_failures` threshold.
21172        let mut s = three_member_spec();
21173        s.politicas.timeout = None;
21174        s.politicas.retries = Some(5);
21175        s.politicas.circuit_breaker = Some(CircuitBreaker {
21176            max_failures: 5,
21177            window: Duration::from_secs(10),
21178        });
21179        s.politicas.rate_limit = Some(RateLimit {
21180            rate: 1,
21181            window: Duration::from_secs(3600),
21182        });
21183        assert_eq!(
21184            s.validate().unwrap_err(),
21185            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
21186                rate: 1,
21187                rl_window: Duration::from_secs(3600),
21188                max_failures: 5,
21189                cb_window: Duration::from_secs(10),
21190            },
21191            "sibling :rate-limit-starve cross-axis arm must fire before the \
21192             retries-saturate arm when both apply"
21193        );
21194    }
21195
21196    #[test]
21197    fn retries_fit_under_breaker_trip_threshold_predicate_matches_gate_semantic() {
21198        // Equivalence pin: the substrate-canonical
21199        // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]
21200        // predicate and the [`AplicacaoSpec::validate_politicas`]
21201        // cross-axis arm must discriminate the same set on every pair
21202        // covered by their shared invariant. A future refactor of
21203        // either side that breaks the equivalence trips here rather
21204        // than as a divergence between the predicate's Boolean answer
21205        // and the validate gate's Ok/Err arm — the same
21206        // predicate-vs-gate coherence discipline the sibling
21207        // [`MeshPolicy::breaker_window_observes_timeout`] and
21208        // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
21209        // carry against `AplicacaoSpec::validate_politicas`. The
21210        // sweep covers both arms of the invariant (strictly below,
21211        // exactly at the boundary, strictly above) and both vacuous
21212        // arms (None `:retries`, None `:circuit-breaker`), so the
21213        // equivalence holds exhaustively over the axis-covered accept
21214        // and reject sets. Clears `:timeout` and `:rate-limit`
21215        // throughout so the sibling cross-axis arms are vacuous on
21216        // every input.
21217        let cb = |max_failures: u32| {
21218            Some(CircuitBreaker {
21219                max_failures,
21220                window: Duration::from_secs(60),
21221            })
21222        };
21223        let cases: &[(Option<u32>, Option<CircuitBreaker>)] = &[
21224            // saturating pairs (predicate = false, gate = Err)
21225            (Some(3), cb(3)),
21226            (Some(3), cb(1)),
21227            (Some(10), cb(5)),
21228            // boundary + coherent pairs (predicate = true, gate = Ok)
21229            (Some(3), cb(4)),
21230            (Some(1), cb(5)),
21231            (Some(3), cb(20)),
21232            // vacuous arms
21233            (None, cb(1)),
21234            (Some(10), None),
21235            (None, None),
21236        ];
21237        for (retries, circuit_breaker) in cases.iter().copied() {
21238            let politicas = MeshPolicy {
21239                retries,
21240                circuit_breaker,
21241                ..Default::default()
21242            };
21243            let predicate = politicas.retries_fit_under_breaker_trip_threshold();
21244
21245            let mut s = three_member_spec();
21246            s.politicas = politicas.clone();
21247            let gate_ok = !matches!(
21248                s.validate(),
21249                Err(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted { .. })
21250            );
21251
21252            assert_eq!(
21253                predicate, gate_ok,
21254                "predicate must agree with validate arm on pair \
21255                 (retries={retries:?}, circuit_breaker={circuit_breaker:?})"
21256            );
21257        }
21258    }
21259
21260    #[test]
21261    fn rejects_rate_limit_cannot_admit_retry_burst() {
21262        // The fail-before-pass-after pin on the cross-axis
21263        // `(:retries, :rate-limit)` invariant. Each axis is
21264        // individually well-formed under its own per-axis bracket (both
21265        // above the zero floor, both below the cap), but the pair is a
21266        // structurally-truncated retry policy: one client's
21267        // `retries + 1 = 6` failing attempts consume 6 tokens from a
21268        // bucket that admits at most 3 per refill window, so the fourth
21269        // attempt onward is 429ed by the local rate limiter and the
21270        // declared retry policy is silently truncated by the same rate
21271        // limiter it feeds through — the substrate declared six
21272        // attempts and structurally allows three.
21273        //
21274        // Envoy's `local_rate_limit.token_bucket.max_tokens` paired
21275        // against `retry_policy.num_retries` carries the identical
21276        // relation; every production playbook that pairs the two axes
21277        // (Envoy, Istio, resilience4j, AWS App Mesh) sizes the bucket
21278        // capacity strictly above any single client's retry budget so
21279        // the limiter distinguishes one client's declared retries from
21280        // sustained multi-client load.
21281        //
21282        // Pin both the diagnostic arm and the payload values so a
21283        // future re-shape of the arm surfaces here as a deliberate
21284        // test edit. Clears `:timeout` and `:circuit-breaker` so the
21285        // sibling cross-axis
21286        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] /
21287        // [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`] /
21288        // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
21289        // arms do not fire first on the ordering-precedent they hold
21290        // over this arm.
21291        let mut s = three_member_spec();
21292        s.politicas.timeout = None;
21293        s.politicas.retries = Some(5);
21294        s.politicas.circuit_breaker = None;
21295        s.politicas.rate_limit = Some(RateLimit {
21296            rate: 3,
21297            window: Duration::from_secs(1),
21298        });
21299        assert_eq!(
21300            s.validate().unwrap_err(),
21301            AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
21302                retries: 5,
21303                rate: 3,
21304            }
21305        );
21306    }
21307
21308    #[test]
21309    fn accepts_rate_limit_admits_retry_burst() {
21310        // Positive-control sweep across the production-playbook band
21311        // — every pair a real playbook recommends where the bucket
21312        // capacity is strictly above the client's retry budget must
21313        // validate. Envoy default `num_retries: 3` with 100/s (100
21314        // tokens per window admits 4 attempts per client with 96 to
21315        // spare); Istio `attempts: 3` with 50/s (50 admits 4);
21316        // resilience4j 2 retries with 10/s (10 admits 3); AWS App
21317        // Mesh `maxRetries: 5` with 1000/s (1000 admits 6); Cloudflare
21318        // Enterprise 3 retries with 1_000_000/h (1M admits 4). Clears
21319        // `:timeout` and `:circuit-breaker` so the sibling cross-axis
21320        // arms are vacuous on this sweep.
21321        for (retries, rate, secs) in [
21322            (3u32, 100u32, 1u64),
21323            (3, 50, 1),
21324            (2, 10, 1),
21325            (5, 1000, 1),
21326            (3, 1_000_000, 3600),
21327            (10, POLICY_RATE_LIMIT_MAX, 1),
21328        ] {
21329            let mut s = three_member_spec();
21330            s.politicas.timeout = None;
21331            s.politicas.retries = Some(retries);
21332            s.politicas.circuit_breaker = None;
21333            s.politicas.rate_limit = Some(RateLimit {
21334                rate,
21335                window: Duration::from_secs(secs),
21336            });
21337            s.validate().unwrap_or_else(|e| {
21338                panic!(
21339                    "production-playbook pair retries={retries} rate={rate}/{secs}s \
21340                     must validate; got {e:?}"
21341                )
21342            });
21343        }
21344    }
21345
21346    #[test]
21347    fn accepts_rate_exactly_at_boundary_admits_retry_burst() {
21348        // Boundary pin: `rate == retries + 1` is the smallest bucket
21349        // capacity that structurally admits one client's exhausted
21350        // retries through completion (each attempt draws exactly one
21351        // token; `retries + 1` tokens available admits `retries + 1`
21352        // attempts, retries fully executed). The invariant is `>=`,
21353        // stated in the coherent direction `rate >= retries + 1`.
21354        // Catches a future off-by-one tightening to `rate > retries + 1`
21355        // that would drift the accept set away from the codified
21356        // [`MeshPolicy::rate_limit_admits_retry_burst`] predicate.
21357        let mut s = three_member_spec();
21358        s.politicas.timeout = None;
21359        s.politicas.retries = Some(3);
21360        s.politicas.circuit_breaker = None;
21361        s.politicas.rate_limit = Some(RateLimit {
21362            rate: 4,
21363            window: Duration::from_secs(1),
21364        });
21365        s.validate()
21366            .expect("rate == retries + 1 is the boundary accept case");
21367    }
21368
21369    #[test]
21370    fn rejects_rate_one_below_retry_burst() {
21371        // Off-by-one boundary pin: exactly one token short of the
21372        // retry burst is still structurally truncating (the invariant
21373        // is `>=`, so `<` refuses even a one-token shortfall).
21374        // `retries = 3` with `rate = 3` means one client's four
21375        // attempts consume four tokens from a three-token bucket —
21376        // the fourth attempt is 429ed. Catches a future relaxation to
21377        // `>` on the wrong side (`rate > retries`, accepting equal)
21378        // that would silently drift the accept boundary and admit a
21379        // structurally-truncated retry policy at the emit boundary.
21380        let mut s = three_member_spec();
21381        s.politicas.timeout = None;
21382        s.politicas.retries = Some(3);
21383        s.politicas.circuit_breaker = None;
21384        s.politicas.rate_limit = Some(RateLimit {
21385            rate: 3,
21386            window: Duration::from_secs(1),
21387        });
21388        assert_eq!(
21389            s.validate().unwrap_err(),
21390            AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
21391                retries: 3,
21392                rate: 3,
21393            }
21394        );
21395    }
21396
21397    #[test]
21398    fn cross_axis_burst_gate_vacuous_when_retries_absent() {
21399        // The predicate is vacuously `true` when `:retries` is None —
21400        // a `:rate-limit` alone declares a token-bucket rate whose
21401        // per-client attempt count is unconstrained by the substrate,
21402        // so no per-client saturation bound on tokens-per-client-call
21403        // is knowable at author time. The substrate takes no position
21404        // on whether an omitted `:retries` axis means zero retries or
21405        // "the client picks its own retry policy" — either way, the
21406        // pair is undeclared and the cross-axis gate has nothing to
21407        // check. Pin so a future tightening that made the gate
21408        // opinionated on half-declared pairs surfaces here.
21409        let mut s = three_member_spec();
21410        s.politicas.timeout = None;
21411        s.politicas.retries = None;
21412        s.politicas.circuit_breaker = None;
21413        s.politicas.rate_limit = Some(RateLimit {
21414            rate: 1,
21415            window: Duration::from_secs(1),
21416        });
21417        s.validate().expect(
21418            "cross-axis burst gate must be vacuous when :retries is None, \
21419             however low :rate is",
21420        );
21421    }
21422
21423    #[test]
21424    fn cross_axis_burst_gate_vacuous_when_rate_limit_absent() {
21425        // Peer of the sibling `:retries`-absent case: a `:retries`
21426        // without a `:rate-limit` declares a client-retry policy with
21427        // no rate limiter to saturate, so the pair is undeclared and
21428        // the cross-axis gate has nothing to check. Uses
21429        // [`POLICY_RETRIES_MAX`] to pin the vacuity across the widest
21430        // authored retry budget the per-axis cap admits — a `:retries
21431        // POLICY_RETRIES_MAX` alone must remain a clean pass whether
21432        // or not `:rate-limit` is declared.
21433        let mut s = three_member_spec();
21434        s.politicas.timeout = None;
21435        s.politicas.retries = Some(POLICY_RETRIES_MAX);
21436        s.politicas.circuit_breaker = None;
21437        s.politicas.rate_limit = None;
21438        s.validate().expect(
21439            "cross-axis burst gate must be vacuous when :rate-limit is None, \
21440             however high :retries is",
21441        );
21442    }
21443
21444    #[test]
21445    fn cross_axis_burst_gate_runs_after_per_axis_brackets() {
21446        // Ordering pin: a pair whose retries is *both* zero-floor-
21447        // violating and structurally below the retry-burst threshold
21448        // must surface the per-axis zero-floor arm first — the
21449        // zero-floor diagnostic is more self-locating (its omit-axis
21450        // remediation is directly named), where the cross-axis arm
21451        // would send the author to reconcile two values one of which
21452        // is not a meaningful retry count at all. Same ordering
21453        // discipline every per-axis bracket carries internally
21454        // (zero-floor before canonical-form before cap), and the
21455        // sibling cross-axis
21456        // `PolicyRetriesZero`-before-`PolicyBreakerTripsBeforeRetriesExhausted`
21457        // ordering pin on the `(:retries, :max-failures)` pair.
21458        let mut s = three_member_spec();
21459        s.politicas.timeout = None;
21460        s.politicas.retries = Some(0);
21461        s.politicas.circuit_breaker = None;
21462        s.politicas.rate_limit = Some(RateLimit {
21463            rate: 1,
21464            window: Duration::from_secs(1),
21465        });
21466        assert_eq!(
21467            s.validate().unwrap_err(),
21468            AplicacaoError::PolicyRetriesZero,
21469            "per-axis retries zero-floor arm must fire before the cross-axis burst gate"
21470        );
21471    }
21472
21473    #[test]
21474    fn cross_axis_burst_gate_runs_after_sibling_starve_gate() {
21475        // Cross-axis ordering pin: a `:politicas` whose axes trip
21476        // BOTH cross-axis arms — `:rate-limit` starves the breaker
21477        // within `:window` (the sibling
21478        // `PolicyBreakerCannotTripUnderRateLimit` invariant) AND
21479        // `:retries + 1` exceeds the bucket capacity (this arm) —
21480        // must surface the rate-limit-starve diagnostic first. The
21481        // starve arm is the token-bucket admission invariant every
21482        // rate-limited edge carries against the breaker whether or
21483        // not `:retries` is declared, so its diagnostic is more
21484        // self-locating; the burst arm reasons across a per-client
21485        // retry-policy budget the starve arm does not touch. Same
21486        // "more foundational cross-axis first" ordering discipline the
21487        // sibling
21488        // `PolicyBreakerCannotTripUnderRateLimit`-before-`PolicyBreakerTripsBeforeRetriesExhausted`
21489        // pin on the peer pair carries.
21490        //
21491        // A `{ retries: 5, rate: 1/h, max_failures: 5, cb_window: 10s }`
21492        // pair trips both: the rate structurally cannot deliver 5
21493        // failures per 10s breaker window (starve arm), and
21494        // simultaneously one client's `retries + 1 = 6` attempts alone
21495        // would exhaust the 1-token bucket (burst arm).
21496        let mut s = three_member_spec();
21497        s.politicas.timeout = None;
21498        s.politicas.retries = Some(5);
21499        s.politicas.circuit_breaker = Some(CircuitBreaker {
21500            max_failures: 5,
21501            window: Duration::from_secs(10),
21502        });
21503        s.politicas.rate_limit = Some(RateLimit {
21504            rate: 1,
21505            window: Duration::from_secs(3600),
21506        });
21507        assert_eq!(
21508            s.validate().unwrap_err(),
21509            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
21510                rate: 1,
21511                rl_window: Duration::from_secs(3600),
21512                max_failures: 5,
21513                cb_window: Duration::from_secs(10),
21514            },
21515            "sibling :rate-limit-starve cross-axis arm must fire before the \
21516             burst arm when both apply"
21517        );
21518    }
21519
21520    #[test]
21521    fn cross_axis_burst_gate_runs_after_sibling_retries_saturate_gate() {
21522        // Cross-axis ordering pin: a `:politicas` whose axes trip
21523        // BOTH the retries-saturate arm and this burst arm — one
21524        // client's `retries + 1` failures saturate the breaker's trip
21525        // threshold (the sibling
21526        // `PolicyBreakerTripsBeforeRetriesExhausted` invariant) AND
21527        // `retries + 1` exceeds the bucket capacity (this arm) —
21528        // must surface the retries-saturate diagnostic first. The
21529        // saturate arm is the per-client-vs-breaker relation every
21530        // retry-with-breaker pair carries whether or not `:rate-limit`
21531        // is declared, so its diagnostic is more self-locating; the
21532        // burst arm reasons across the rate-limit token-bucket
21533        // admission axis the saturate arm does not touch. Same
21534        // "more foundational cross-axis first" ordering discipline
21535        // carries here.
21536        //
21537        // A `{ retries: 5, max_failures: 3, cb_window: 60s,
21538        // rate: 3/s }` pair trips both: the breaker's `max_failures
21539        // = 3` is `<= retries = 5` (saturate arm), and simultaneously
21540        // one client's `retries + 1 = 6` attempts alone would exhaust
21541        // the 3-token bucket (burst arm). Clears `:timeout` so the
21542        // sibling `:window<:timeout` gate is vacuous, and the
21543        // `(rate=3/s, max_failures=3, cb_window=60s)` triple keeps
21544        // the starve arm coherent (`3 × 60s >= 3 × 1s`) so it is not
21545        // the arm that fires first.
21546        let mut s = three_member_spec();
21547        s.politicas.timeout = None;
21548        s.politicas.retries = Some(5);
21549        s.politicas.circuit_breaker = Some(CircuitBreaker {
21550            max_failures: 3,
21551            window: Duration::from_secs(60),
21552        });
21553        s.politicas.rate_limit = Some(RateLimit {
21554            rate: 3,
21555            window: Duration::from_secs(1),
21556        });
21557        assert_eq!(
21558            s.validate().unwrap_err(),
21559            AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
21560                retries: 5,
21561                max_failures: 3,
21562            },
21563            "sibling :retries-saturate cross-axis arm must fire before the \
21564             burst arm when both apply"
21565        );
21566    }
21567
21568    #[test]
21569    fn rate_limit_admits_retry_burst_predicate_matches_gate_semantic() {
21570        // Equivalence pin: the substrate-canonical
21571        // [`MeshPolicy::rate_limit_admits_retry_burst`] predicate and
21572        // the [`AplicacaoSpec::validate_politicas`] cross-axis arm
21573        // must discriminate the same set on every pair covered by
21574        // their shared invariant. A future refactor of either side
21575        // that breaks the equivalence trips here rather than as a
21576        // divergence between the predicate's Boolean answer and the
21577        // validate gate's Ok/Err arm — the same predicate-vs-gate
21578        // coherence discipline the three sibling cross-axis
21579        // predicates ([`MeshPolicy::breaker_window_observes_timeout`],
21580        // [`MeshPolicy::breaker_can_trip_under_rate_limit`],
21581        // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`])
21582        // carry against `AplicacaoSpec::validate_politicas`. The sweep
21583        // covers both arms of the invariant (strictly below, exactly
21584        // at the boundary, strictly above) and both vacuous arms
21585        // (None `:retries`, None `:rate-limit`), so the equivalence
21586        // holds exhaustively over the axis-covered accept and reject
21587        // sets. Clears `:timeout` and `:circuit-breaker` throughout
21588        // so the three sibling cross-axis arms are vacuous on every
21589        // input.
21590        let rl = |rate: u32, secs: u64| {
21591            Some(RateLimit {
21592                rate,
21593                window: Duration::from_secs(secs),
21594            })
21595        };
21596        let cases: &[(Option<u32>, Option<RateLimit>)] = &[
21597            // burst-exceeding pairs (predicate = false, gate = Err)
21598            (Some(3), rl(3, 1)),
21599            (Some(5), rl(1, 1)),
21600            (Some(10), rl(5, 1)),
21601            // boundary + coherent pairs (predicate = true, gate = Ok)
21602            (Some(3), rl(4, 1)),
21603            (Some(1), rl(5, 1)),
21604            (Some(3), rl(1_000_000, 3600)),
21605            // vacuous arms
21606            (None, rl(1, 1)),
21607            (Some(10), None),
21608            (None, None),
21609        ];
21610        for (retries, rate_limit) in cases.iter().copied() {
21611            let politicas = MeshPolicy {
21612                retries,
21613                rate_limit,
21614                ..Default::default()
21615            };
21616            let predicate = politicas.rate_limit_admits_retry_burst();
21617
21618            let mut s = three_member_spec();
21619            s.politicas = politicas.clone();
21620            let gate_ok = !matches!(
21621                s.validate(),
21622                Err(AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst { .. })
21623            );
21624
21625            assert_eq!(
21626                predicate, gate_ok,
21627                "predicate must agree with validate arm on pair \
21628                 (retries={retries:?}, rate_limit={rate_limit:?})"
21629            );
21630        }
21631    }
21632
21633    /// Sweep body shared by every `first_cross_axis_violation` ≡ gate
21634    /// equivalence pin — assert that on each `(label, politicas,
21635    /// expected)` case the substrate-canonical fold and the validate
21636    /// cascade agree byte-for-byte. Extracted so each pin's own body
21637    /// stays under `clippy::too_many_lines`.
21638    fn assert_first_cross_axis_violation_agrees_with_gate(
21639        cases: &[(&str, MeshPolicy, Option<AplicacaoError>)],
21640    ) {
21641        for (label, politicas, expected) in cases {
21642            let fold = politicas.first_cross_axis_violation();
21643            assert_eq!(
21644                fold.as_ref(),
21645                expected.as_ref(),
21646                "fold must return {expected:?} on `{label}`; got {fold:?}"
21647            );
21648
21649            let mut s = three_member_spec();
21650            s.politicas = politicas.clone();
21651            let gate = s.validate();
21652            match expected {
21653                None => {
21654                    // No cross-axis violation: validate must pass (the
21655                    // per-axis brackets pass by construction on every
21656                    // fixture above; every fixture's non-`:politicas`
21657                    // slots come from `three_member_spec`).
21658                    gate.as_ref()
21659                        .unwrap_or_else(|e| panic!("`{label}` must validate cleanly; got {e:?}"));
21660                }
21661                Some(want) => {
21662                    let got =
21663                        gate.expect_err(&format!("`{label}` must surface a cross-axis violation"));
21664                    assert_eq!(
21665                        &got, want,
21666                        "validate cross-axis cascade must return {want:?} on `{label}`; got {got:?}"
21667                    );
21668                }
21669            }
21670        }
21671    }
21672
21673    #[test]
21674    fn first_cross_axis_violation_matches_gate_on_single_arm_and_vacuous_shapes() {
21675        // Equivalence pin on the compound cross-axis fold: the
21676        // substrate-canonical [`MeshPolicy::first_cross_axis_violation`]
21677        // and the [`AplicacaoSpec::validate_politicas`] cross-axis
21678        // cascade must return identical `AplicacaoError` variants on
21679        // every axis-covered input — the "compound-fold ≡ gate"
21680        // contract that generalizes the four sibling per-arm pins
21681        // onto the compound primitive that folds all four. A future
21682        // refactor of either side that breaks the equivalence trips
21683        // here rather than as a divergence between what the substrate
21684        // primitive answers and what `feira build` accepts.
21685        //
21686        // Half-A of the sweep: every single-arm violation (one arm
21687        // fires with the three sibling arms vacuous), the vacuous
21688        // shape (empty policy — no arm fires), and the fully-coherent
21689        // shape (every axis declared inside the coherence surface —
21690        // no arm fires). Half-B (pairwise-ordering coverage — the
21691        // "which arm wins when two apply" contract) lives in the
21692        // sibling `first_cross_axis_violation_matches_gate_on_pairwise_orderings`
21693        // pin; splitting keeps each pin's body under
21694        // `clippy::too_many_lines`.
21695        let cb = |max_failures: u32, secs: u64| CircuitBreaker {
21696            max_failures,
21697            window: Duration::from_secs(secs),
21698        };
21699        let rl = |rate: u32, secs: u64| RateLimit {
21700            rate,
21701            window: Duration::from_secs(secs),
21702        };
21703        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
21704            (
21705                "window-below-timeout only",
21706                MeshPolicy {
21707                    timeout: Some(Duration::from_secs(30)),
21708                    circuit_breaker: Some(cb(5, 10)),
21709                    ..Default::default()
21710                },
21711                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
21712                    window: Duration::from_secs(10),
21713                    timeout: Duration::from_secs(30),
21714                }),
21715            ),
21716            (
21717                "starve only",
21718                MeshPolicy {
21719                    rate_limit: Some(rl(1, 3600)),
21720                    circuit_breaker: Some(cb(5, 10)),
21721                    ..Default::default()
21722                },
21723                Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
21724                    rate: 1,
21725                    rl_window: Duration::from_secs(3600),
21726                    max_failures: 5,
21727                    cb_window: Duration::from_secs(10),
21728                }),
21729            ),
21730            (
21731                "retries-saturate only",
21732                MeshPolicy {
21733                    retries: Some(3),
21734                    circuit_breaker: Some(cb(3, 60)),
21735                    ..Default::default()
21736                },
21737                Some(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
21738                    retries: 3,
21739                    max_failures: 3,
21740                }),
21741            ),
21742            (
21743                "retries-burst only",
21744                MeshPolicy {
21745                    retries: Some(5),
21746                    rate_limit: Some(rl(3, 1)),
21747                    ..Default::default()
21748                },
21749                Some(AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
21750                    retries: 5,
21751                    rate: 3,
21752                }),
21753            ),
21754            ("empty policy", MeshPolicy::default(), None),
21755            (
21756                "fully-coherent policy",
21757                MeshPolicy {
21758                    timeout: Some(Duration::from_secs(30)),
21759                    retries: Some(3),
21760                    circuit_breaker: Some(cb(5, 60)),
21761                    mtls_required: Some(true),
21762                    rate_limit: Some(rl(100, 1)),
21763                },
21764                None,
21765            ),
21766        ];
21767        assert_first_cross_axis_violation_agrees_with_gate(cases);
21768    }
21769
21770    #[test]
21771    fn first_cross_axis_violation_matches_gate_on_pairwise_orderings() {
21772        // Half-B of the compound-fold ≡ gate equivalence pin: the
21773        // load-bearing pairwise-ordering coverage. Every ordered pair
21774        // of the four cross-axis arms — six combinations — where two
21775        // arms are simultaneously eligible must surface the
21776        // more-foundational arm's diagnostic verbatim. Pins the fold's
21777        // arm-ordering byte-for-byte against the validate cascade's
21778        // arm-ordering, so a future reshuffle of either side that
21779        // silently drifts the ordering trips here rather than as a
21780        // per-arm miss the sibling per-arm `_predicate_matches_gate_semantic`
21781        // pins cannot catch (they clear every sibling arm, so their
21782        // sweeps are pairwise-ordering-agnostic by construction).
21783        //
21784        // The six pairs the four-arm cascade admits:
21785        // window-before-starve, window-before-saturate,
21786        // window-before-burst, starve-before-saturate,
21787        // starve-before-burst, saturate-before-burst.
21788        let cb = |max_failures: u32, secs: u64| CircuitBreaker {
21789            max_failures,
21790            window: Duration::from_secs(secs),
21791        };
21792        let rl = |rate: u32, secs: u64| RateLimit {
21793            rate,
21794            window: Duration::from_secs(secs),
21795        };
21796        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
21797            (
21798                "window+starve → window wins",
21799                MeshPolicy {
21800                    timeout: Some(Duration::from_secs(30)),
21801                    rate_limit: Some(rl(1, 3600)),
21802                    circuit_breaker: Some(cb(5, 10)),
21803                    ..Default::default()
21804                },
21805                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
21806                    window: Duration::from_secs(10),
21807                    timeout: Duration::from_secs(30),
21808                }),
21809            ),
21810            (
21811                "window+retries-saturate → window wins",
21812                MeshPolicy {
21813                    timeout: Some(Duration::from_secs(30)),
21814                    retries: Some(5),
21815                    circuit_breaker: Some(cb(3, 10)),
21816                    ..Default::default()
21817                },
21818                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
21819                    window: Duration::from_secs(10),
21820                    timeout: Duration::from_secs(30),
21821                }),
21822            ),
21823            (
21824                "window+retries-burst → window wins",
21825                MeshPolicy {
21826                    timeout: Some(Duration::from_secs(30)),
21827                    retries: Some(5),
21828                    rate_limit: Some(rl(3, 1)),
21829                    circuit_breaker: Some(cb(5, 10)),
21830                    ..Default::default()
21831                },
21832                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
21833                    window: Duration::from_secs(10),
21834                    timeout: Duration::from_secs(30),
21835                }),
21836            ),
21837            (
21838                "starve+retries-saturate → starve wins",
21839                MeshPolicy {
21840                    retries: Some(5),
21841                    rate_limit: Some(rl(1, 3600)),
21842                    circuit_breaker: Some(cb(5, 10)),
21843                    ..Default::default()
21844                },
21845                Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
21846                    rate: 1,
21847                    rl_window: Duration::from_secs(3600),
21848                    max_failures: 5,
21849                    cb_window: Duration::from_secs(10),
21850                }),
21851            ),
21852            (
21853                "starve+retries-burst → starve wins",
21854                MeshPolicy {
21855                    retries: Some(5),
21856                    rate_limit: Some(rl(1, 3600)),
21857                    circuit_breaker: Some(cb(10, 10)),
21858                    ..Default::default()
21859                },
21860                Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
21861                    rate: 1,
21862                    rl_window: Duration::from_secs(3600),
21863                    max_failures: 10,
21864                    cb_window: Duration::from_secs(10),
21865                }),
21866            ),
21867            (
21868                "retries-saturate+retries-burst → saturate wins",
21869                MeshPolicy {
21870                    retries: Some(5),
21871                    rate_limit: Some(rl(3, 1)),
21872                    circuit_breaker: Some(cb(3, 60)),
21873                    ..Default::default()
21874                },
21875                Some(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
21876                    retries: 5,
21877                    max_failures: 3,
21878                }),
21879            ),
21880        ];
21881        assert_first_cross_axis_violation_agrees_with_gate(cases);
21882    }
21883
21884    /// Sweep body shared by every `MeshPolicy::validate` ≡ gate
21885    /// equivalence pin — assert that on each `(label, politicas,
21886    /// expected)` case both the substrate primitive
21887    /// [`MeshPolicy::validate`] and the [`AplicacaoSpec::validate_politicas`]
21888    /// cascade (reached through `AplicacaoSpec::validate`, keying off the
21889    /// same `three_member_spec` fixture whose non-`:politicas` slots
21890    /// always validate cleanly) return identical `AplicacaoError` variants.
21891    /// Peer of [`assert_first_cross_axis_violation_agrees_with_gate`] on
21892    /// the sibling cross-axis-only surface — extended here onto the
21893    /// compound per-axis + cross-axis entry gate. Extracted so each pin's
21894    /// own body stays under `clippy::too_many_lines`.
21895    fn assert_validate_matches_gate(cases: &[(&str, MeshPolicy, Option<AplicacaoError>)]) {
21896        for (label, politicas, expected) in cases {
21897            let direct = politicas.validate();
21898            match (expected, &direct) {
21899                (None, Ok(())) => {}
21900                (None, Err(got)) => {
21901                    panic!("`{label}`: MeshPolicy::validate must pass; got {got:?}")
21902                }
21903                (Some(want), Ok(())) => {
21904                    panic!("`{label}`: MeshPolicy::validate must return {want:?}; got Ok")
21905                }
21906                (Some(want), Err(got)) => assert_eq!(
21907                    got, want,
21908                    "`{label}`: MeshPolicy::validate must return {want:?}; got {got:?}"
21909                ),
21910            }
21911
21912            let mut s = three_member_spec();
21913            s.politicas = politicas.clone();
21914            let gate = s.validate();
21915            match (expected, &gate) {
21916                (None, Ok(())) => {}
21917                (None, Err(got)) => {
21918                    panic!("`{label}`: validate_politicas gate must pass; got {got:?}")
21919                }
21920                (Some(want), Ok(())) => {
21921                    panic!("`{label}`: validate_politicas gate must return {want:?}; got Ok")
21922                }
21923                (Some(want), Err(got)) => assert_eq!(
21924                    got, want,
21925                    "`{label}`: validate_politicas gate must return {want:?}; got {got:?}"
21926                ),
21927            }
21928        }
21929    }
21930
21931    #[test]
21932    fn validate_matches_gate_on_per_axis_and_phase_boundary_shapes() {
21933        // Half-A of the compound-per-axis-+-cross-axis-fold ≡ gate
21934        // equivalence pin on [`MeshPolicy::validate`]: the four per-axis
21935        // zero-floor arms (`:timeout`, `:retries`, `:circuit-breaker
21936        // :max-failures`, `:rate-limit` rate) that discriminate the
21937        // "per-axis phase fires" arm of the compound gate, plus one
21938        // per-axis-before-cross-axis case (`{ timeout: 30s, cb.window:
21939        // ZERO }`) that pins the phase-boundary ordering — the per-axis
21940        // `PolicyBreakerZeroWindow` arm strictly precedes the cross-axis
21941        // `PolicyBreakerWindowBelowTimeout` arm, so the zero-window
21942        // diagnostic wins over the window-below-timeout diagnostic. Peer
21943        // of the sibling
21944        // `first_cross_axis_violation_matches_gate_on_single_arm_and_vacuous_shapes`
21945        // + `_on_pairwise_orderings` pins on the compound cross-axis
21946        // fold, extended here onto the outer compound entry gate that
21947        // folds per-axis + cross-axis surfaces. Half-B (cross-axis and
21948        // clean-pass surfaces) lives in the sibling
21949        // `validate_matches_gate_on_cross_axis_and_clean_pass_shapes`
21950        // pin; splitting keeps each pin's body under
21951        // `clippy::too_many_lines`.
21952        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
21953            (
21954                "per-axis: timeout zero",
21955                MeshPolicy {
21956                    timeout: Some(Duration::ZERO),
21957                    ..Default::default()
21958                },
21959                Some(AplicacaoError::PolicyTimeoutZero),
21960            ),
21961            (
21962                "per-axis: retries zero",
21963                MeshPolicy {
21964                    retries: Some(0),
21965                    ..Default::default()
21966                },
21967                Some(AplicacaoError::PolicyRetriesZero),
21968            ),
21969            (
21970                "per-axis: breaker max-failures zero",
21971                MeshPolicy {
21972                    circuit_breaker: Some(CircuitBreaker {
21973                        max_failures: 0,
21974                        window: Duration::from_secs(60),
21975                    }),
21976                    ..Default::default()
21977                },
21978                Some(AplicacaoError::PolicyBreakerZeroFailures),
21979            ),
21980            (
21981                "per-axis: rate-limit rate zero",
21982                MeshPolicy {
21983                    rate_limit: Some(RateLimit {
21984                        rate: 0,
21985                        window: Duration::from_secs(1),
21986                    }),
21987                    ..Default::default()
21988                },
21989                Some(AplicacaoError::PolicyRateLimitZero),
21990            ),
21991            (
21992                "per-axis before cross-axis: zero-window wins over window-below-timeout",
21993                MeshPolicy {
21994                    timeout: Some(Duration::from_secs(30)),
21995                    circuit_breaker: Some(CircuitBreaker {
21996                        max_failures: 5,
21997                        window: Duration::ZERO,
21998                    }),
21999                    ..Default::default()
22000                },
22001                Some(AplicacaoError::PolicyBreakerZeroWindow),
22002            ),
22003        ];
22004        assert_validate_matches_gate(cases);
22005    }
22006
22007    #[test]
22008    fn validate_matches_gate_on_cross_axis_and_clean_pass_shapes() {
22009        // Half-B of the compound-per-axis-+-cross-axis-fold ≡ gate
22010        // equivalence pin on [`MeshPolicy::validate`]: the cross-axis
22011        // arm that discriminates the "cross-axis phase fires" arm of
22012        // the compound gate (window-below-timeout — sibling per-arm
22013        // coverage lives in the two
22014        // `first_cross_axis_violation_matches_gate_on_*` pins above),
22015        // plus the two clean-pass shapes (empty policy — every axis
22016        // absent — and fully-coherent — every axis inside the coherence
22017        // surface) that pin the compound gate's `Ok(())` arm. Half-A
22018        // (per-axis + phase-boundary surfaces) lives in the sibling
22019        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
22020        // pin; splitting keeps each pin's body under
22021        // `clippy::too_many_lines`.
22022        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
22023            (
22024                "cross-axis: window-below-timeout",
22025                MeshPolicy {
22026                    timeout: Some(Duration::from_secs(30)),
22027                    circuit_breaker: Some(CircuitBreaker {
22028                        max_failures: 5,
22029                        window: Duration::from_secs(10),
22030                    }),
22031                    ..Default::default()
22032                },
22033                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
22034                    window: Duration::from_secs(10),
22035                    timeout: Duration::from_secs(30),
22036                }),
22037            ),
22038            ("clean pass: empty policy", MeshPolicy::default(), None),
22039            (
22040                "clean pass: every axis coherent",
22041                MeshPolicy {
22042                    timeout: Some(Duration::from_secs(30)),
22043                    retries: Some(3),
22044                    circuit_breaker: Some(CircuitBreaker {
22045                        max_failures: 5,
22046                        window: Duration::from_secs(60),
22047                    }),
22048                    mtls_required: Some(true),
22049                    rate_limit: Some(RateLimit {
22050                        rate: 100,
22051                        window: Duration::from_secs(1),
22052                    }),
22053                },
22054                None,
22055            ),
22056        ];
22057        assert_validate_matches_gate(cases);
22058    }
22059
22060    #[test]
22061    fn empty_politicas_validates() {
22062        // Omitting every policy axis is fine — defaults express "no
22063        // policy on this axis", not "policy = 0". The fixture's typical
22064        // values continue to validate; this test pins that
22065        // MeshPolicy::default() is a clean pass through validate().
22066        let mut s = three_member_spec();
22067        s.politicas = MeshPolicy::default();
22068        s.validate().unwrap();
22069    }
22070
22071    #[test]
22072    fn typical_politicas_validates_with_every_axis_set() {
22073        // The full §III.1 example block (timeout + retries + breaker +
22074        // mtls + rate-limit) — every axis nonzero — must remain a
22075        // clean pass.
22076        let mut s = three_member_spec();
22077        s.politicas = MeshPolicy {
22078            timeout: Some(Duration::from_secs(30)),
22079            retries: Some(3),
22080            circuit_breaker: Some(CircuitBreaker {
22081                max_failures: 5,
22082                window: Duration::from_secs(60),
22083            }),
22084            mtls_required: Some(true),
22085            rate_limit: Some(RateLimit {
22086                rate: 100,
22087                window: Duration::from_secs(1),
22088            }),
22089        };
22090        s.validate().unwrap();
22091    }
22092
22093    #[test]
22094    fn rejects_empty_cluster_name() {
22095        let mut s = three_member_spec();
22096        s.placement.clusters = vec!["rio".into(), String::new()];
22097        assert_eq!(
22098            s.validate().unwrap_err(),
22099            AplicacaoError::PlacementClusterEmpty
22100        );
22101    }
22102
22103    #[test]
22104    fn rejects_duplicate_cluster_names() {
22105        let mut s = three_member_spec();
22106        s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
22107        let err = s.validate().unwrap_err();
22108        assert!(
22109            matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
22110            "got {err:?}"
22111        );
22112    }
22113
22114    #[test]
22115    fn rejects_placement_cluster_with_uppercase() {
22116        // The canonical "I copied the cluster's display name verbatim"
22117        // typo — K8s context names are lowercase per DNS-1123 label
22118        // rule, but org docs often round-trip a TitleCase identifier
22119        // (`Rio`, `Mar-East`) from an ADR. Mirrors the
22120        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
22121        // on the peer name axis.
22122        let mut s = three_member_spec();
22123        s.placement.clusters = vec!["Rio".into(), "mar".into()];
22124        let err = s.validate().unwrap_err();
22125        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
22126            panic!("expected PlacementClusterInvalid, got other variant");
22127        };
22128        assert_eq!(cluster, "Rio");
22129        assert!(
22130            reason.contains("uppercase"),
22131            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
22132        );
22133        assert!(
22134            reason.contains("\"rio\""),
22135            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
22136        );
22137    }
22138
22139    #[test]
22140    fn rejects_placement_cluster_with_underscore() {
22141        // The canonical "I'm thinking of an env var / hostname slug"
22142        // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
22143        // schema. K8s context filtering on `my_cluster` silently misses
22144        // the cluster the author intended; the gate moves it to caixa-
22145        // build time. Same shape as `rejects_membro_caixa_with_underscore`
22146        // (3f9d7a0).
22147        let mut s = three_member_spec();
22148        s.placement.clusters = vec!["my_cluster".into()];
22149        let err = s.validate().unwrap_err();
22150        assert!(
22151            matches!(
22152                err,
22153                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
22154                    if cluster == "my_cluster" && reason.contains('_')
22155            ),
22156            "got {err:?}"
22157        );
22158    }
22159
22160    #[test]
22161    fn rejects_placement_cluster_with_dot() {
22162        // A `:placement :clusters` entry is a single DNS-1123 *label*,
22163        // not a subdomain — even though K8s context names sometimes
22164        // carry a dotted form via kubeconfig conventions, the strictest
22165        // floor among the use sites (DNS-1035 cluster.x-k8s.io
22166        // `metadata.name`, Cilium identity label values) wins. The "I
22167        // want to namespace my cluster names with `.`" intent is
22168        // expressed via `-` (`mar-east`).
22169        let mut s = three_member_spec();
22170        s.placement.clusters = vec!["team.rio".into()];
22171        let err = s.validate().unwrap_err();
22172        assert!(
22173            matches!(
22174                err,
22175                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
22176                    if cluster == "team.rio" && reason.contains('.')
22177            ),
22178            "got {err:?}"
22179        );
22180    }
22181
22182    #[test]
22183    fn rejects_placement_cluster_with_leading_hyphen() {
22184        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
22185        // with an alphanumeric. The K8s apiserver rejects `-rio`
22186        // outright; the rendered fan-out would emit a `metadata.name:
22187        // "-rio"` that fails admission far from the source caixa.lisp.
22188        let mut s = three_member_spec();
22189        s.placement.clusters = vec!["-rio".into()];
22190        let err = s.validate().unwrap_err();
22191        assert!(
22192            matches!(
22193                err,
22194                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
22195                    if cluster == "-rio" && reason.contains("start and end")
22196            ),
22197            "got {err:?}"
22198        );
22199    }
22200
22201    #[test]
22202    fn rejects_placement_cluster_with_trailing_hyphen() {
22203        // The symmetric arm of the boundary rule. Pin separately so
22204        // both ends are covered against a future relaxation that only
22205        // checks one boundary (parallel to
22206        // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
22207        let mut s = three_member_spec();
22208        s.placement.clusters = vec!["rio-".into()];
22209        let err = s.validate().unwrap_err();
22210        assert!(
22211            matches!(
22212                err,
22213                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
22214                    if cluster == "rio-"
22215            ),
22216            "got {err:?}"
22217        );
22218    }
22219
22220    #[test]
22221    fn rejects_placement_cluster_with_unicode() {
22222        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
22223        // before it reaches K8s. The byte-by-byte ASCII validity check
22224        // rejects multi-byte UTF-8 sequences by the first byte that
22225        // fails `[a-z0-9-]`.
22226        let mut s = three_member_spec();
22227        s.placement.clusters = vec!["rió".into()];
22228        let err = s.validate().unwrap_err();
22229        assert!(
22230            matches!(
22231                err,
22232                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
22233                    if cluster == "rió"
22234            ),
22235            "got {err:?}"
22236        );
22237    }
22238
22239    #[test]
22240    fn rejects_placement_cluster_with_whitespace() {
22241        // Whitespace is the canonical "I pasted from a sketch / doc"
22242        // footgun. The apiserver rejects every cluster `metadata.name`
22243        // value carrying whitespace.
22244        let mut s = three_member_spec();
22245        s.placement.clusters = vec!["rio cluster".into()];
22246        let err = s.validate().unwrap_err();
22247        assert!(
22248            matches!(
22249                err,
22250                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
22251                    if cluster == "rio cluster"
22252            ),
22253            "got {err:?}"
22254        );
22255    }
22256
22257    #[test]
22258    fn rejects_placement_cluster_too_long() {
22259        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
22260        // pin. The diagnostic names both the cap (63) and the actual
22261        // length so the author can shorten in one edit. Mirrors
22262        // `rejects_membro_caixa_too_long` (3f9d7a0).
22263        let mut s = three_member_spec();
22264        let too_long = "a".repeat(64);
22265        s.placement.clusters = vec![too_long.clone()];
22266        let err = s.validate().unwrap_err();
22267        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
22268            panic!("expected PlacementClusterInvalid");
22269        };
22270        assert_eq!(cluster, too_long);
22271        assert!(
22272            reason.contains("63") && reason.contains("64"),
22273            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
22274        );
22275    }
22276
22277    #[test]
22278    fn placement_cluster_max_length_validates() {
22279        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
22280        // future tightening (e.g. dropping to 62) surfaces here as a
22281        // regression, mirroring `membro_caixa_max_length_validates`
22282        // (3f9d7a0).
22283        let mut s = three_member_spec();
22284        s.placement.clusters = vec!["a".repeat(63)];
22285        s.validate().unwrap();
22286    }
22287
22288    #[test]
22289    fn accepts_canonical_placement_cluster_forms() {
22290        // The DNS-1123 label shapes a caixa author is realistically
22291        // going to write for cluster names: single-word lowercase
22292        // (`rio`), regional hyphen-joined (`mar-east`), single
22293        // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
22294        // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
22295        // Pin every leg so a future tightening that bans (e.g.) digit-
22296        // start identifiers surfaces here.
22297        for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
22298            let mut s = three_member_spec();
22299            s.placement.clusters = vec![form.into()];
22300            s.validate().unwrap_or_else(|e| {
22301                panic!("canonical cluster form {form:?} must validate, got {e:?}")
22302            });
22303        }
22304    }
22305
22306    #[test]
22307    fn placement_cluster_empty_takes_precedence_over_invalid() {
22308        // Order pin: the existing `PlacementClusterEmpty` diagnostic
22309        // (which doesn't try to parse) fires before the new
22310        // `PlacementClusterInvalid` parse-side diagnostic, so an empty
22311        // `:clusters` entry keeps its narrower error message — the new
22312        // gate would also reject `""`, but the empty-string arm is the
22313        // more self-locating diagnostic. Mirrors the
22314        // `membro_caixa_empty_takes_precedence_over_invalid` pin
22315        // (3f9d7a0).
22316        let mut s = three_member_spec();
22317        s.placement.clusters = vec!["rio".into(), String::new()];
22318        let err = s.validate().unwrap_err();
22319        assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
22320    }
22321
22322    #[test]
22323    fn placement_cluster_invalid_fires_before_duplicate_check() {
22324        // Order pin: a malformed-shape `:clusters` entry surfaces *its
22325        // own* diagnostic, even when a later entry would otherwise
22326        // collapse onto a duplicate name. The per-entry shape gate runs
22327        // inline before the duplicate-key insert, parallel to
22328        // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
22329        let mut s = three_member_spec();
22330        s.placement.clusters = vec!["Rio".into(), "rio".into()];
22331        let err = s.validate().unwrap_err();
22332        assert!(
22333            matches!(
22334                err,
22335                AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
22336            ),
22337            "got {err:?}"
22338        );
22339    }
22340
22341    #[test]
22342    fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
22343        // The diagnostic-shape pin: the error names the offending
22344        // `:clusters` value verbatim so the author can grep their
22345        // caixa.lisp without re-running the build, and carries a
22346        // non-empty `reason` naming the specific violation. Same shape
22347        // every typed-shape gate enshrines
22348        // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
22349        // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
22350        let mut s = three_member_spec();
22351        s.placement.clusters = vec!["BAD_CLUSTER".into()];
22352        let err = s.validate().unwrap_err();
22353        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
22354            panic!("expected PlacementClusterInvalid");
22355        };
22356        assert_eq!(cluster, "BAD_CLUSTER");
22357        assert!(
22358            !reason.is_empty(),
22359            "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
22360        );
22361    }
22362
22363    #[test]
22364    fn rejects_sharded_with_empty_clusters() {
22365        // §III.1: Sharded uses :clusters as the shard pool. An empty
22366        // pool means "shard across no clusters" — meaningless, same as
22367        // Replicated with no hosts.
22368        let mut s = three_member_spec();
22369        s.placement.estrategia = PlacementStrategy::Sharded;
22370        s.placement.shard_key = Some("$tenantId".into());
22371        s.placement.clusters = vec![];
22372        assert!(matches!(
22373            s.validate().unwrap_err(),
22374            AplicacaoError::PlacementWithoutClusters {
22375                estrategia: PlacementStrategy::Sharded
22376            }
22377        ));
22378    }
22379
22380    #[test]
22381    fn rejects_sharded_with_empty_shard_key() {
22382        let mut s = three_member_spec();
22383        s.placement.estrategia = PlacementStrategy::Sharded;
22384        s.placement.shard_key = Some(String::new());
22385        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
22386    }
22387
22388    #[test]
22389    fn rejects_shard_key_under_replicated_strategy() {
22390        // The fail-before-pass-after pin: a `:placement (:estrategia
22391        // Replicated :shard-key "tenantId")` manifest carries the
22392        // hash-keyed-distribution slot on a strategy that never consumes
22393        // it. Before the gate the typed slot's value silently vanished
22394        // at the renderer layer (caixa-mesh emits `placement.shardKey`
22395        // verbatim regardless of strategy; the Akka-style cluster-
22396        // sharding reconciler keys off `estrategia == Sharded` and
22397        // ignores the slot otherwise), with no diagnostic. Lifting the
22398        // rejection to a build-time gate makes the
22399        // `shard_key.is_some() == matches!(estrategia, Sharded)`
22400        // partition a structural property of every validated
22401        // [`Placement`].
22402        let mut s = three_member_spec();
22403        // The fixture already uses Replicated; just add a shard-key.
22404        s.placement.shard_key = Some("$tenantId".into());
22405        let err = s.validate().unwrap_err();
22406        let AplicacaoError::ShardKeyOnNonSharded {
22407            estrategia,
22408            shard_key,
22409        } = err
22410        else {
22411            panic!("expected ShardKeyOnNonSharded, got {err:?}");
22412        };
22413        assert_eq!(estrategia, PlacementStrategy::Replicated);
22414        assert_eq!(shard_key, "$tenantId");
22415    }
22416
22417    #[test]
22418    fn rejects_shard_key_under_singlenode_strategy() {
22419        // Peer of the Replicated case above on the SingleNode arm: OTP
22420        // distributed-app takeover (one cluster runs at a time) has no
22421        // hash-keyed routing axis to consume `:shard-key` either, so
22422        // the rejection fires on both non-Sharded arms uniformly.
22423        let mut s = three_member_spec();
22424        s.placement.estrategia = PlacementStrategy::SingleNode;
22425        s.placement.shard_key = Some("$tenantId".into());
22426        let err = s.validate().unwrap_err();
22427        let AplicacaoError::ShardKeyOnNonSharded {
22428            estrategia,
22429            shard_key,
22430        } = err
22431        else {
22432            panic!("expected ShardKeyOnNonSharded, got {err:?}");
22433        };
22434        assert_eq!(estrategia, PlacementStrategy::SingleNode);
22435        assert_eq!(shard_key, "$tenantId");
22436    }
22437
22438    #[test]
22439    fn rejects_empty_shard_key_under_replicated_strategy() {
22440        // The `Some("")` case under non-Sharded is rejected by
22441        // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
22442        // fires before the empty-value gate), not
22443        // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
22444        // the `Sharded` arm). Pin the partition so a future reorder of
22445        // the validate_placement match arms doesn't silently swap which
22446        // diagnostic the author sees — both are author errors, but
22447        // ShardKeyOnNonSharded names which strategy is the actual fix
22448        // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
22449        // only says "pick a non-empty key".
22450        let mut s = three_member_spec();
22451        s.placement.shard_key = Some(String::new());
22452        let err = s.validate().unwrap_err();
22453        assert!(
22454            matches!(
22455                err,
22456                AplicacaoError::ShardKeyOnNonSharded {
22457                    estrategia: PlacementStrategy::Replicated,
22458                    ref shard_key,
22459                } if shard_key.is_empty()
22460            ),
22461            "got {err:?}"
22462        );
22463    }
22464
22465    #[test]
22466    fn replicated_without_shard_key_validates() {
22467        // The complement of the rejection: `:placement :estrategia
22468        // Replicated` with `:shard-key None` is the canonical happy
22469        // path on every existing fixture. Pin the no-shard-key case so
22470        // the new gate doesn't accidentally fire on `None`.
22471        let mut s = three_member_spec();
22472        assert!(matches!(
22473            s.placement.estrategia,
22474            PlacementStrategy::Replicated
22475        ));
22476        s.placement.shard_key = None;
22477        s.validate().unwrap();
22478    }
22479
22480    #[test]
22481    fn singlenode_without_shard_key_validates() {
22482        // Peer of the Replicated no-shard-key case on the SingleNode
22483        // arm — both non-Sharded strategies must validate cleanly when
22484        // the slot is omitted.
22485        let mut s = three_member_spec();
22486        s.placement.estrategia = PlacementStrategy::SingleNode;
22487        s.placement.shard_key = None;
22488        s.validate().unwrap();
22489    }
22490
22491    fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
22492        // Fixture builder for the `:placement :shard-key` shape gate
22493        // tests: a three-member Aplicacao on the `Sharded` strategy
22494        // with the supplied `:shard-key` slot. Co-locates the
22495        // arm-construction so every test below carries one line of
22496        // setup (the offending `:shard-key` value) and the assertion.
22497        let mut s = three_member_spec();
22498        s.placement.estrategia = PlacementStrategy::Sharded;
22499        s.placement.shard_key = Some(key.into());
22500        s
22501    }
22502
22503    #[test]
22504    fn rejects_shard_key_with_embedded_space() {
22505        // The canonical paste-from-aligned-doc footgun:
22506        // `:shard-key "$tenant Id"` — the Akka-style entity-id
22507        // extractor reads the slot as a single-token reference, and an
22508        // embedded space breaks the token boundary at the runtime
22509        // hash-extractor pass with no diagnostic naming the offending
22510        // entry.
22511        let s = sharded_spec_with_key("$tenant Id");
22512        let err = s.validate().unwrap_err();
22513        assert!(
22514            matches!(
22515                err,
22516                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
22517                    if shard_key == "$tenant Id" && reason.contains("space")
22518            ),
22519            "got {err:?}"
22520        );
22521    }
22522
22523    #[test]
22524    fn rejects_shard_key_with_leading_space() {
22525        // Leading-space arm of the embedded-whitespace footgun — the
22526        // paste-from-aligned-doc / paste-from-CSV-cell variant where
22527        // the leading column-padding leaked into the slot.
22528        let s = sharded_spec_with_key(" $tenantId");
22529        let err = s.validate().unwrap_err();
22530        assert!(
22531            matches!(
22532                err,
22533                AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
22534                    if shard_key == " $tenantId"
22535            ),
22536            "got {err:?}"
22537        );
22538    }
22539
22540    #[test]
22541    fn rejects_shard_key_with_trailing_newline() {
22542        // The canonical paste-from-shell-heredoc footgun — every
22543        // `<<EOF` heredoc terminator paste leaves a trailing newline
22544        // the YAML emitter then folds away inconsistently across
22545        // emitter implementations.
22546        let s = sharded_spec_with_key("$tenantId\n");
22547        let err = s.validate().unwrap_err();
22548        assert!(
22549            matches!(
22550                err,
22551                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
22552                    if shard_key == "$tenantId\n" && reason.contains("0x0a")
22553            ),
22554            "got {err:?}"
22555        );
22556    }
22557
22558    #[test]
22559    fn rejects_shard_key_with_embedded_tab() {
22560        // The paste-from-aligned-doc tab-stop variant — tabs land
22561        // alongside spaces in copy-paste from formatted columns.
22562        let s = sharded_spec_with_key("$tenant\tId");
22563        let err = s.validate().unwrap_err();
22564        assert!(
22565            matches!(
22566                err,
22567                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
22568                    if shard_key == "$tenant\tId" && reason.contains("tab")
22569            ),
22570            "got {err:?}"
22571        );
22572    }
22573
22574    #[test]
22575    fn rejects_shard_key_with_control_character() {
22576        // The paste-from-binary / paste-from-screen-cleared-terminal
22577        // footgun — an embedded `\x01` (SOH) byte that some YAML
22578        // emitters silently strip and others escape as ``,
22579        // breaking round-trip across emitter implementations.
22580        let s = sharded_spec_with_key("$tenant\u{0001}Id");
22581        let err = s.validate().unwrap_err();
22582        assert!(
22583            matches!(
22584                err,
22585                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
22586                    if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
22587            ),
22588            "got {err:?}"
22589        );
22590    }
22591
22592    #[test]
22593    fn rejects_shard_key_with_non_ascii() {
22594        // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
22595        // footgun — non-ASCII bytes normalize differently between the
22596        // caixa-mesh-side YAML emitter and the in-cluster reconciler's
22597        // YAML parser, the same entity ID can silently map to two
22598        // distinct shards on a re-render.
22599        let s = sharded_spec_with_key("$tenàntId");
22600        let err = s.validate().unwrap_err();
22601        assert!(
22602            matches!(
22603                err,
22604                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
22605                    if shard_key == "$tenàntId" && reason.contains("non-ASCII")
22606            ),
22607            "got {err:?}"
22608        );
22609    }
22610
22611    #[test]
22612    fn rejects_shard_key_too_long() {
22613        // Length cap pin: 64 bytes — one byte over the
22614        // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
22615        // here is a paste-from-doc multi-line blob landing in
22616        // `:shard-key` instead of a single-token extractor expression.
22617        let too_long = "a".repeat(64);
22618        let s = sharded_spec_with_key(&too_long);
22619        let err = s.validate().unwrap_err();
22620        let AplicacaoError::ShardKeyInvalid {
22621            ref shard_key,
22622            ref reason,
22623        } = err
22624        else {
22625            panic!("expected ShardKeyInvalid, got {err:?}");
22626        };
22627        assert_eq!(shard_key, &too_long);
22628        assert!(
22629            reason.contains("63") && reason.contains("64"),
22630            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
22631        );
22632    }
22633
22634    #[test]
22635    fn shard_key_max_length_validates() {
22636        // Boundary pin: 63 bytes exactly — the
22637        // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
22638        // dropping to 62) surfaces here as a regression, mirroring
22639        // `placement_cluster_max_length_validates` /
22640        // `placement_affinity_max_length_validates` on the peer
22641        // identifier-shaped slots.
22642        let s = sharded_spec_with_key(&"a".repeat(63));
22643        s.validate().unwrap();
22644    }
22645
22646    #[test]
22647    fn accepts_canonical_shard_key_forms() {
22648        // The Akka-style entity-id extractor shapes a caixa author is
22649        // realistically going to write — pin every leg so a future
22650        // tightening that bans (e.g.) the `${...}` interpolation
22651        // variant or the `metadata.<field>` JSONPath form surfaces
22652        // here as a regression. The canonical forms span:
22653        //
22654        //   - bare property name (`tenantId`, `customerId`)
22655        //   - Akka `ExtractEntityId` placeholder (`$tenantId`)
22656        //   - JSONPath-style nested reference (`metadata.tenantId`,
22657        //     `$.user.id`)
22658        //   - interpolation-style template (`${tenant}`)
22659        //   - snake_case property name (`customer_id`)
22660        //   - kebab-case property name (`customer-id` — accepted
22661        //     because the slot is a printable-ASCII single-token
22662        //     reference, not a DNS-1123 label like
22663        //     `:placement :affinity` / `:clusters`)
22664        //   - single character (`a`, `$` — boundary)
22665        for form in [
22666            "tenantId",
22667            "customerId",
22668            "$tenantId",
22669            "metadata.tenantId",
22670            "$.user.id",
22671            "${tenant}",
22672            "customer_id",
22673            "customer-id",
22674            "a",
22675            "$",
22676        ] {
22677            let s = sharded_spec_with_key(form);
22678            s.validate().unwrap_or_else(|e| {
22679                panic!("canonical shard-key form {form:?} must validate, got {e:?}")
22680            });
22681        }
22682    }
22683
22684    #[test]
22685    fn shard_key_empty_takes_precedence_over_invalid() {
22686        // Order pin: the existing `ShardedKeyEmpty` diagnostic
22687        // (reserved for the `Sharded` `Some("")` arm) fires before the
22688        // new `ShardKeyInvalid` parse-side diagnostic, so an empty
22689        // `:shard-key` keeps its narrower error message — the new gate
22690        // would also reject `""` defensively, but the empty-string arm
22691        // is the more self-locating diagnostic. Mirrors the
22692        // `placement_cluster_empty_takes_precedence_over_invalid` pin
22693        // on the peer identifier-shaped slot.
22694        let s = sharded_spec_with_key("");
22695        let err = s.validate().unwrap_err();
22696        assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
22697    }
22698
22699    #[test]
22700    fn shard_key_invalid_diagnostic_carries_offending_value() {
22701        // The diagnostic-shape pin: the error names the offending
22702        // `:shard-key` value verbatim so the author can grep their
22703        // caixa.lisp without re-running the build, and carries a
22704        // parser-shaped `reason:` naming the specific violation —
22705        // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
22706        // on the peer identifier-shaped slot.
22707        let s = sharded_spec_with_key("$tenant Id");
22708        let err = s.validate().unwrap_err();
22709        let AplicacaoError::ShardKeyInvalid {
22710            ref shard_key,
22711            ref reason,
22712        } = err
22713        else {
22714            panic!("expected ShardKeyInvalid, got {err:?}");
22715        };
22716        assert_eq!(shard_key, "$tenant Id");
22717        assert!(
22718            !reason.is_empty(),
22719            "reason must name the specific violation, got empty string"
22720        );
22721    }
22722
22723    #[test]
22724    fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
22725        // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
22726        // `:shard-key` carried on non-Sharded strategies) fires before
22727        // the shape gate, so a malformed `:shard-key` carried on (e.g.)
22728        // a `Replicated` strategy surfaces the more self-locating
22729        // strategy-mismatch diagnostic (naming the actual fix — drop
22730        // the slot, or switch to Sharded) rather than the shape
22731        // diagnostic. The strategy-mismatch arm is the more actionable
22732        // diagnostic: a malformed shard-key on Replicated is "you
22733        // shouldn't have a :shard-key here at all", not "your
22734        // :shard-key value is malformed".
22735        let mut s = three_member_spec();
22736        // Replicated is the default fixture strategy.
22737        s.placement.shard_key = Some("$tenant Id".into());
22738        let err = s.validate().unwrap_err();
22739        assert!(
22740            matches!(
22741                err,
22742                AplicacaoError::ShardKeyOnNonSharded {
22743                    estrategia: PlacementStrategy::Replicated,
22744                    ..
22745                }
22746            ),
22747            "got {err:?}"
22748        );
22749    }
22750
22751    #[test]
22752    fn rejects_empty_affinity_hint() {
22753        let mut s = three_member_spec();
22754        s.placement.affinity = Some(String::new());
22755        assert_eq!(
22756            s.validate().unwrap_err(),
22757            AplicacaoError::PlacementAffinityEmpty
22758        );
22759    }
22760
22761    #[test]
22762    fn placement_without_affinity_validates() {
22763        // Omitting :affinity is fine — the placement engine falls back
22764        // to the default heuristic. Pin the no-hint case so the
22765        // affinity-empty rejection doesn't accidentally fire on `None`.
22766        let mut s = three_member_spec();
22767        s.placement.affinity = None;
22768        s.validate().unwrap();
22769    }
22770
22771    #[test]
22772    fn rejects_placement_affinity_with_uppercase() {
22773        // The canonical "I copied the ADR's display name verbatim" typo
22774        // — placement hints land verbatim in K8s label-selector
22775        // territory, where the apiserver enforces the DNS-1123 label
22776        // rule (lowercase-only) on every identity-keyed admission axis.
22777        // Mirrors `rejects_placement_cluster_with_uppercase` on the
22778        // sibling slot.
22779        let mut s = three_member_spec();
22780        s.placement.affinity = Some("DataLocality".into());
22781        let err = s.validate().unwrap_err();
22782        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
22783            panic!("expected PlacementAffinityInvalid, got other variant");
22784        };
22785        assert_eq!(affinity, "DataLocality");
22786        assert!(
22787            reason.contains("uppercase"),
22788            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
22789        );
22790        assert!(
22791            reason.contains("\"datalocality\""),
22792            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
22793        );
22794    }
22795
22796    #[test]
22797    fn rejects_placement_affinity_with_underscore() {
22798        // The canonical "I'm thinking of an env var / Python identifier"
22799        // leak — `_` is forbidden by every DNS-1123 label schema. Same
22800        // shape as `rejects_placement_cluster_with_underscore` on the
22801        // sibling slot.
22802        let mut s = three_member_spec();
22803        s.placement.affinity = Some("data_locality".into());
22804        let err = s.validate().unwrap_err();
22805        assert!(
22806            matches!(
22807                err,
22808                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
22809                    if affinity == "data_locality" && reason.contains('_')
22810            ),
22811            "got {err:?}"
22812        );
22813    }
22814
22815    #[test]
22816    fn rejects_placement_affinity_with_dot() {
22817        // A `:placement :affinity` value is a single DNS-1123 *label*
22818        // (it lands as a K8s label value selector key), not a subdomain.
22819        // The "I want to namespace my hint with `.`" intent is expressed
22820        // via `-` (`data-locality-east`).
22821        let mut s = three_member_spec();
22822        s.placement.affinity = Some("data.locality".into());
22823        let err = s.validate().unwrap_err();
22824        assert!(
22825            matches!(
22826                err,
22827                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
22828                    if affinity == "data.locality" && reason.contains('.')
22829            ),
22830            "got {err:?}"
22831        );
22832    }
22833
22834    #[test]
22835    fn rejects_placement_affinity_with_unicode() {
22836        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
22837        // before it reaches K8s. The byte-by-byte ASCII validity check
22838        // rejects multi-byte UTF-8 sequences by the first byte that
22839        // fails `[a-z0-9-]`.
22840        let mut s = three_member_spec();
22841        s.placement.affinity = Some("data-localité".into());
22842        let err = s.validate().unwrap_err();
22843        assert!(
22844            matches!(
22845                err,
22846                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
22847                    if affinity == "data-localité"
22848            ),
22849            "got {err:?}"
22850        );
22851    }
22852
22853    #[test]
22854    fn rejects_placement_affinity_with_leading_hyphen() {
22855        // DNS-1123 boundary rule: labels must start with an
22856        // alphanumeric. Pin separately from the trailing-hyphen arm so
22857        // a future relaxation that only checks one boundary surfaces
22858        // here as a regression (parallel to
22859        // `rejects_placement_cluster_with_leading_hyphen`).
22860        let mut s = three_member_spec();
22861        s.placement.affinity = Some("-data-locality".into());
22862        let err = s.validate().unwrap_err();
22863        assert!(
22864            matches!(
22865                err,
22866                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
22867                    if affinity == "-data-locality" && reason.contains("start and end")
22868            ),
22869            "got {err:?}"
22870        );
22871    }
22872
22873    #[test]
22874    fn rejects_placement_affinity_with_trailing_hyphen() {
22875        // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
22876        // ends are covered against a future relaxation.
22877        let mut s = three_member_spec();
22878        s.placement.affinity = Some("data-locality-".into());
22879        let err = s.validate().unwrap_err();
22880        assert!(
22881            matches!(
22882                err,
22883                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
22884                    if affinity == "data-locality-"
22885            ),
22886            "got {err:?}"
22887        );
22888    }
22889
22890    #[test]
22891    fn rejects_placement_affinity_with_whitespace() {
22892        // Whitespace is the canonical "I pasted from a sketch / doc"
22893        // footgun. The apiserver rejects every label-selector value
22894        // carrying whitespace.
22895        let mut s = three_member_spec();
22896        s.placement.affinity = Some("data locality".into());
22897        let err = s.validate().unwrap_err();
22898        assert!(
22899            matches!(
22900                err,
22901                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
22902                    if affinity == "data locality"
22903            ),
22904            "got {err:?}"
22905        );
22906    }
22907
22908    #[test]
22909    fn rejects_placement_affinity_too_long() {
22910        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
22911        // pin. The diagnostic names both the cap (63) and the actual
22912        // length so the author can shorten in one edit. Mirrors
22913        // `rejects_placement_cluster_too_long`.
22914        let mut s = three_member_spec();
22915        let too_long = "a".repeat(64);
22916        s.placement.affinity = Some(too_long.clone());
22917        let err = s.validate().unwrap_err();
22918        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
22919            panic!("expected PlacementAffinityInvalid");
22920        };
22921        assert_eq!(affinity, too_long);
22922        assert!(
22923            reason.contains("63") && reason.contains("64"),
22924            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
22925        );
22926    }
22927
22928    #[test]
22929    fn placement_affinity_max_length_validates() {
22930        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
22931        // future tightening (e.g. dropping to 62) surfaces here as a
22932        // regression, mirroring `placement_cluster_max_length_validates`.
22933        let mut s = three_member_spec();
22934        s.placement.affinity = Some("a".repeat(63));
22935        s.validate().unwrap();
22936    }
22937
22938    #[test]
22939    fn accepts_canonical_placement_affinity_forms() {
22940        // The DNS-1123 label shapes a caixa author is realistically
22941        // going to write for placement hints: the M3 canonical examples
22942        // (`data-locality`, `low-latency`, `anti-affinity`), the
22943        // single-token form (`affinity`), the single-character boundary
22944        // (`a`), the digit-start (DNS-1123 allows this, unlike
22945        // DNS-1035), and a regional-suffixed form. Pin every leg so a
22946        // future tightening that bans (e.g.) digit-start identifiers
22947        // surfaces here.
22948        for form in [
22949            "data-locality",
22950            "low-latency",
22951            "anti-affinity",
22952            "affinity",
22953            "a",
22954            "3-tier",
22955            "locality-east",
22956        ] {
22957            let mut s = three_member_spec();
22958            s.placement.affinity = Some(form.into());
22959            s.validate().unwrap_or_else(|e| {
22960                panic!("canonical affinity form {form:?} must validate, got {e:?}")
22961            });
22962        }
22963    }
22964
22965    #[test]
22966    fn placement_affinity_empty_takes_precedence_over_invalid() {
22967        // Order pin: the existing `PlacementAffinityEmpty` diagnostic
22968        // (which doesn't try to parse) fires before the new
22969        // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
22970        // `:affinity` keeps its narrower error message — the new gate
22971        // would also reject `""`, but the empty-string arm is the more
22972        // self-locating diagnostic. Mirrors the
22973        // `placement_cluster_empty_takes_precedence_over_invalid` pin.
22974        let mut s = three_member_spec();
22975        s.placement.affinity = Some(String::new());
22976        let err = s.validate().unwrap_err();
22977        assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
22978    }
22979
22980    #[test]
22981    fn placement_affinity_invalid_diagnostic_carries_offending_value() {
22982        // The diagnostic shape pin: every rejection carries the offending
22983        // `affinity:` verbatim plus a parser-shaped `reason:` so the
22984        // author can grep their caixa.lisp for `:affinity "<hint>"` and
22985        // fix it in one edit. Mirrors the
22986        // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
22987        // pin on the sibling slot.
22988        let mut s = three_member_spec();
22989        s.placement.affinity = Some("Data_Locality".into());
22990        let err = s.validate().unwrap_err();
22991        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
22992            panic!("expected PlacementAffinityInvalid");
22993        };
22994        assert_eq!(affinity, "Data_Locality");
22995        assert!(
22996            !reason.is_empty(),
22997            "diagnostic reason must not be empty (got: {reason:?})"
22998        );
22999    }
23000
23001    #[test]
23002    fn singlenode_with_takeover_candidates_validates() {
23003        // OTP distributed-application convention (MESH-COMPOSITION
23004        // §II.1): SingleNode runs on one cluster at a time but the
23005        // :clusters list enumerates the takeover candidates. Multiple
23006        // entries are not a contradiction — they are the failover pool.
23007        let mut s = three_member_spec();
23008        s.placement.estrategia = PlacementStrategy::SingleNode;
23009        s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
23010        s.validate().unwrap();
23011    }
23012
23013    // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
23014
23015    #[test]
23016    fn mesh_policy_default_is_empty() {
23017        // The Default impl carries None on every axis — the typed
23018        // analog of an unset `:politicas (())` slot. Renderers that
23019        // overlay the policy onto a cluster artifact key off this
23020        // predicate to skip the slot entirely; pinning so a future
23021        // axis added to MeshPolicy can't silently break the contract
23022        // (a new field whose Default is non-None would flip is_empty
23023        // to false on every existing caixa, surfacing here).
23024        assert!(MeshPolicy::default().is_empty());
23025    }
23026
23027    #[test]
23028    fn mesh_policy_with_only_timeout_is_not_empty() {
23029        let p = MeshPolicy {
23030            timeout: Some(Duration::from_secs(30)),
23031            ..Default::default()
23032        };
23033        assert!(!p.is_empty());
23034    }
23035
23036    #[test]
23037    fn mesh_policy_with_only_retries_is_not_empty() {
23038        let p = MeshPolicy {
23039            retries: Some(3),
23040            ..Default::default()
23041        };
23042        assert!(!p.is_empty());
23043    }
23044
23045    #[test]
23046    fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
23047        let p = MeshPolicy {
23048            circuit_breaker: Some(CircuitBreaker {
23049                max_failures: 5,
23050                window: Duration::from_secs(60),
23051            }),
23052            ..Default::default()
23053        };
23054        assert!(!p.is_empty());
23055    }
23056
23057    #[test]
23058    fn mesh_policy_with_only_mtls_required_is_not_empty() {
23059        // Even `mtls_required: Some(false)` (an explicit opt-out) is
23060        // not empty — the author *named* the axis, the renderer needs
23061        // to honor that vs. fall back to the cluster default.
23062        let p = MeshPolicy {
23063            mtls_required: Some(false),
23064            ..Default::default()
23065        };
23066        assert!(!p.is_empty());
23067    }
23068
23069    #[test]
23070    fn mesh_policy_with_only_rate_limit_is_not_empty() {
23071        let p = MeshPolicy {
23072            rate_limit: Some(RateLimit {
23073                rate: 100,
23074                window: Duration::from_secs(1),
23075            }),
23076            ..Default::default()
23077        };
23078        assert!(!p.is_empty());
23079    }
23080
23081    #[test]
23082    fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
23083        // The three-member happy-path fixture sets timeout + retries +
23084        // mtls_required — every populated axis must read non-empty.
23085        // Pin the round-trip so the M3.x per-:politicas emitter (the
23086        // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
23087        // on is_empty() to decide whether to emit at all without
23088        // re-deriving the contract from inline field probes.
23089        assert!(!three_member_spec().politicas.is_empty());
23090    }
23091
23092    // ── shared duration codec: cross-slot integer-magnitude gate ──
23093    //
23094    // The integer-magnitude discipline applied to
23095    // `supervisor::duration_codec::parse` lifts onto every typed slot
23096    // that routes through the shared codec — `MeshPolicy::timeout`
23097    // (`:politicas :timeout`) and `CircuitBreaker::window`
23098    // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
23099    // These cross-slot tests pin that the gate fires at the serde
23100    // layer for both typed slots, not just for the supervisor side.
23101
23102    #[test]
23103    fn policy_timeout_serde_rejects_fractional_seconds() {
23104        // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
23105        // so the shared codec's integer-magnitude gate applies on
23106        // deserialize. `"1.5s"` previously parsed to 1500ms and round-
23107        // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
23108        // deserialize with the canonical-form diagnostic naming the
23109        // offending `"1.5"` and the remediation `"1500ms"`.
23110        let payload = r#"{"timeout":"1.5s"}"#;
23111        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23112        let msg = err.to_string();
23113        assert!(
23114            msg.contains("not a non-negative integer"),
23115            "expected integer-magnitude diagnostic in {msg:?}"
23116        );
23117        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
23118        assert!(
23119            msg.contains("\"1500ms\""),
23120            "missing canonical-form remediation in {msg:?}"
23121        );
23122    }
23123
23124    #[test]
23125    fn policy_timeout_serde_rejects_leading_plus_sign() {
23126        // Pin the leading-`+` arm cross-slot — the prior f64 parser
23127        // accepted `"+30s"` silently and round-tripped to `"30s"`.
23128        let payload = r#"{"timeout":"+30s"}"#;
23129        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23130        let msg = err.to_string();
23131        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
23132    }
23133
23134    #[test]
23135    fn circuit_breaker_window_serde_rejects_fractional_minutes() {
23136        // `CircuitBreaker::window` uses `with =
23137        // "supervisor::duration_codec_required"` (the required-Duration
23138        // variant that delegates to the same shared parser). `"0.5m"`
23139        // parsed to 30s and round-tripped to `"30s"` on next emit —
23140        // DRIFT closed.
23141        let payload = format!(
23142            r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
23143            max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
23144            window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
23145        );
23146        let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
23147        let msg = err.to_string();
23148        assert!(
23149            msg.contains("not a non-negative integer"),
23150            "expected integer-magnitude diagnostic in {msg:?}"
23151        );
23152        assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
23153        assert!(
23154            msg.contains("\"30s\""),
23155            "missing canonical-form remediation in {msg:?}"
23156        );
23157    }
23158
23159    #[test]
23160    fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
23161        // Pin the happy-path on the cross-slot side: every canonical
23162        // author shape `render` ever emits parses cleanly through the
23163        // shared codec on the `CircuitBreaker` slot. The
23164        // codec's accepted set (post-gate) is exactly its emitted set
23165        // for the integer-magnitude class.
23166        for window_lit in ["30s", "500ms", "2m", "1h"] {
23167            let payload = format!(
23168                r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
23169                max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
23170                window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
23171            );
23172            let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
23173                panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
23174            });
23175            assert_eq!(cb.max_failures, 5);
23176        }
23177    }
23178
23179    // ── rate_limit_codec: integer-magnitude gate ──
23180    //
23181    // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
23182    // / 737a676 / d53c922 trajectory landed on every typed-duration /
23183    // typed-byte-size codec in caixa-core lifts onto the fifth typed
23184    // codec — `rate_limit_codec` — through the digit-only magnitude
23185    // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
23186    // These tests pin the gate at the serde layer for `:politicas
23187    // :rate-limit` (the only typed slot the codec backs), and at the
23188    // codec-internal `parse` layer for the canonical positive cases.
23189
23190    #[test]
23191    fn rate_limit_serde_rejects_fractional_rate() {
23192        // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
23193        // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
23194        // wording, which didn't name the canonical-form remediation or
23195        // the round-trip drift the next emit would produce. Now refused
23196        // at deserialize with the canonical-form diagnostic naming the
23197        // offending `"1.5"` magnitude and the round-trip drift wording.
23198        let payload = r#"{"rateLimit":"1.5/s"}"#;
23199        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23200        let msg = err.to_string();
23201        assert!(
23202            msg.contains("not a non-negative integer"),
23203            "expected integer-magnitude diagnostic in {msg:?}"
23204        );
23205        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
23206        assert!(
23207            msg.contains("THEORY.md"),
23208            "missing render-determinism contract citation in {msg:?}"
23209        );
23210    }
23211
23212    #[test]
23213    fn rate_limit_serde_rejects_leading_plus_sign() {
23214        // `u32::from_str("+100")` returns `Ok(100)` (Rust's
23215        // permissive-`+` parse), so `"+100/s"` silently parsed to
23216        // `RateLimit { 100, 1s }` and round-tripped through `render` to
23217        // `"100/s"` — a *different* canonical string on the next emit,
23218        // breaking the THEORY.md Part V render-determinism contract
23219        // exactly the way the peer duration codecs' `"+30s"` case did.
23220        // This is the load-bearing class the digit-only gate closes
23221        // beyond what `u32::from_str`'s strictness covers on its own.
23222        let payload = r#"{"rateLimit":"+100/s"}"#;
23223        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23224        let msg = err.to_string();
23225        assert!(
23226            msg.contains("not a non-negative integer"),
23227            "expected integer-magnitude diagnostic in {msg:?}"
23228        );
23229        assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
23230    }
23231
23232    #[test]
23233    fn rate_limit_serde_rejects_leading_minus_sign() {
23234        // The signed-negative arm: `"-1/s"` lands on the
23235        // non-canonical-but-numeric branch via the `i64` fallback (the
23236        // `f64` parse also succeeds), surfacing the canonical-form
23237        // diagnostic. Replaces the prior value-laundered "not a u32"
23238        // wording with the unified diagnostic across signs.
23239        let payload = r#"{"rateLimit":"-1/s"}"#;
23240        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23241        let msg = err.to_string();
23242        assert!(
23243            msg.contains("not a non-negative integer"),
23244            "expected integer-magnitude diagnostic in {msg:?}"
23245        );
23246        assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
23247    }
23248
23249    #[test]
23250    fn rate_limit_serde_rejects_decimal_shaped_integer() {
23251        // `"100.0/s"` is integer-valued numerically but not in the
23252        // codec's accepted set — `render` emits `"100/s"`, so the
23253        // round-trip would drift. Lifted to the canonical-form
23254        // diagnostic peer with the duration codec's `"1.0s"` case
23255        // (1c55a2a).
23256        let payload = r#"{"rateLimit":"100.0/s"}"#;
23257        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23258        let msg = err.to_string();
23259        assert!(
23260            msg.contains("not a non-negative integer"),
23261            "expected integer-magnitude diagnostic in {msg:?}"
23262        );
23263        assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
23264    }
23265
23266    #[test]
23267    fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
23268        // Non-numeric, non-digit-only input lands on the existing
23269        // narrower `"not a u32"` arm (preserved for diagnostic-shape
23270        // stability on the parser-shape footgun case). Pin this so a
23271        // future relaxation of the numeric-fallback predicate doesn't
23272        // silently collapse garbage onto the canonical-form arm — same
23273        // partition the peer duration codecs draw between
23274        // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
23275        let payload = r#"{"rateLimit":"abc/s"}"#;
23276        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23277        let msg = err.to_string();
23278        assert!(
23279            msg.contains("not a u32"),
23280            "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
23281        );
23282        assert!(
23283            !msg.contains("not a non-negative integer"),
23284            "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
23285        );
23286    }
23287
23288    #[test]
23289    fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
23290        // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
23291        // u32's range. The digit-only gate passes; `u32::from_str`
23292        // fails on overflow. Surface that with the overflow-shaped
23293        // diagnostic naming the offending magnitude verbatim, peer
23294        // with `supervisor::duration_codec`'s overflow arm. Pinning
23295        // the wording so a future refactor doesn't silently collapse
23296        // overflow onto the canonical-form arm.
23297        let payload = r#"{"rateLimit":"4294967296/s"}"#;
23298        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23299        let msg = err.to_string();
23300        assert!(
23301            msg.contains("overflows u32"),
23302            "expected overflow diagnostic in {msg:?}"
23303        );
23304        assert!(
23305            msg.contains("\"4294967296\""),
23306            "missing offending magnitude in {msg:?}"
23307        );
23308    }
23309
23310    #[test]
23311    fn rate_limit_serde_rejects_leading_zero_magnitude() {
23312        // `"0100/s"` is digit-only, so the existing
23313        // non-digit-only / sign / fractional arm doesn't catch it —
23314        // `u32::from_str("0100")` returns `Ok(100)`, so before this
23315        // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
23316        // round-tripped through `render` to `"100/s"` — a *different*
23317        // canonical string on the next emit, breaking the THEORY.md
23318        // Part V render-determinism contract exactly the way the
23319        // peer `"+100/s"` case did before the leading-`+` arm landed.
23320        // This is the load-bearing class the leading-zero gate closes
23321        // beyond what the existing digit-only / sign / fractional
23322        // gates cover, and the peer arm to the leading-`+` test
23323        // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
23324        // canonical-form-drift axis.
23325        let payload = r#"{"rateLimit":"0100/s"}"#;
23326        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23327        let msg = err.to_string();
23328        assert!(
23329            msg.contains("non-canonical leading zero"),
23330            "expected leading-zero diagnostic in {msg:?}"
23331        );
23332        assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
23333        assert!(
23334            msg.contains("THEORY.md"),
23335            "missing render-determinism contract citation in {msg:?}"
23336        );
23337    }
23338
23339    #[test]
23340    fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
23341        // `"00/s"` is the degenerate leading-zero case — every byte
23342        // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
23343        // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
23344        // a *different* canonical string, same render-determinism
23345        // violation. The single-byte `"0/s"` itself is in the
23346        // accepted set (round-trips losslessly through `render`,
23347        // refused downstream by `PolicyRateLimitZero`); the
23348        // multi-byte `"00/s"` is not. Pins the boundary between the
23349        // accepted single-`0` and the rejected leading-zero class.
23350        let payload = r#"{"rateLimit":"00/s"}"#;
23351        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23352        let msg = err.to_string();
23353        assert!(
23354            msg.contains("non-canonical leading zero"),
23355            "expected leading-zero diagnostic in {msg:?}"
23356        );
23357        assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
23358    }
23359
23360    #[test]
23361    fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
23362        // Cross-window pin — the gate is window-agnostic; the
23363        // leading-zero class is a property of the magnitude, not the
23364        // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
23365        // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
23366        // single-window coverage extended across the three canonical
23367        // windows the codec accepts.
23368        let payload = r#"{"rateLimit":"007/h"}"#;
23369        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23370        let msg = err.to_string();
23371        assert!(
23372            msg.contains("non-canonical leading zero"),
23373            "expected leading-zero diagnostic in {msg:?}"
23374        );
23375        assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
23376    }
23377
23378    #[test]
23379    fn rate_limit_serde_rejects_leading_whitespace() {
23380        // `" 100/s"` — the canonical paste-from-aligned-doc /
23381        // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
23382        // the top-level `s.trim()` silently ate the leading space and
23383        // parsed the value to `RateLimit { 100, 1s }`, which then
23384        // round-tripped through `render` to `"100/s"` (a *different*
23385        // canonical string on the next emit) — the exact
23386        // canonical-form-drift class the leading-`+` / leading-zero
23387        // arms already close, extended to the whitespace byte class.
23388        let payload = r#"{"rateLimit":" 100/s"}"#;
23389        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23390        let msg = err.to_string();
23391        assert!(
23392            msg.contains("contains whitespace byte"),
23393            "expected whitespace diagnostic in {msg:?}"
23394        );
23395        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
23396        assert!(
23397            msg.contains("THEORY.md"),
23398            "missing render-determinism contract citation in {msg:?}"
23399        );
23400    }
23401
23402    #[test]
23403    fn rate_limit_serde_rejects_trailing_whitespace() {
23404        // `"100/s "` — the canonical shell-history / trailing-space
23405        // paste footgun. Before this gate the top-level `s.trim()`
23406        // silently ate the trailing space and parsed to
23407        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
23408        // next emit — same canonical-form drift as the leading-space
23409        // sibling, closed on the same whitespace-byte arm.
23410        let payload = r#"{"rateLimit":"100/s "}"#;
23411        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23412        let msg = err.to_string();
23413        assert!(
23414            msg.contains("contains whitespace byte"),
23415            "expected whitespace diagnostic in {msg:?}"
23416        );
23417        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
23418    }
23419
23420    #[test]
23421    fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
23422        // `"100 / s"` — the canonical typographically-spaced author
23423        // shape (the same idiom every prose reference to a rate limit
23424        // renders as, mistakenly retained when the value is pasted
23425        // into a codec-shaped slot). Before this gate the per-part
23426        // `rate_str.trim()` / `unit.trim()` calls silently ate both
23427        // spaces on either side of `/` and parsed to
23428        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
23429        // codec's *internal* whitespace-tolerance vector, orthogonal
23430        // to the leading / trailing surface but the same canonical-
23431        // form-drift class. Pins the arm as strictly stronger than the
23432        // pre-existing top-level `s.trim()` behavior: it fires on
23433        // whitespace anywhere in the value, not just at the string
23434        // boundary.
23435        let payload = r#"{"rateLimit":"100 / s"}"#;
23436        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23437        let msg = err.to_string();
23438        assert!(
23439            msg.contains("contains whitespace byte"),
23440            "expected whitespace diagnostic in {msg:?}"
23441        );
23442        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
23443    }
23444
23445    #[test]
23446    fn rate_limit_serde_rejects_tab_byte() {
23447        // `"\t100/s"` — the canonical paste-from-indented-doc /
23448        // paste-from-YAML-block-scalar footgun where a tab byte leads
23449        // the magnitude. Pins that the gate covers tab (`0x09`) as
23450        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
23451        // members and both would be silently swallowed by `s.trim()`
23452        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
23453        // space alone to the full ASCII-whitespace set (space `0x20`,
23454        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
23455        // the tab arm as a representative of the non-space members.
23456        let payload = r#"{"rateLimit":"\t100/s"}"#;
23457        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23458        let msg = err.to_string();
23459        assert!(
23460            msg.contains("contains whitespace byte"),
23461            "expected whitespace diagnostic in {msg:?}"
23462        );
23463        assert!(
23464            msg.contains("0x09"),
23465            "missing offending tab byte in {msg:?}"
23466        );
23467    }
23468
23469    // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
23470    //
23471    // Successor to the ASCII-whitespace arm (1ad7755) on
23472    // `rate_limit_codec` — closes the strictly-complementary class the
23473    // byte-scan cannot see, through the lifted
23474    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
23475
23476    #[test]
23477    fn rate_limit_serde_rejects_leading_nbsp() {
23478        // NBSP prefix — paste-from-typography footgun. Byte-scan
23479        // misses, `str::trim` silently strips it, value drifts to
23480        // `"100/s"` on next serialize.
23481        let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
23482        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23483        let msg = err.to_string();
23484        assert!(
23485            msg.contains("non-ASCII Unicode whitespace character"),
23486            "expected non-ASCII whitespace diagnostic in {msg:?}"
23487        );
23488        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
23489    }
23490
23491    #[test]
23492    fn rate_limit_serde_rejects_internal_em_space() {
23493        // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
23494        // paste-from-typography footgun on the `<integer>/<unit>`
23495        // shape.
23496        let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
23497        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23498        let msg = err.to_string();
23499        assert!(
23500            msg.contains("non-ASCII Unicode whitespace character"),
23501            "expected non-ASCII whitespace diagnostic in {msg:?}"
23502        );
23503        assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
23504    }
23505
23506    #[test]
23507    fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
23508        // Positive-control pin: every ASCII-only canonical form the
23509        // renderer emits stays accepted through the new arm.
23510        for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
23511            let payload = format!(r#"{{"rateLimit":{lit}}}"#);
23512            let p: MeshPolicy = serde_json::from_str(&payload)
23513                .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
23514            assert!(p.rate_limit.is_some());
23515        }
23516    }
23517
23518    #[test]
23519    fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
23520        // The boundary case — `"0/s"` is the canonical form
23521        // `render(RateLimit { 0, 1s })` emits, so the codec accepts
23522        // it at the parse layer; the downstream
23523        // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
23524        // `rate == 0` at the typed-validate layer above. Pins the
23525        // partition: the leading-zero gate at the codec layer does
23526        // not poach the rate-zero semantic-validation arm at the
23527        // typed-validate layer above (a future stricter codec must
23528        // not reject `"0/s"` here, or it'd collapse the diagnostic
23529        // partitioning that lets `PolicyRateLimitZero` name the
23530        // offending typed slot).
23531        let payload = r#"{"rateLimit":"0/s"}"#;
23532        let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
23533            panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
23534        });
23535        let rl = policy.rate_limit.expect("rate_limit must be Some");
23536        assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
23537        assert_eq!(
23538            rl.window,
23539            Duration::from_secs(1),
23540            "single-`0` magnitude with `s` unit must parse to window=1s"
23541        );
23542    }
23543
23544    #[test]
23545    fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
23546        // The complementary boundary pin — every magnitude
23547        // `render` emits starts with `[1-9]` (or is the single byte
23548        // `"0"`), so the canonical-form predicate is `(len == 1) ||
23549        // (first byte != '0')`. Pinning the `len > 1 && first byte ==
23550        // '1'` case explicitly so a future tightening of the gate
23551        // (e.g. an over-eager "no leading digit < 5" rule, or a
23552        // mistakenly anchored start-of-magnitude byte check) lands
23553        // here before the canonical-forms-iterating test would catch
23554        // it.
23555        let payload = r#"{"rateLimit":"100/s"}"#;
23556        let policy: MeshPolicy = serde_json::from_str(payload)
23557            .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
23558        let rl = policy.rate_limit.expect("rate_limit must be Some");
23559        assert_eq!(
23560            rl.rate, 100,
23561            "canonical-100 magnitude must parse to rate=100"
23562        );
23563    }
23564
23565    #[test]
23566    fn rate_limit_serde_accepts_integer_canonical_forms() {
23567        // Pin the happy-path: every canonical author shape `render`
23568        // ever emits parses cleanly through the codec post-gate. The
23569        // codec's accepted set (post-gate) is exactly its emitted set
23570        // for the integer-magnitude class — same property
23571        // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
23572        // gates guarantee on the peer codecs. Iterating across rate
23573        // magnitudes (including `"0"`, which the codec accepts even
23574        // though `validate_politicas` rejects `rate == 0` at the typed
23575        // layer above) closes the codec contract at the parse layer
23576        // independently of the validate layer.
23577        for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
23578            for unit_lit in ["s", "m", "h"] {
23579                let lit = format!("{rate_lit}/{unit_lit}");
23580                let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
23581                let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
23582                    panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
23583                });
23584                let rl = policy.rate_limit.expect("rate_limit must be Some");
23585                assert_eq!(
23586                    rl.rate,
23587                    rate_lit.parse::<u32>().unwrap(),
23588                    "rate mismatch for {lit:?}"
23589                );
23590            }
23591        }
23592    }
23593
23594    #[test]
23595    fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
23596        // The structural property the gate enforces: serialize ∘
23597        // deserialize is the identity on every canonical author shape.
23598        // Peer of `parse_byte_size`'s and `parse_duration`'s
23599        // `_round_trips_through_render_for_every_canonical_form` tests
23600        // on the rate-limit axis. Before the gate, `"+100/s"` violated
23601        // this (`parse` → `RateLimit { 100, 1s }` → `render` →
23602        // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
23603        for rate in [1u32, 100, 5000, 1_000_000] {
23604            for (window, unit) in [
23605                (Duration::from_secs(1), "s"),
23606                (Duration::from_secs(60), "m"),
23607                (Duration::from_secs(3600), "h"),
23608            ] {
23609                let policy = MeshPolicy {
23610                    rate_limit: Some(RateLimit { rate, window }),
23611                    ..Default::default()
23612                };
23613                let json = serde_json::to_string(&policy).unwrap();
23614                let expected = format!("\"{rate}/{unit}\"");
23615                assert!(
23616                    json.contains(&expected),
23617                    "expected {expected:?} in {json:?}"
23618                );
23619                let back: MeshPolicy = serde_json::from_str(&json).unwrap();
23620                assert_eq!(
23621                    back.rate_limit, policy.rate_limit,
23622                    "round-trip for {json:?}"
23623                );
23624            }
23625        }
23626    }
23627
23628    // ── self-membership cross-slot gate ──────────────────────────────
23629
23630    #[test]
23631    fn validate_no_self_membership_rejects_self_named_membro() {
23632        // An Aplicacao whose `:membros` lists its own `:nome` is a
23633        // one-node lacre-closure recursion — rejected, naming the parent.
23634        let membros = vec![
23635            membro("catalog", "^0.1"),
23636            membro("checkout", "^0.1"),
23637            membro("cart", "^0.1"),
23638        ];
23639        let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
23640        assert!(
23641            matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
23642            "got {err:?}"
23643        );
23644    }
23645
23646    #[test]
23647    fn validate_no_self_membership_accepts_distinct_membros() {
23648        // Positive control: distinct member names (including a member
23649        // that is itself an Aplicacao — recursive composition is valid,
23650        // MESH-COMPOSITION §V) pass the gate.
23651        let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
23652        validate_no_self_membership(&membros, "checkout").unwrap();
23653    }
23654
23655    #[test]
23656    fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
23657        // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
23658        // `NoMembros` arm (the more-fundamental "graph must have nodes"
23659        // gate), not by this cross-slot self-edge gate. Keeping the
23660        // self-membership predicate vacuously-ok on the empty input
23661        // matches its supervisor-axis peer
23662        // (`validate_no_self_supervision_empty_children_is_ok`) and
23663        // makes the gate composable from any future call site (an M4
23664        // CR materializer's per-membros validator) without re-checking
23665        // emptiness.
23666        validate_no_self_membership(&[], "checkout").unwrap();
23667    }
23668
23669    #[test]
23670    fn validate_no_self_membership_diagnostic_names_offending_caixa() {
23671        // Pinning the Display: the self-membership diagnostic must name
23672        // the offending caixa verbatim + the "lists itself" framing the
23673        // author can grep for, so the cluster-far failure surfaces at
23674        // build time with one-line remediation. Same diagnostic shape
23675        // as the supervisor-axis `ChildSupervisesSelf` peer.
23676        let membros = vec![membro("orquestra", "^0.1")];
23677        let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
23678        let msg = err.to_string();
23679        assert!(
23680            msg.contains("orquestra"),
23681            "diagnostic must name the offending caixa nome (got: {msg:?})"
23682        );
23683        assert!(
23684            msg.contains("lists itself"),
23685            "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
23686        );
23687    }
23688
23689    #[test]
23690    fn default_servico_port_constant_pins_canonical_8080_literal() {
23691        // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
23692        // at the verbatim `8080` literal both consumers (the
23693        // `Entrada::port` serde default via [`default_port`] and the
23694        // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
23695        // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
23696        // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
23697        // discipline (a085b26) on the per-renderer canonical-K8s-axis
23698        // string-constant axis: a future refactor that drifts the
23699        // constant out from under either consumer surfaces here ahead
23700        // of every per-renderer's first emission. The literal value
23701        // matches the well-known HTTP-alt port the `pleme-computeunit`
23702        // library chart already emits as its `trigger.service.port`
23703        // default — by construction the same value the substrate
23704        // assumes about every Servico's in-cluster L4 listener.
23705        assert_eq!(
23706            DEFAULT_SERVICO_PORT, 8080,
23707            "canonical Servico port literal must remain `8080` verbatim — \
23708             this is the value both the `Entrada::port` serde default and the \
23709             caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
23710        );
23711    }
23712
23713    #[test]
23714    fn default_port_helper_returns_canonical_servico_port_constant() {
23715        // The bridge-arm — pins that the [`default_port`] helper
23716        // [`Entrada::port`]'s `#[serde(default = "default_port")]`
23717        // attribute hooks routes through the lifted
23718        // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
23719        // literal. A future refactor that re-introduces the `8080`
23720        // literal at the helper's return site (silently re-opening
23721        // the drift footgun this lift closed) surfaces here ahead of
23722        // every author-side `(:entrada (:host … :para …))` slot
23723        // without an explicit `:port`. Peer with the
23724        // `default_namespace_re_export_points_at_caixa_core_canonical`
23725        // pin on the caixa-mesh-side re-export axis.
23726        assert_eq!(
23727            default_port(),
23728            DEFAULT_SERVICO_PORT,
23729            "the serde-default helper must route through the lifted constant"
23730        );
23731    }
23732
23733    #[test]
23734    fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
23735        // The end-to-end pin — an author-surface `(:entrada (:host …
23736        // :para …))` without an explicit `:port` slot deserializes to
23737        // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
23738        // verbatim. Routes the canonical lifted constant through both
23739        // the serde-default machinery (the `#[serde(default =
23740        // "default_port")]` attribute) and the typed-value-shape
23741        // contract (the resulting [`Entrada::port`] value). A future
23742        // refactor that drifts either axis — replacing the serde
23743        // hook's helper, changing the typed slot's wire shape — would
23744        // surface here before any per-renderer's CNP / Gateway /
23745        // HTTPRoute emission consumed the drifted default.
23746        let entrada: Entrada =
23747            serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
23748        assert_eq!(
23749            entrada.port, DEFAULT_SERVICO_PORT,
23750            "the serde default must materialize as the lifted canonical Servico port"
23751        );
23752    }
23753
23754    #[test]
23755    fn servico_port_min_pins_canonical_accept_set_floor() {
23756        // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
23757        // verbatim `1` literal every typed `:entrada :port` acceptance
23758        // gate keys off. Peer with the
23759        // [`default_servico_port_constant_pins_canonical_8080_literal`]
23760        // discipline on the canonical-Servico-port-constant axis: a
23761        // future refactor that drifts the accept-set floor out from
23762        // under the sole consumer at [`AplicacaoSpec::validate`]'s
23763        // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
23764        // every per-`:entrada` `EntradaPortZero` diagnostic. The
23765        // literal value matches the IANA-registered TCP/UDP port
23766        // space floor (`1..=65535` — port `0` is the "any ephemeral"
23767        // sentinel, not a well-defined destination the substrate's
23768        // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
23769        // axis can honor).
23770        assert_eq!(
23771            SERVICO_PORT_MIN, 1,
23772            "canonical Servico port accept-set floor must remain `1` verbatim — \
23773             this is the value the `AplicacaoSpec::validate` gate at \
23774             `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
23775        );
23776    }
23777
23778    #[test]
23779    fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
23780        // The cross-const invariant pin — the substrate's canonical
23781        // default port must satisfy its own accept-set floor by
23782        // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
23783        // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
23784        // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
23785        // override the operator pins through a future
23786        // `:placement :default-port` slot that lands out-of-range, a
23787        // per-edition Servico-port migration that lifted the floor
23788        // above the previous default without coordinating the pair —
23789        // would silently invalidate the serde-default emission at
23790        // every author-side `(:entrada (:host … :para …))` slot
23791        // without an explicit `:port`: the default port would fall
23792        // below the accept-set floor, the `AplicacaoSpec::validate`
23793        // gate would reject every default-carrying Aplicacao as
23794        // `EntradaPortZero`, and the substrate's typed
23795        // `(defcaixa … :kind Aplicacao)` surface would fail validate
23796        // on every Aplicacao whose author omitted `:entrada :port`
23797        // for the substrate's chosen default — a class of authoring-
23798        // surface footguns the compile-time pin structurally closes.
23799        // Peer with the
23800        // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
23801        // (27f9b34) cross-const invariant pin discipline on the peer
23802        // canonical-Helm-per-values-block child-chart-enablement-toggle
23803        // axis pair.
23804        const {
23805            assert!(
23806                SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
23807                "the substrate's canonical default port DEFAULT_SERVICO_PORT \
23808                 must satisfy its own accept-set floor SERVICO_PORT_MIN — \
23809                 every default-carrying `(:entrada (:host … :para …))` slot \
23810                 without an explicit `:port` inherits `DEFAULT_SERVICO_PORT` \
23811                 through the serde default hook and must pass the \
23812                 `AplicacaoSpec::validate` floor gate by construction",
23813            );
23814        }
23815    }
23816
23817    #[test]
23818    fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
23819        // The gate-site pin — asserts the `AplicacaoSpec::validate`
23820        // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
23821        // `EntradaPortZero` diagnostic on the below-floor input
23822        // `port: 0` (the only below-floor value the `u16` field can
23823        // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
23824        // is the singleton `{0}`). A future refactor that drifts the
23825        // gate off the lifted const (silently re-introducing an
23826        // inline `if e.port == 0` byte-check) surfaces here — the
23827        // pin cannot distinguish `< 1` from `== 0` on the current
23828        // floor, but it *does* pin that the diagnostic fires on `0`
23829        // through whichever gate is wired, so any future accept-set
23830        // floor migration (a hypothetical unprivileged-only
23831        // migration lifting `SERVICO_PORT_MIN` to `1024`) must
23832        // update this test alongside the const declaration —
23833        // structurally guaranteeing the gate + accept-set + pin
23834        // trio move together. Peer with the
23835        // [`rejects_zero_entrada_port`] behavioral pin on the same
23836        // per-`:entrada :port` axis — that pin asserts the pre-lift
23837        // behavioral contract (`port: 0` → `EntradaPortZero`); this
23838        // pin adds the structural link to the lifted floor const.
23839        assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
23840        let mut s = three_member_spec();
23841        s.entrada.as_mut().unwrap().port = 0;
23842        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
23843    }
23844
23845    // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
23846
23847    #[test]
23848    fn membro_serde_keys_match_lifted_membro_key_consts() {
23849        // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
23850        // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
23851        // name the exact camelCase JSON keys the
23852        // `#[serde(rename_all = "camelCase")]` attribute on
23853        // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
23854        // that each canonical byte-sequence appears verbatim in the
23855        // JSON — a future accidental `rename_all = "snake_case"` /
23856        // `"kebab-case"` / verbatim-field-name flip at the derive
23857        // attribute (any of which would silently break every downstream
23858        // JSON consumer that reaches for one of the two consts via
23859        // `Value::get(...)`) surfaces here as a build-time test failure
23860        // at `aplicacao.rs`, not as an apply-time
23861        // `.get(<stale-canonical-const>)` returning `None` far from the
23862        // derive-attr drift's commit. Peer with the sibling
23863        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
23864        // (40cc4e5) pin on the M2 supervision-tree top-level axis —
23865        // same discipline the SupervisorSpec top-level lift established,
23866        // extended here to the M3 [`Membro`] per-`:membros` axis.
23867        let m = Membro {
23868            caixa: "catalog".into(),
23869            versao: "^0.1".into(),
23870        };
23871        let json = serde_json::to_string(&m).unwrap();
23872        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
23873            let quoted = format!("\"{key}\"");
23874            assert!(
23875                json.contains(&quoted),
23876                "serialized Membro must carry the lifted MEMBRO_KEY_* \
23877                 byte-sequence {quoted} verbatim in the JSON emission \
23878                 (got: {json})",
23879            );
23880        }
23881    }
23882
23883    #[test]
23884    fn membro_key_consts_are_pairwise_distinct() {
23885        // Cross-axis drift-detection pin: a future collapse of the two
23886        // canonical [`Membro`] per-entry byte-strings onto the same
23887        // value (e.g. an accidental copy-paste flip of
23888        // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
23889        // silently reroute every downstream probe on one axis onto the
23890        // sibling axis's overlay entry and pass every propagation-probe
23891        // test that expected only the stale axis's value. Peer of the
23892        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
23893        // (40cc4e5).
23894        let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
23895        for (i, a) in all.iter().enumerate() {
23896            for b in all.iter().skip(i + 1) {
23897                assert_ne!(
23898                    a, b,
23899                    "MEMBRO_KEY_* consts must be pairwise-distinct \
23900                     canonical byte-sequences — got `{a}` == `{b}`",
23901                );
23902            }
23903        }
23904    }
23905
23906    // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
23907    //    URL-path fallback resolver every HTTPRoute-aware renderer
23908    //    reaching for a per-rule path-list resolution routes through.
23909    //    The four pin tests below fix the four-way accept-set the
23910    //    resolver must always honor: (:paths-non-empty-verbatim,
23911    //    :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
23912    //    :paths-preserves-order-across-multiple-entries) — drift on any
23913    //    arm surfaces at caixa-core build time rather than at cluster-
23914    //    apply time. Peer discipline with `MeshPolicy::is_empty` on the
23915    //    sibling `:politicas` typed-primitive dispatch axis.
23916
23917    fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
23918        Entrada {
23919            host: "example.com".into(),
23920            para: "cart".into(),
23921            paths: paths.into_iter().map(String::from).collect(),
23922            port: DEFAULT_SERVICO_PORT,
23923        }
23924    }
23925
23926    #[test]
23927    fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
23928        // The typed `:entrada :paths` slot carries an author-declared
23929        // list — the resolver returns each entry verbatim, no
23930        // catch-all substitution. The canonical "author declared
23931        // paths, honor them verbatim" arm of the path-list dispatch.
23932        let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
23933        assert_eq!(
23934            e.resolved_paths(),
23935            vec!["/api/cart", "/api/products"],
23936            "resolved_paths must return each `:entrada :paths` entry \
23937             verbatim when the typed slot is non-empty (got {:?})",
23938            e.resolved_paths(),
23939        );
23940    }
23941
23942    #[test]
23943    fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
23944        // Empty `:entrada :paths` slot — the resolver substitutes the
23945        // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
23946        // catch-all fallback verbatim. Pins the empty-arm of the
23947        // resolver's four-way accept-set against a future silent
23948        // detour that returned an empty Vec (which would emit an
23949        // HTTPRoute with zero rules — silently dropping every
23950        // external `:entrada` flow at admission time), routed to a
23951        // different fallback shape, or dropped the catch-all
23952        // altogether.
23953        let e = entrada_with_paths(vec![]);
23954        assert_eq!(
23955            e.resolved_paths(),
23956            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
23957            "resolved_paths on empty `:entrada :paths` must fall back \
23958             to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
23959             all — got {:?}",
23960            e.resolved_paths(),
23961        );
23962    }
23963
23964    #[test]
23965    fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
23966        // Single-entry `:entrada :paths` — the resolver returns the
23967        // single declared path verbatim, NOT the catch-all fallback
23968        // (author declared a path, honor it — the empty-arm and the
23969        // len-1 arm are semantically distinct axes of the resolver's
23970        // accept-set). Pins that the resolver treats "author declared
23971        // one path" as authored input, not as the empty case.
23972        let e = entrada_with_paths(vec!["/api/only"]);
23973        assert_eq!(
23974            e.resolved_paths(),
23975            vec!["/api/only"],
23976            "resolved_paths on single-entry `:entrada :paths` must \
23977             return the declared path verbatim, NOT the catch-all \
23978             fallback (got {:?})",
23979            e.resolved_paths(),
23980        );
23981    }
23982
23983    #[test]
23984    fn resolved_paths_preserves_author_declared_order() {
23985        // The `:entrada :paths` list is author-ordered — the resolver
23986        // preserves the author's declaration order verbatim, since
23987        // per-rule dispatch order at the K8s Gateway API HTTPRoute
23988        // consumer is significant (first-match-wins under the
23989        // path-prefix matcher). Pins against a future silent
23990        // re-sort / dedup / normalize detour that reordered author
23991        // input.
23992        let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
23993        assert_eq!(
23994            e.resolved_paths(),
23995            vec!["/z/last", "/a/first", "/m/mid"],
23996            "resolved_paths must preserve author-declared `:entrada \
23997             :paths` order verbatim — got {:?}",
23998            e.resolved_paths(),
23999        );
24000    }
24001
24002    // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
24003    //    slot `&[String]` slice accessor every per-`:entrada` consumer
24004    //    that must see the author's declaration verbatim (not the
24005    //    fallback-applied projection the sibling `resolved_paths`
24006    //    returns) routes through. The three pin tests below fix the
24007    //    accept-set the accessor must honor: (:non-empty-byte-equal,
24008    //    :empty-projects-empty-slice, :preserves-author-declared-order)
24009    //    — drift on any arm surfaces at caixa-core build time rather
24010    //    than at cluster-apply time. Peer discipline with the sibling
24011    //    [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
24012    //    peer M3 mesh-slot `Vec<String>`-carry axis.
24013
24014    #[test]
24015    fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
24016        // Byte-equal pin: [`Entrada::paths`] must project the raw
24017        // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
24018        // slice borrowed from the typed slot's own [`Vec<String>`]
24019        // storage — no re-ordering, no dedup, no per-entry normalization,
24020        // no fallback substitution (the fallback-applying projection is
24021        // the sibling [`Entrada::resolved_paths`] resolver). Pins against
24022        // a future silent detour that re-normalized the list, dropped
24023        // duplicates the [`AplicacaoSpec::validate`]
24024        // `EntradaPathDuplicate` refusal already rejects at build time,
24025        // or (most severe) accidentally routed through the fallback-
24026        // applying sibling and returned the substrate catch-all when
24027        // the author declared an empty list — collapsing the raw-slot
24028        // and fallback-applied axes into one and breaking the
24029        // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
24030        //
24031        // Peer of the sibling
24032        // [`Placement::clusters`]-shape byte-equal pin
24033        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
24034        // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
24035        let fixtures: Vec<Vec<String>> = vec![
24036            Vec::new(),
24037            vec!["/api/cart".into()],
24038            vec!["/api/cart".into(), "/api/products".into()],
24039            vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
24040        ];
24041        for paths in fixtures {
24042            let e = Entrada {
24043                host: "example.com".into(),
24044                para: "cart".into(),
24045                paths: paths.clone(),
24046                port: DEFAULT_SERVICO_PORT,
24047            };
24048            assert_eq!(
24049                e.paths(),
24050                paths.as_slice(),
24051                "Entrada::paths must return :entrada :paths verbatim \
24052                 (got {:?}, expected {:?})",
24053                e.paths(),
24054                paths.as_slice(),
24055            );
24056            assert_eq!(
24057                e.paths(),
24058                e.paths.as_slice(),
24059                "Entrada::paths accessor and .paths.as_slice() field \
24060                 access must byte-equal — the accessor is the substrate-\
24061                 primitive typed dispatch every downstream per-`:entrada` \
24062                 raw-slot path-list consumer must route through",
24063            );
24064            assert_eq!(
24065                e.paths().len(),
24066                e.paths.len(),
24067                "Entrada::paths().len() must byte-equal self.paths.len() \
24068                 — a length drift would silently split the paired \
24069                 pre-flight cascade-head `.is_empty()` probe input in \
24070                 the sibling [`Entrada::resolved_paths`] resolver from \
24071                 the per-entry validate loop's traversal input in \
24072                 [`AplicacaoSpec::validate`]",
24073            );
24074        }
24075    }
24076
24077    #[test]
24078    fn resolved_paths_reads_through_lifted_paths_accessor() {
24079        // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
24080        // pre-flight `.paths().is_empty()` cascade-head probe (which
24081        // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
24082        // catch-all fallback arm when the accessor projects the empty
24083        // slice) and the per-entry `.paths().iter().map(String::as_str)`
24084        // projection (which must reach every entry in the same order
24085        // the accessor projects, so the sibling
24086        // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
24087        // per-entry projection stay in lockstep by construction) must
24088        // both key off the lifted accessor. Pins the two-site coherence
24089        // by exercising each production consumer end-to-end: (1) the
24090        // catch-all-fallback arm under the empty slice, (2) the
24091        // author-declared-verbatim arm under a two-entry cohort whose
24092        // per-entry projection must byte-equal the input's per-entry
24093        // author-declared paths in the author's declared order.
24094        //
24095        // Peer of the sibling M3
24096        // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
24097        // `validate_placement_reads_through_lifted_clusters_accessor`
24098        // on the sibling `Placement::clusters` reader-site convergence.
24099        let empty = entrada_with_paths(vec![]);
24100        assert_eq!(
24101            empty.resolved_paths(),
24102            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
24103            "resolved_paths on empty :entrada :paths must trip the \
24104             lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
24105             catch-all fallback — routing through the lifted paths() \
24106             accessor must not silently drop the fallback arm",
24107        );
24108
24109        let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
24110        assert_eq!(
24111            declared.resolved_paths(),
24112            vec!["/api/cart", "/api/products"],
24113            "resolved_paths on non-empty :entrada :paths must return each \
24114             entry verbatim in the author's declared order — routing \
24115             through the lifted paths() accessor must not silently \
24116             reorder or drop entries",
24117        );
24118        // Byte-equal pin against the raw-slot accessor to keep the
24119        // fallback-applying resolver's per-entry projection input in
24120        // lockstep with the raw-slot accessor's projection.
24121        let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
24122        assert_eq!(
24123            declared.resolved_paths(),
24124            raw_projected,
24125            "resolved_paths non-empty projection must byte-equal the \
24126             lifted paths() accessor's per-entry String::as_str projection \
24127             — the two projections share the same input slice by \
24128             construction, so any drift here would surface a silent \
24129             re-ordering / dedup / normalization detour in the resolver",
24130        );
24131    }
24132
24133    #[test]
24134    fn validate_reads_through_lifted_entrada_paths_accessor() {
24135        // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
24136        // per-entry value-shape gate's `for p in e.paths()` traversal
24137        // (which must reach every entry in the same order the accessor
24138        // projects, so both the per-entry `EntradaPathEmpty` /
24139        // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
24140        // the duplicate-detection HashSet insert that trips
24141        // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
24142        // projection) must route through the lifted accessor. Pins the
24143        // coherence by exercising each production consumer end-to-end:
24144        // (1) the `EntradaPathEmpty` refusal fires on the second entry
24145        // of a two-entry cohort whose head is valid but tail is empty
24146        // (which requires the loop to reach the second entry through
24147        // the accessor), and (2) the `EntradaPathDuplicate` refusal
24148        // fires on the second entry of a two-entry cohort that shares
24149        // a path (which requires the loop to reach both entries — a
24150        // first-entry-only projection would silently pass since the
24151        // dedup HashSet has room for the first insert).
24152        //
24153        // Peer of the sibling
24154        // `validate_placement_reads_through_lifted_clusters_accessor`
24155        // on the sibling `Placement::clusters` reader-site convergence.
24156        let base = crate::AplicacaoSpec {
24157            membros: vec![crate::Membro {
24158                caixa: "cart".into(),
24159                versao: "^0.1".into(),
24160            }],
24161            contratos: Vec::new(),
24162            politicas: crate::MeshPolicy::default(),
24163            placement: crate::Placement {
24164                estrategia: crate::PlacementStrategy::SingleNode,
24165                clusters: vec!["rio".into()],
24166                shard_key: None,
24167                affinity: None,
24168            },
24169            entrada: Some(Entrada {
24170                host: "example.com".into(),
24171                para: "cart".into(),
24172                paths: vec!["/api/cart".into(), String::new()],
24173                port: DEFAULT_SERVICO_PORT,
24174            }),
24175        };
24176        assert_eq!(
24177            base.validate(),
24178            Err(crate::AplicacaoError::EntradaPathEmpty),
24179            "validate must trip EntradaPathEmpty on the second entry of \
24180             a two-entry cohort — routing through the lifted paths() \
24181             accessor must not silently short-circuit the loop at the \
24182             valid head entry",
24183        );
24184
24185        let mut dup = base;
24186        dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
24187        assert_eq!(
24188            dup.validate(),
24189            Err(crate::AplicacaoError::EntradaPathDuplicate {
24190                path: "/api/cart".into(),
24191            }),
24192            "validate must trip EntradaPathDuplicate on the second entry \
24193             of a two-entry cohort that shares a path — routing through \
24194             the lifted paths() accessor must not silently short-circuit \
24195             the dedup HashSet insert at the first entry",
24196        );
24197    }
24198
24199    // ── Entrada::hostname / Entrada::hostnames — the substrate-
24200    //    canonical per-`:entrada` DNS-hostname resolver pair every
24201    //    Gateway-API-aware renderer reaching for a per-listener
24202    //    singular `hostname:` filter (Gateway) or a per-route plural
24203    //    `spec.hostnames[]` filter list (HTTPRoute) routes through.
24204    //    The three pin tests below fix the two-way accept-set the pair
24205    //    must always honor: (:singular-byte-equal-to-host,
24206    //    :plural-is-singleton-of-singular, :plural-len-is-one) — drift
24207    //    on any arm surfaces at caixa-core build time rather than at
24208    //    cluster-apply time when the API server refuses the HTTPRoute
24209    //    for non-intersecting hostname filters. Peer discipline with
24210    //    the sibling `resolved_paths` accept-set pin block above on the
24211    //    per-`:entrada` path-list resolver axis.
24212
24213    fn entrada_with_host(host: &str) -> Entrada {
24214        Entrada {
24215            host: host.into(),
24216            para: "cart".into(),
24217            paths: Vec::new(),
24218            port: DEFAULT_SERVICO_PORT,
24219        }
24220    }
24221
24222    #[test]
24223    fn hostname_returns_entrada_host_byte_equal() {
24224        // The canonical singular-axis pin: [`Entrada::hostname`] must
24225        // return the `:entrada :host` field byte-for-byte, borrowed
24226        // from the typed slot's own [`String`] storage. Pins against a
24227        // future silent detour that re-normalized the host (an
24228        // accidental `.to_lowercase()` — validate_entrada_host already
24229        // enforces lowercase, so any re-normalization is redundant + a
24230        // drift surface between the validator and the accessor), a
24231        // trailing-`.` fully-qualified DNS shape substitution, or a
24232        // Punycode round-trip that lowered a Unicode host through IDNA.
24233        let e = entrada_with_host("checkout.quero.cloud");
24234        assert_eq!(
24235            e.hostname(),
24236            "checkout.quero.cloud",
24237            "Entrada::hostname must return :entrada :host verbatim \
24238             (got {:?})",
24239            e.hostname(),
24240        );
24241        assert_eq!(
24242            e.hostname(),
24243            e.host.as_str(),
24244            "Entrada::hostname must byte-equal the .host field access",
24245        );
24246    }
24247
24248    #[test]
24249    fn hostnames_returns_singleton_of_hostname_accessor() {
24250        // The pair-invariant pin: [`Entrada::hostnames`] must always
24251        // return exactly `vec![hostname()]` — the singleton list whose
24252        // sole entry is the substrate's canonical per-`:entrada`
24253        // singular hostname. Pins the two-consumer coherence axis: the
24254        // Gateway listener's singular `hostname:` filter and the
24255        // HTTPRoute's plural `spec.hostnames[]` filter list must
24256        // agree, else the Gateway API v1.x conformance layer rejects
24257        // the HTTPRoute at attach time with
24258        // `Accepted:False/NoMatchingParent` (the parent Gateway's
24259        // listener hostname doesn't intersect the route's hostname
24260        // filter list) — a divergence whose apply-time symptom is far
24261        // from any single-site commit and never surfaces in the
24262        // emitted YAML. Pinning the pair-invariant here makes any
24263        // future accidental split (an accidental `.to_string() + "."`
24264        // trailing-`.` on the plural side that didn't land on the
24265        // singular side, an accidental prefix stripping on one axis,
24266        // an accidental wildcard prepend the SNI fan-out overlay
24267        // authors on the plural side without a paired singular
24268        // migration) trip at caixa-core build time.
24269        let e = entrada_with_host("checkout.quero.cloud");
24270        assert_eq!(
24271            e.hostnames(),
24272            vec![e.hostname()],
24273            "Entrada::hostnames must return `vec![hostname()]` under \
24274             the pair-invariant — got {:?} vs. singleton {:?}",
24275            e.hostnames(),
24276            vec![e.hostname()],
24277        );
24278    }
24279
24280    #[test]
24281    fn hostnames_is_singleton_under_single_host_author_surface() {
24282        // The singleton-shape pin: under today's single-hostname-per-
24283        // `:entrada` author surface (the `:host` slot is a single
24284        // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
24285        // must always return a list of length exactly one. Pins
24286        // against a future silent detour that returned an empty list
24287        // (which would emit an HTTPRoute with `spec.hostnames: []` —
24288        // matching every incoming Host header regardless of the
24289        // Aplicacao's declared ingress apex, silently over-matching
24290        // every foreign VirtualHost the parent Gateway also fronts) or
24291        // a duplicated entry (which the Gateway API v1.x parser
24292        // accepts as a `[]-length-2 list of equal hostnames]` but
24293        // whose semantics differ from the intended singleton). The
24294        // author-surface extension point ("a future `:entrada
24295        // :alt-hosts` list overlay" the docstring names) is the sole
24296        // future axis that flips this pin — that migration will re-
24297        // author this test to pin the new plural cardinality.
24298        let e = entrada_with_host("checkout.quero.cloud");
24299        assert_eq!(
24300            e.hostnames().len(),
24301            1,
24302            "Entrada::hostnames must be a singleton under today's \
24303             single-hostname-per-`:entrada` author surface — got \
24304             length {}: {:?}",
24305            e.hostnames().len(),
24306            e.hostnames(),
24307        );
24308    }
24309
24310    // ── Entrada::destination — the substrate-canonical per-`:entrada`
24311    //    destination-Servico scalar accessor every Gateway-API
24312    //    HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
24313    //    discriminator arg (HTTPRoute name composer) or a per-rule
24314    //    `backendRefs[0].name` axis routes through. The two pin tests
24315    //    below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
24316    //    either arm surfaces at caixa-core build time rather than at
24317    //    cluster-apply time when an HTTPRoute's `metadata.name` and
24318    //    `backendRefs[]` silently disagree on which destination Servico
24319    //    the ingress fronts. Peer discipline with the sibling
24320    //    `resolved_paths` + `hostname` + `hostnames` accept-set pin
24321    //    blocks above on the per-`:entrada` path-list / DNS-hostname
24322    //    resolver axes.
24323
24324    #[test]
24325    fn destination_returns_entrada_para_byte_equal() {
24326        // The canonical destination-scalar pin: [`Entrada::destination`]
24327        // must return the `:entrada :para` field byte-for-byte, borrowed
24328        // from the typed slot's own [`String`] storage. Pins against a
24329        // future silent detour that re-normalized the destination (an
24330        // accidental `.to_lowercase()` — the destination Servico is
24331        // already validated as a DNS-1123 label upstream, so any
24332        // re-normalization is redundant + a drift surface between the
24333        // validator and the accessor), a namespace-prefix rewrite (an
24334        // accidental `format!("{namespace}/{para}")` per-CR fully-
24335        // qualified rewrite that didn't land on the peer axis), or a
24336        // per-cluster suffix stamp the operator authors on one
24337        // consumer without the other.
24338        for para in ["cart", "checkout", "catalog", "orders-v2"] {
24339            let e = Entrada {
24340                host: "checkout.quero.cloud".into(),
24341                para: para.into(),
24342                paths: Vec::new(),
24343                port: DEFAULT_SERVICO_PORT,
24344            };
24345            assert_eq!(
24346                e.destination(),
24347                para,
24348                "Entrada::destination must return :entrada :para verbatim \
24349                 (got {:?}, expected {para:?})",
24350                e.destination(),
24351            );
24352            assert_eq!(
24353                e.destination(),
24354                e.para.as_str(),
24355                "Entrada::destination must byte-equal the .para field access",
24356            );
24357        }
24358    }
24359
24360    #[test]
24361    fn destination_borrows_from_entrada_para_storage() {
24362        // The borrow-not-copy pin: [`Entrada::destination`] must
24363        // return a `&str` slice that borrows from the typed slot's
24364        // own [`String`] storage — same-address invariant with
24365        // `entrada.para.as_str()`. Pins against a future silent detour
24366        // that allocated a fresh `String` (`self.para.clone()` in the
24367        // body would type-check but silently drop the borrow, and
24368        // every downstream consumer that assumed the returned slice
24369        // outlives `&self` would break on a stale-reference use-after-
24370        // free). Peer with the sibling `hostname_returns_entrada_
24371        // host_byte_equal` on the singular-DNS-hostname axis.
24372        let e = entrada_with_host("checkout.quero.cloud");
24373        let dest = e.destination();
24374        let para_slice = e.para.as_str();
24375        assert_eq!(
24376            dest.as_ptr(),
24377            para_slice.as_ptr(),
24378            "Entrada::destination must borrow from the .para String's \
24379             backing storage — a fresh allocation here means the \
24380             accessor no longer names the substrate-primitive typed \
24381             dispatch and every downstream consumer would silently \
24382             carry a detached copy",
24383        );
24384        assert_eq!(
24385            dest.len(),
24386            para_slice.len(),
24387            "Entrada::destination and .para.as_str() must byte-equal in \
24388             length as well as in address",
24389        );
24390    }
24391
24392    #[test]
24393    fn port_returns_entrada_port_verbatim_across_permutations() {
24394        // The canonical L4-port-scalar pin: [`Entrada::port`] must
24395        // return the `:entrada :port` field verbatim as a `u16` across
24396        // every author-declared value in the validated accept-set
24397        // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
24398        // silent detour that clamped the port (an accidental
24399        // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
24400        // land on the peer [`AplicacaoSpec::port_for_destination`]
24401        // resolver), rewrote it through a per-cluster port-remap table
24402        // the operator authors on one consumer without the other, or
24403        // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
24404        // serde-default value (which would silently collapse the
24405        // distinction between "author explicitly declared `:port 8080`"
24406        // and "author omitted the slot and inherited the default" the
24407        // future per-cluster override slot depends on). Peer with the
24408        // sibling `destination_returns_entrada_para_byte_equal` +
24409        // `hostname_returns_entrada_host_byte_equal` pins on the
24410        // per-`:entrada` `&str` scalar axes.
24411        for port in [
24412            SERVICO_PORT_MIN,
24413            DEFAULT_SERVICO_PORT,
24414            8443u16,
24415            9090u16,
24416            u16::MAX,
24417        ] {
24418            let e = Entrada {
24419                host: "checkout.quero.cloud".into(),
24420                para: "cart".into(),
24421                paths: Vec::new(),
24422                port,
24423            };
24424            assert_eq!(
24425                e.port(),
24426                port,
24427                "Entrada::port must return :entrada :port verbatim \
24428                 (got {}, expected {port})",
24429                e.port(),
24430            );
24431            assert_eq!(
24432                e.port(),
24433                e.port,
24434                "Entrada::port accessor and .port field access must \
24435                 byte-equal — the accessor is the substrate-primitive \
24436                 typed dispatch every downstream L4-port consumer must \
24437                 route through",
24438            );
24439        }
24440    }
24441
24442    #[test]
24443    fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
24444        // Two-consumer coherence pin: the
24445        // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
24446        // (which reads through [`Entrada::port`] to compare against
24447        // [`SERVICO_PORT_MIN`]) and the
24448        // [`AplicacaoSpec::port_for_destination`] resolver (which reads
24449        // through [`Entrada::port`] to emit the per-destination
24450        // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
24451        // lifted accessor, so any future rebrand on the typed slot's
24452        // reader shape lands at exactly one place. Pins the two-site
24453        // coherence by exercising a below-floor port through validate
24454        // (which must reject) and a validated in-accept-set port through
24455        // port_for_destination (which must emit the same value the
24456        // accessor returns).
24457        let mut spec = three_member_spec();
24458        if let Some(e) = spec.entrada.as_mut() {
24459            e.port = 0;
24460        }
24461        assert_eq!(
24462            spec.validate().unwrap_err(),
24463            AplicacaoError::EntradaPortZero,
24464            "validate must reject `:entrada :port 0` through the lifted \
24465             Entrada::port accessor — port zero lies below \
24466             SERVICO_PORT_MIN and the validator routes through port() \
24467             to name the floor",
24468        );
24469
24470        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
24471            let mut spec = three_member_spec();
24472            if let Some(e) = spec.entrada.as_mut() {
24473                e.port = port;
24474            }
24475            spec.validate().expect(
24476                "entrada with in-accept-set :port must validate — the \
24477                 structural-floor gate reads through Entrada::port",
24478            );
24479            let entrada_ref = spec.entrada().expect(":entrada present");
24480            assert_eq!(
24481                spec.port_for_destination(entrada_ref.destination()),
24482                entrada_ref.port(),
24483                "port_for_destination(entrada.destination()) must equal \
24484                 entrada.port() — the two consumers of the per-:entrada \
24485                 L4-port axis (validator, per-destination resolver) both \
24486                 route through Entrada::port",
24487            );
24488        }
24489    }
24490
24491    #[test]
24492    fn wit_contract_source_returns_de_byte_equal_across_permutations() {
24493        // The canonical caller-Servico-scalar pin: [`WitContract::source`]
24494        // must return the `:contratos :de` field byte-for-byte, borrowed
24495        // from the typed slot's own [`String`] storage. Peer of the
24496        // sibling `destination_returns_entrada_para_byte_equal` pin on
24497        // the per-`:entrada` axis — same "the substrate-primitive
24498        // accessor must byte-equal the raw field access verbatim across
24499        // every author-declared value" discipline extended to the
24500        // per-`:contratos` caller arm. Pins against a future silent
24501        // detour that re-normalized the caller (an accidental
24502        // `.to_lowercase()` — every `:contratos :de` is validated as a
24503        // DNS-1123 label upstream via `validate_contrato_caixa`, so any
24504        // re-normalization is redundant + a drift surface between the
24505        // validator and the accessor), a namespace-prefix rewrite (an
24506        // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
24507        // rewrite that didn't land on the peer axis), or a per-cluster
24508        // suffix stamp the operator authors on one consumer without the
24509        // other.
24510        for de in ["cart", "checkout", "catalog", "orders-v2"] {
24511            let c = WitContract {
24512                de: de.into(),
24513                para: "downstream".into(),
24514                wit: "wasi:http/proxy".into(),
24515                endpoint: Some("/lookup".into()),
24516                subject: None,
24517                slot: None,
24518            };
24519            assert_eq!(
24520                c.source(),
24521                de,
24522                "WitContract::source must return :contratos :de verbatim \
24523                 (got {:?}, expected {de:?})",
24524                c.source(),
24525            );
24526            assert_eq!(
24527                c.source(),
24528                c.de.as_str(),
24529                "WitContract::source must byte-equal the .de field access",
24530            );
24531        }
24532    }
24533
24534    #[test]
24535    fn wit_contract_source_borrows_from_de_storage() {
24536        // The borrow-not-copy pin: [`WitContract::source`] must return a
24537        // `&str` slice that borrows from the typed slot's own [`String`]
24538        // storage — same-address invariant with `c.de.as_str()`. Pins
24539        // against a future silent detour that allocated a fresh `String`
24540        // (`self.de.clone()` in the body would type-check but silently
24541        // drop the borrow, and every downstream consumer that assumed
24542        // the returned slice outlives `&self` would break on a stale-
24543        // reference use-after-free). Peer of the sibling
24544        // `destination_borrows_from_entrada_para_storage` on the
24545        // per-`:entrada` axis.
24546        let c = WitContract {
24547            de: "cart".into(),
24548            para: "catalog".into(),
24549            wit: "wasi:http/proxy".into(),
24550            endpoint: Some("/lookup".into()),
24551            subject: None,
24552            slot: None,
24553        };
24554        let src = c.source();
24555        let de_slice = c.de.as_str();
24556        assert_eq!(
24557            src.as_ptr(),
24558            de_slice.as_ptr(),
24559            "WitContract::source must borrow from the .de String's \
24560             backing storage — a fresh allocation here means the \
24561             accessor no longer names the substrate-primitive typed \
24562             dispatch and every downstream consumer would silently \
24563             carry a detached copy",
24564        );
24565        assert_eq!(
24566            src.len(),
24567            de_slice.len(),
24568            "WitContract::source and .de.as_str() must byte-equal in \
24569             length as well as in address",
24570        );
24571    }
24572
24573    #[test]
24574    fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
24575        // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
24576        // must return the `:contratos :para` field byte-for-byte,
24577        // borrowed from the typed slot's own [`String`] storage. Peer of
24578        // the sibling `destination_returns_entrada_para_byte_equal` on
24579        // the per-`:entrada` axis — both accessors name "the destination-
24580        // Servico byte-string" concept on their respective mesh-slot
24581        // atoms (per-ingress apex vs. per-typed-edge callee) and both
24582        // must project the underlying `.para` field verbatim so every
24583        // downstream renderer that composes them with peer accessors
24584        // (e.g. `spec.port_for_destination(c.destination())` at the CNP
24585        // per-edge L4 port emit site) reads the same byte-string the
24586        // author declared.
24587        for para in ["catalog", "payment", "orders", "inventory-v3"] {
24588            let c = WitContract {
24589                de: "cart".into(),
24590                para: para.into(),
24591                wit: "wasi:http/proxy".into(),
24592                endpoint: Some("/lookup".into()),
24593                subject: None,
24594                slot: None,
24595            };
24596            assert_eq!(
24597                c.destination(),
24598                para,
24599                "WitContract::destination must return :contratos :para \
24600                 verbatim (got {:?}, expected {para:?})",
24601                c.destination(),
24602            );
24603            assert_eq!(
24604                c.destination(),
24605                c.para.as_str(),
24606                "WitContract::destination must byte-equal the .para \
24607                 field access",
24608            );
24609        }
24610    }
24611
24612    #[test]
24613    fn wit_contract_destination_borrows_from_para_storage() {
24614        // The borrow-not-copy pin: [`WitContract::destination`] must
24615        // return a `&str` slice that borrows from the typed slot's own
24616        // [`String`] storage — same-address invariant with
24617        // `c.para.as_str()`. Peer of the sibling
24618        // `destination_borrows_from_entrada_para_storage` on the
24619        // per-`:entrada` axis.
24620        let c = WitContract {
24621            de: "cart".into(),
24622            para: "catalog".into(),
24623            wit: "wasi:http/proxy".into(),
24624            endpoint: Some("/lookup".into()),
24625            subject: None,
24626            slot: None,
24627        };
24628        let dest = c.destination();
24629        let para_slice = c.para.as_str();
24630        assert_eq!(
24631            dest.as_ptr(),
24632            para_slice.as_ptr(),
24633            "WitContract::destination must borrow from the .para \
24634             String's backing storage — a fresh allocation here means \
24635             the accessor no longer names the substrate-primitive typed \
24636             dispatch and every downstream consumer would silently \
24637             carry a detached copy",
24638        );
24639        assert_eq!(
24640            dest.len(),
24641            para_slice.len(),
24642            "WitContract::destination and .para.as_str() must byte-equal \
24643             in length as well as in address",
24644        );
24645    }
24646
24647    #[test]
24648    fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
24649        // The canonical per-`:contratos` WIT-world-reference scalar pin:
24650        // [`WitContract::world_ref`] must return the `:contratos :wit`
24651        // field byte-for-byte, borrowed from the typed slot's own
24652        // [`String`] storage. Sibling of the peer per-`:contratos`
24653        // [`WitContract::source`] / [`WitContract::destination`]
24654        // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
24655        // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
24656        // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
24657        // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
24658        // "the substrate-primitive accessor must byte-equal the raw
24659        // field access verbatim across every author-declared value"
24660        // discipline extended to the per-`:contratos` WIT-world arm.
24661        // Pins against a future silent detour that re-canonicalized the
24662        // WIT world reference (an accidental `.to_lowercase()` pass that
24663        // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
24664        // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
24665        // gate is already lowercase-prefixed so any re-normalization is
24666        // redundant + a drift surface between the validator and the
24667        // accessor), an M4-promotion-shape rewrite that formatted a
24668        // typed WIT-world enum through [`Display`] and silently drifted
24669        // the printer output from the source `caixa.lisp`, or a per-
24670        // cluster WIT-alias rewrite that didn't land on the peer field-
24671        // access sites. Five values sweep the shape-dispatch accept-set
24672        // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
24673        // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
24674        // `wasi:keyvalue/`).
24675        for (wit, endpoint, subject, slot) in [
24676            ("wasi:http/proxy", Some("/lookup"), None, None),
24677            ("http:proxy", Some("/health"), None, None),
24678            ("nats:pub-sub", None, Some("orders.paid"), None),
24679            ("kafka:events", None, Some("checkout-events"), None),
24680            ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
24681        ] {
24682            let c = WitContract {
24683                de: "cart".into(),
24684                para: "downstream".into(),
24685                wit: wit.into(),
24686                endpoint: endpoint.map(str::to_string),
24687                subject: subject.map(str::to_string),
24688                slot: slot.map(str::to_string),
24689            };
24690            assert_eq!(
24691                c.world_ref(),
24692                wit,
24693                "WitContract::world_ref must return :contratos :wit \
24694                 verbatim (got {:?}, expected {wit:?})",
24695                c.world_ref(),
24696            );
24697            assert_eq!(
24698                c.world_ref(),
24699                c.wit.as_str(),
24700                "WitContract::world_ref must byte-equal the .wit field \
24701                 access",
24702            );
24703        }
24704    }
24705
24706    #[test]
24707    fn wit_contract_world_ref_borrows_from_wit_storage() {
24708        // The borrow-not-copy pin: [`WitContract::world_ref`] must
24709        // return a `&str` slice that borrows from the typed slot's own
24710        // [`String`] storage — same-address invariant with
24711        // `c.wit.as_str()`. Pins against a future silent detour that
24712        // allocated a fresh `String` (`self.wit.clone()` in the body
24713        // would type-check but silently drop the borrow, and every
24714        // downstream consumer that assumed the returned slice outlives
24715        // `&self` would break on a stale-reference use-after-free — the
24716        // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
24717        // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
24718        // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
24719        // / [`is_pubsub`][WitContract::is_pubsub] /
24720        // [`is_store`][WitContract::is_store] methods route through —
24721        // each borrow from the WitContract's own storage and each would
24722        // silently misbehave if this accessor produced a detached copy).
24723        // Peer of the sibling per-`:contratos` [`WitContract::source`] /
24724        // [`WitContract::destination`] and per-`:entrada`
24725        // [`Entrada::destination`] / [`Entrada::hostname`] and
24726        // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
24727        // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
24728        let c = WitContract {
24729            de: "cart".into(),
24730            para: "catalog".into(),
24731            wit: "wasi:http/proxy".into(),
24732            endpoint: Some("/lookup".into()),
24733            subject: None,
24734            slot: None,
24735        };
24736        let world = c.world_ref();
24737        let wit_slice = c.wit.as_str();
24738        assert_eq!(
24739            world.as_ptr(),
24740            wit_slice.as_ptr(),
24741            "WitContract::world_ref must borrow from the .wit String's \
24742             backing storage — a fresh allocation here means the \
24743             accessor no longer names the substrate-primitive typed \
24744             dispatch and every downstream consumer would silently carry \
24745             a detached copy",
24746        );
24747        assert_eq!(
24748            world.len(),
24749            wit_slice.len(),
24750            "WitContract::world_ref and .wit.as_str() must byte-equal in \
24751             length as well as in address",
24752        );
24753    }
24754
24755    #[test]
24756    fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
24757        // Sibling-triple invariant pin composing all three per-`:contratos`
24758        // substrate-primitive typed dispatches — [`WitContract::source`]
24759        // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
24760        // [`WitContract::world_ref`] — at the joint
24761        // `(source(), destination(), world_ref())` call shape every
24762        // renderer that fans on per-edge caller-callee-shape identity
24763        // keys off. The invariant, evaluated per-contract:
24764        //
24765        //   (c.source(), c.destination(), c.world_ref())
24766        //   == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
24767        //
24768        // Closes the last unlifted per-`:contratos` scalar axis — every
24769        // downstream consumer that reads the triple now routes through
24770        // exactly three typed dispatches on the substrate primitive,
24771        // not two typed + one open-coded field access. A future refactor
24772        // that silently split any one accessor's projection (an
24773        // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
24774        // canonicalization that didn't reach the peer `source`/
24775        // `destination` arms, an accidental `source()` per-cluster
24776        // caller-alias rewrite that didn't land on the `world_ref` peer)
24777        // surfaces at caixa-core build time. Peer of the sibling per-
24778        // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
24779        // per-`:entrada` `(hostname(), destination())` (6db982c /
24780        // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
24781        // axes, extended to the per-`:contratos` triple.
24782        for (de, para, wit, endpoint, subject, slot) in [
24783            (
24784                "cart",
24785                "catalog",
24786                "wasi:http/proxy",
24787                Some("/lookup"),
24788                None,
24789                None,
24790            ),
24791            (
24792                "checkout",
24793                "orders",
24794                "nats:pub-sub",
24795                None,
24796                Some("orders.paid"),
24797                None,
24798            ),
24799            (
24800                "cart",
24801                "kv",
24802                "wasi:keyvalue/store",
24803                None,
24804                None,
24805                Some("carts/{cart_id}"),
24806            ),
24807            (
24808                "orders-v2",
24809                "inventory-v3",
24810                "http:proxy",
24811                Some("/reserve"),
24812                None,
24813                None,
24814            ),
24815        ] {
24816            let c = WitContract {
24817                de: de.into(),
24818                para: para.into(),
24819                wit: wit.into(),
24820                endpoint: endpoint.map(str::to_string),
24821                subject: subject.map(str::to_string),
24822                slot: slot.map(str::to_string),
24823            };
24824            assert_eq!(
24825                (c.source(), c.destination(), c.world_ref()),
24826                (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
24827                "(WitContract::source, ::destination, ::world_ref) must \
24828                 project (.de, .para, .wit) verbatim across every author-\
24829                 declared triple (got ({:?}, {:?}, {:?}), expected \
24830                 ({de:?}, {para:?}, {wit:?}))",
24831                c.source(),
24832                c.destination(),
24833                c.world_ref(),
24834            );
24835        }
24836    }
24837
24838    #[test]
24839    fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
24840        // The canonical per-`:contratos` owned-form caller-callee-pair
24841        // pin: [`WitContract::edge_pair`] must return the
24842        // `(source(), destination())` tuple in owned form byte-for-byte,
24843        // projected through the lifted [`WitContract::source`] /
24844        // [`WitContract::destination`] scalar accessors. Pins the
24845        // composite-projection invariant on the per-`:contratos`
24846        // mesh-slot atom — every author-declared `(de, para)` pair must
24847        // round-trip verbatim through the substrate primitive's typed
24848        // dispatch, so the nine [`AplicacaoError`] diagnostic-
24849        // construction sites the accessor now feeds
24850        // ([`AplicacaoError::EmptyWit`],
24851        // [`AplicacaoError::ContratoEndpointEmpty`],
24852        // [`AplicacaoError::ContratoEndpointNotAbsolute`],
24853        // [`AplicacaoError::ContratoEndpointInvalid`],
24854        // [`AplicacaoError::ContratoSubjectEmpty`],
24855        // [`AplicacaoError::ContratoSubjectInvalid`],
24856        // [`AplicacaoError::ContratoSlotEmpty`],
24857        // [`AplicacaoError::ContratoSlotInvalid`],
24858        // [`AplicacaoError::ContratoDuplicate`]) all read the same
24859        // `(de, para)` label pair every author sees at the source
24860        // `caixa.lisp`. Pins against a future silent detour that swapped
24861        // the `.0` / `.1` arms (an accidental `(destination(),
24862        // source())` re-order in the body would silently invert every
24863        // downstream diagnostic's `de:` / `para:` label pair, silently
24864        // reversing the direction of every operator-facing typed error
24865        // arrow), a fresh-allocation shape drift (an accidental
24866        // `.to_string()` on one arm but not the other would leave the
24867        // owned/borrowed pair mismatched vs. the sibling `source()` /
24868        // `destination()` returns), or an M4 per-cluster caller/callee-
24869        // alias rewrite that landed on `source()` without reaching
24870        // `destination()` (or vice versa). Peer of the sibling per-
24871        // `:contratos` `(source, destination, world_ref)` triple
24872        // pin above on the mesh-slot-atom scalar-value axes, extended
24873        // to the owned-form pair-projection axis.
24874        for (de, para, wit, endpoint, subject, slot) in [
24875            (
24876                "cart",
24877                "catalog",
24878                "wasi:http/proxy",
24879                Some("/lookup"),
24880                None,
24881                None,
24882            ),
24883            (
24884                "checkout",
24885                "orders",
24886                "nats:pub-sub",
24887                None,
24888                Some("orders.paid"),
24889                None,
24890            ),
24891            (
24892                "cart",
24893                "kv",
24894                "wasi:keyvalue/store",
24895                None,
24896                None,
24897                Some("carts/{cart_id}"),
24898            ),
24899            (
24900                "orders-v2",
24901                "inventory-v3",
24902                "http:proxy",
24903                Some("/reserve"),
24904                None,
24905                None,
24906            ),
24907        ] {
24908            let c = WitContract {
24909                de: de.into(),
24910                para: para.into(),
24911                wit: wit.into(),
24912                endpoint: endpoint.map(str::to_string),
24913                subject: subject.map(str::to_string),
24914                slot: slot.map(str::to_string),
24915            };
24916            assert_eq!(
24917                c.edge_pair(),
24918                (de.to_string(), para.to_string()),
24919                "WitContract::edge_pair must return (:contratos :de, \
24920                 :contratos :para) as an owned tuple verbatim (got {:?}, \
24921                 expected ({de:?}, {para:?}))",
24922                c.edge_pair(),
24923            );
24924        }
24925    }
24926
24927    #[test]
24928    fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
24929        // The composition pin: [`WitContract::edge_pair`] must return
24930        // exactly `(source().to_string(), destination().to_string())` —
24931        // the owned form of the sibling accessor pair — so any future
24932        // refactor that silently re-authored the caller-arm / callee-arm
24933        // projection to bypass the lifted scalar accessors (an accidental
24934        // `(self.de.clone(), self.para.clone())` regression back to the
24935        // raw field-access shape, an M4-typed-caller-enum `Display`
24936        // re-canonicalization on `source()` that didn't reach
24937        // `edge_pair()`, a per-cluster alias rewrite the operator lands
24938        // on `destination()` without reaching this composite projection)
24939        // trips at caixa-core build time. Pins the "typed dispatch
24940        // composes with typed dispatch, not with raw field access"
24941        // discipline every downstream diagnostic-construction site now
24942        // routes through — a `de:` / `para:` label pair whose
24943        // projection silently drifted off the substrate primitive's
24944        // scalar accessors would silently split the diagnostic's self-
24945        // locating signal from the source `caixa.lisp` author's view.
24946        // Peer of the sibling per-`:politicas` `is_empty` /
24947        // `validate_politicas` accessor-routing-pin family on the M3
24948        // mesh-slot family (18575, 18739, 18918, 19140, 19371).
24949        let c = WitContract {
24950            de: "cart".into(),
24951            para: "catalog".into(),
24952            wit: "wasi:http/proxy".into(),
24953            endpoint: Some("/lookup".into()),
24954            subject: None,
24955            slot: None,
24956        };
24957        assert_eq!(
24958            c.edge_pair(),
24959            (c.source().to_string(), c.destination().to_string()),
24960            "WitContract::edge_pair must compose exactly \
24961             (source().to_string(), destination().to_string()) — a \
24962             bypass of either sibling accessor here would silently \
24963             decouple the composite-projection axis from the \
24964             substrate-primitive scalar accessors every downstream \
24965             consumer routes through",
24966        );
24967    }
24968
24969    #[test]
24970    fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
24971     {
24972        // The canonical per-`:contratos` owned-form
24973        // caller-callee-world-ref-triple pin:
24974        // [`WitContract::edge_triple`] must return the
24975        // `(source(), destination(), world_ref())` tuple in owned form
24976        // byte-for-byte, projected through the lifted
24977        // [`WitContract::source`] / [`WitContract::destination`] /
24978        // [`WitContract::world_ref`] scalar accessors. Pins the
24979        // composite-projection invariant on the per-`:contratos`
24980        // mesh-slot atom — every author-declared `(de, para, wit)`
24981        // triple must round-trip verbatim through the substrate
24982        // primitive's typed dispatch, so the nine
24983        // [`AplicacaoError`] diagnostic-construction sites the
24984        // accessor now feeds (the [`WitTarget`]-dispatch's eight
24985        // wrong-target / missing-target / invalid-wit / capability-
24986        // with-payload arms in [`WitContract::target`], plus the
24987        // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
24988        // diagnostic constructor in [`AplicacaoSpec::validate`]) all
24989        // read the same `(de, para, wit)` triple every author sees at
24990        // the source `caixa.lisp`. Pins against a future silent
24991        // detour that swapped any two arms (an accidental `(destination(),
24992        // source(), world_ref())` re-order in the body would silently
24993        // invert every downstream diagnostic's `de:` / `para:` label
24994        // pair, silently reversing the direction of every operator-
24995        // facing typed error arrow), a fresh-allocation shape drift
24996        // (an accidental `.to_string()` skipped on one arm would leave
24997        // the owned/borrowed triple mismatched vs. the sibling
24998        // `source()` / `destination()` / `world_ref()` returns), or an
24999        // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
25000        // canonicalization pass that landed on one accessor without
25001        // reaching the peers. Peer of the sibling per-`:contratos`
25002        // caller-callee-pair
25003        // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
25004        // pin on the mesh-slot-atom composite-projection axis,
25005        // extended to the triple-projection axis.
25006        for (de, para, wit, endpoint, subject, slot) in [
25007            (
25008                "cart",
25009                "catalog",
25010                "wasi:http/proxy",
25011                Some("/lookup"),
25012                None,
25013                None,
25014            ),
25015            (
25016                "checkout",
25017                "orders",
25018                "nats:pub-sub",
25019                None,
25020                Some("orders.paid"),
25021                None,
25022            ),
25023            (
25024                "cart",
25025                "kv",
25026                "wasi:keyvalue/store",
25027                None,
25028                None,
25029                Some("carts/{cart_id}"),
25030            ),
25031            (
25032                "orders-v2",
25033                "inventory-v3",
25034                "http:proxy",
25035                Some("/reserve"),
25036                None,
25037                None,
25038            ),
25039        ] {
25040            let c = WitContract {
25041                de: de.into(),
25042                para: para.into(),
25043                wit: wit.into(),
25044                endpoint: endpoint.map(str::to_string),
25045                subject: subject.map(str::to_string),
25046                slot: slot.map(str::to_string),
25047            };
25048            assert_eq!(
25049                c.edge_triple(),
25050                (de.to_string(), para.to_string(), wit.to_string()),
25051                "WitContract::edge_triple must return (:contratos :de, \
25052                 :contratos :para, :contratos :wit) as an owned triple \
25053                 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
25054                c.edge_triple(),
25055            );
25056        }
25057    }
25058
25059    #[test]
25060    fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
25061        // The composition pin: [`WitContract::edge_triple`] must return
25062        // exactly `(source().to_string(), destination().to_string(),
25063        // world_ref().to_string())` — the owned form of the sibling
25064        // scalar-accessor triple — so any future refactor that silently
25065        // re-authored one arm's projection to bypass the lifted scalar
25066        // accessors (an accidental `(self.de.clone(), self.para.clone(),
25067        // self.wit.clone())` regression back to the raw field-access
25068        // shape the internal `edge` closure and the ContratoDuplicate
25069        // diagnostic both carried before this lift landed, an
25070        // M4-typed-caller-enum `Display` re-canonicalization on
25071        // `source()` that didn't reach `edge_triple()`, a per-cluster
25072        // alias rewrite the operator lands on `destination()` /
25073        // `world_ref()` without reaching this composite projection)
25074        // trips at caixa-core build time. Pins the "typed dispatch
25075        // composes with typed dispatch, not with raw field access"
25076        // discipline every downstream diagnostic-construction site now
25077        // routes through — a `de:` / `para:` / `wit:` triple whose
25078        // projection silently drifted off the substrate primitive's
25079        // scalar accessors would silently split the diagnostic's self-
25080        // locating signal from the source `caixa.lisp` author's view.
25081        // Peer of the sibling per-`:contratos` edge_pair composition-
25082        // pin above on the mesh-slot-atom composite-projection axis.
25083        let c = WitContract {
25084            de: "cart".into(),
25085            para: "catalog".into(),
25086            wit: "wasi:http/proxy".into(),
25087            endpoint: Some("/lookup".into()),
25088            subject: None,
25089            slot: None,
25090        };
25091        assert_eq!(
25092            c.edge_triple(),
25093            (
25094                c.source().to_string(),
25095                c.destination().to_string(),
25096                c.world_ref().to_string(),
25097            ),
25098            "WitContract::edge_triple must compose exactly \
25099             (source().to_string(), destination().to_string(), \
25100             world_ref().to_string()) — a bypass of any sibling accessor \
25101             here would silently decouple the composite-projection axis \
25102             from the substrate-primitive scalar accessors every \
25103             downstream consumer routes through",
25104        );
25105    }
25106
25107    #[test]
25108    fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
25109        // The canonical semantics-pin: [`WitContract::edge_triple`] must
25110        // project the full `(de, para, wit)` identity of a `:contratos`
25111        // edge — the sub-triple every triple-carrying
25112        // [`AplicacaoError::Contrato*`] diagnostic weaves into its
25113        // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
25114        // missing-target, capability-with-payload, invalid-wit, and the
25115        // duplicate-gate). Rejects a drift in shape (an accidental
25116        // silent detour that returned a `(de, para)` pair or added an
25117        // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
25118        // would trip here because the return type would no longer
25119        // pattern-match the eight `let (de, para, wit) = edge();`
25120        // destructures the [`WitContract::target`] dispatch feeds off
25121        // + the paired duplicate-gate `let (de, para, wit) =
25122        // c.edge_triple();` destructure in
25123        // [`AplicacaoSpec::validate`]). Peer of the sibling per-
25124        // `:contratos` caller-callee-pair pin above extended to the
25125        // triple projection surface: closes the "one composite
25126        // accessor per typed diagnostic-construction sub-tuple"
25127        // discipline on the per-`:contratos` mesh-slot-atom axis.
25128        let c = WitContract {
25129            de: "checkout".into(),
25130            para: "orders".into(),
25131            wit: "nats:pub-sub".into(),
25132            endpoint: None,
25133            subject: Some("orders.paid".into()),
25134            slot: None,
25135        };
25136        let (de, para, wit) = c.edge_triple();
25137        assert_eq!(de, "checkout");
25138        assert_eq!(para, "orders");
25139        assert_eq!(wit, "nats:pub-sub");
25140    }
25141
25142    #[test]
25143    fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
25144     {
25145        // The composition pin: [`WitContract::identity`] must return
25146        // exactly `(source(), destination(), world_ref(), endpoint(),
25147        // subject(), slot())` — the borrowed form of the six-scalar-
25148        // accessor identity axis. Any future refactor that silently
25149        // re-authored one arm's projection to bypass a scalar accessor
25150        // (a `self.de.as_str()` regression back to raw field access on
25151        // any of the three required arms, a `self.endpoint.as_deref()`
25152        // regression on any of the three optional arms, an M4 per-
25153        // cluster caller/callee-alias rewrite the operator lands on
25154        // `source()` / `destination()` without reaching this composite
25155        // projection) trips at caixa-core build time. Sweeps four
25156        // permutations of the WIT-shape × payload lattice — HTTP with
25157        // endpoint, pub-sub with subject, store with slot, payload-less
25158        // capability — so every payload arm is exercised. Peer of the
25159        // sibling per-`:contratos`
25160        // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
25161        // composition pin on the mesh-slot-atom composite-projection
25162        // axis; extends the discipline from the (de, para, wit) prefix
25163        // onto the full-identity axis carrying the three payload arms.
25164        for (de, para, wit, endpoint, subject, slot) in [
25165            (
25166                "cart",
25167                "catalog",
25168                "wasi:http/proxy",
25169                Some("/lookup"),
25170                None,
25171                None,
25172            ),
25173            (
25174                "checkout",
25175                "orders",
25176                "nats:pub-sub",
25177                None,
25178                Some("orders.paid"),
25179                None,
25180            ),
25181            (
25182                "cart",
25183                "kv",
25184                "wasi:keyvalue/store",
25185                None,
25186                None,
25187                Some("carts/{cart_id}"),
25188            ),
25189            ("audit", "sink", "wasi:logging", None, None, None),
25190        ] {
25191            let c = WitContract {
25192                de: de.into(),
25193                para: para.into(),
25194                wit: wit.into(),
25195                endpoint: endpoint.map(str::to_owned),
25196                subject: subject.map(str::to_owned),
25197                slot: slot.map(str::to_owned),
25198            };
25199            assert_eq!(
25200                c.identity(),
25201                (
25202                    c.source(),
25203                    c.destination(),
25204                    c.world_ref(),
25205                    c.endpoint(),
25206                    c.subject(),
25207                    c.slot(),
25208                ),
25209                "WitContract::identity must compose exactly \
25210                 (source(), destination(), world_ref(), endpoint(), \
25211                 subject(), slot()) — a bypass of any sibling accessor \
25212                 here would silently decouple the identity-projection \
25213                 axis from the substrate-primitive scalar accessors \
25214                 every dedup-key consumer routes through",
25215            );
25216        }
25217    }
25218
25219    #[test]
25220    fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
25221        // The canonical semantics-pin: [`WitContract::identity`] must
25222        // project the six-axis (de, para, wit, endpoint, subject, slot)
25223        // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
25224        // gate keys off — two `WitContract`s that agree on all six axes
25225        // are the same typed edge declared twice, the graph-edge
25226        // analogue of duplicate `:membros` / `:placement :clusters` /
25227        // `:entrada :paths` entries. Rejects a shape drift (an
25228        // accidental silent detour that returned a prefix tuple or
25229        // added an extra field) by pattern-matching the six-arm shape.
25230        // Peer of the sibling per-`:contratos`
25231        // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
25232        // pin extended from the (de, para, wit) prefix onto the full
25233        // six-axis identity that the dedup key rides.
25234        let c = WitContract {
25235            de: "cart".into(),
25236            para: "catalog".into(),
25237            wit: "wasi:http/proxy".into(),
25238            endpoint: Some("/products/:id".into()),
25239            subject: None,
25240            slot: None,
25241        };
25242        let (de, para, wit, endpoint, subject, slot) = c.identity();
25243        assert_eq!(de, "cart");
25244        assert_eq!(para, "catalog");
25245        assert_eq!(wit, "wasi:http/proxy");
25246        assert_eq!(endpoint, Some("/products/:id"));
25247        assert_eq!(subject, None);
25248        assert_eq!(slot, None);
25249
25250        // Two byte-identical contracts must produce equal identities —
25251        // the dedup key's foundational invariant.
25252        let c2 = c.clone();
25253        assert_eq!(c.identity(), c2.identity());
25254
25255        // Any change on any of the six axes must break the identity —
25256        // sweeps by mutating one axis at a time.
25257        let mut mutated = c.clone();
25258        mutated.de = "search".into();
25259        assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
25260        let mut mutated = c.clone();
25261        mutated.para = "warehouse".into();
25262        assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
25263        let mut mutated = c.clone();
25264        mutated.wit = "http:legacy".into();
25265        assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
25266        let mut mutated = c.clone();
25267        mutated.endpoint = Some("/search".into());
25268        assert_ne!(
25269            c.identity(),
25270            mutated.identity(),
25271            "endpoint axis must partition"
25272        );
25273        let mut mutated = c.clone();
25274        mutated.subject = Some("orders.paid".into());
25275        assert_ne!(
25276            c.identity(),
25277            mutated.identity(),
25278            "subject axis must partition"
25279        );
25280        let mut mutated = c;
25281        mutated.slot = Some("carts/{id}".into());
25282        assert_ne!(mutated.identity().5, None, "slot axis must partition");
25283    }
25284
25285    #[test]
25286    fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
25287        // The canonical per-`:contratos` structural-self-edge pin:
25288        // [`WitContract::is_self_loop`] must return `true` when the
25289        // `:de` and `:para` fields agree byte-for-byte, across every
25290        // WIT-shape variant the per-edge shape family carries. Pins
25291        // the shape-agnostic identity-space partition the
25292        // [`AplicacaoSpec::validate`] self-edge gate at
25293        // caixa-core/src/aplicacao.rs:5559 fires against — all four
25294        // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
25295        // under the same one predicate. Four permutations sweep the
25296        // accept-set: HTTP with endpoint, pub-sub with subject, KV
25297        // store with slot, and payload-less capability.
25298        for (nome, wit, endpoint, subject, slot) in [
25299            ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
25300            ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
25301            (
25302                "kv",
25303                "wasi:keyvalue/store",
25304                None,
25305                None,
25306                Some("carts/{cart_id}"),
25307            ),
25308            ("audit", "wasi:logging", None, None, None),
25309        ] {
25310            let c = WitContract {
25311                de: nome.into(),
25312                para: nome.into(),
25313                wit: wit.into(),
25314                endpoint: endpoint.map(str::to_string),
25315                subject: subject.map(str::to_string),
25316                slot: slot.map(str::to_string),
25317            };
25318            assert!(
25319                c.is_self_loop(),
25320                "WitContract::is_self_loop must return true when \
25321                 :contratos :de == :contratos :para (got false on \
25322                 {nome:?} under {wit:?})",
25323            );
25324        }
25325    }
25326
25327    #[test]
25328    fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
25329        // The complement pin: [`WitContract::is_self_loop`] must return
25330        // `false` on every well-shaped inter-Servico contract (the
25331        // author-intended `:contratos` shape MESH-COMPOSITION §III.1
25332        // names — "Servico A calls Servico B" between two distinct
25333        // graph nodes). Pins against a future silent detour that
25334        // inverted the predicate (an accidental `!= ` swap for `==`
25335        // would silently reject every legitimate inter-Servico edge
25336        // and admit every self-edge — the exact inversion of the
25337        // author-intended shape). Four permutations sweep the same
25338        // WIT-shape accept-set the sibling positive-arm test carries.
25339        for (de, para, wit, endpoint, subject, slot) in [
25340            (
25341                "cart",
25342                "catalog",
25343                "wasi:http/proxy",
25344                Some("/lookup"),
25345                None,
25346                None,
25347            ),
25348            (
25349                "checkout",
25350                "orders",
25351                "nats:pub-sub",
25352                None,
25353                Some("orders.paid"),
25354                None,
25355            ),
25356            (
25357                "cart",
25358                "kv",
25359                "wasi:keyvalue/store",
25360                None,
25361                None,
25362                Some("carts/{cart_id}"),
25363            ),
25364            ("audit", "sink", "wasi:logging", None, None, None),
25365        ] {
25366            let c = WitContract {
25367                de: de.into(),
25368                para: para.into(),
25369                wit: wit.into(),
25370                endpoint: endpoint.map(str::to_string),
25371                subject: subject.map(str::to_string),
25372                slot: slot.map(str::to_string),
25373            };
25374            assert!(
25375                !c.is_self_loop(),
25376                "WitContract::is_self_loop must return false when \
25377                 :contratos :de differs from :contratos :para (got true \
25378                 on {de:?} → {para:?} under {wit:?})",
25379            );
25380        }
25381    }
25382
25383    #[test]
25384    fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
25385        // The composition pin: [`WitContract::is_self_loop`] must
25386        // resolve to exactly `self.source() == self.destination()` —
25387        // the equality probe of the sibling scalar-accessor pair — so
25388        // any future refactor that silently re-authored the predicate
25389        // to bypass the lifted scalar accessors (an accidental
25390        // `self.de == self.para` regression back to the raw field-
25391        // access shape, an M4-typed-caller-enum identity-comparison
25392        // rule that landed on `source()` without reaching
25393        // `destination()`, a per-cluster alias rewrite the operator
25394        // pins on `destination()` without reaching this predicate)
25395        // trips at caixa-core build time. Pins the "typed dispatch
25396        // composes with typed dispatch, not with raw field access"
25397        // discipline the sibling [`WitContract::edge_pair`] /
25398        // [`WitContract::edge_triple`] composite-projection accessors
25399        // already carry, extended onto the per-edge endpoint-equality
25400        // predicate axis. Positive and complement arms both fire.
25401        let self_edge = WitContract {
25402            de: "cart".into(),
25403            para: "cart".into(),
25404            wit: "wasi:http/proxy".into(),
25405            endpoint: Some("/lookup".into()),
25406            subject: None,
25407            slot: None,
25408        };
25409        assert_eq!(
25410            self_edge.is_self_loop(),
25411            self_edge.source() == self_edge.destination(),
25412            "WitContract::is_self_loop must compose exactly \
25413             `source() == destination()` — a bypass of either sibling \
25414             accessor here would silently decouple the endpoint-\
25415             equality predicate from the substrate-primitive scalar \
25416             accessors every downstream consumer routes through",
25417        );
25418        let inter_edge = WitContract {
25419            de: "cart".into(),
25420            para: "catalog".into(),
25421            wit: "wasi:http/proxy".into(),
25422            endpoint: Some("/lookup".into()),
25423            subject: None,
25424            slot: None,
25425        };
25426        assert_eq!(
25427            inter_edge.is_self_loop(),
25428            inter_edge.source() == inter_edge.destination(),
25429            "WitContract::is_self_loop must compose exactly \
25430             `source() == destination()` on the complement arm too",
25431        );
25432    }
25433
25434    #[test]
25435    fn wit_contract_target_wit_shape_gate_routes_through_world_ref_accessor() {
25436        // The composition pin: [`WitContract::target`]'s invalid-wit
25437        // value-shape gate must feed the reason string through the
25438        // lifted [`WitContract::world_ref`] scalar accessor — the same
25439        // typed dispatch on the substrate primitive every peer
25440        // per-`:contratos` payload-carrier extraction in the same
25441        // method body already routes through
25442        // ([`WitContract::endpoint`] on the HTTP-arm target extraction,
25443        // [`WitContract::subject`] on the pub-sub-arm target extraction,
25444        // [`WitContract::slot`] on the store-arm target extraction) and
25445        // every peer composite-projection accessor
25446        // ([`WitContract::edge_pair`], [`WitContract::edge_triple`],
25447        // [`WitContract::identity`]) already composes from. Any future
25448        // refactor that silently re-authored the gate to bypass the
25449        // lifted accessor (an accidental `&self.wit` regression back to
25450        // the raw field-access shape, an M4-typed-`WitWorld` `Display`
25451        // re-canonicalization on `world_ref()` that didn't reach this
25452        // gate, a per-CR lowercasing canonicalization pass the M4
25453        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
25454        // per-tenant that lands on `world_ref()` without reaching this
25455        // gate) would silently split the invalid-wit diagnostic reason
25456        // from the substrate-primitive projection every downstream
25457        // consumer routes through. Same "typed dispatch composes with
25458        // typed dispatch, not with raw field access" discipline the
25459        // sibling
25460        // [`wit_contract_is_self_loop_routes_through_source_destination_accessors`]
25461        // pin already carries on the endpoint-equality predicate axis,
25462        // extended onto the invalid-wit value-shape gate axis inside
25463        // the same [`WitContract::target`] body. Closes the last
25464        // unlifted raw-field-access site inside `impl WitContract`.
25465        //
25466        // The fixture carries `:wit "WASI:HTTP/proxy"` — the canonical
25467        // uppercase-typo footgun the pre-c4213a4 shape silently demoted
25468        // to a capability-only edge; the value-shape gate rejects it
25469        // through [`crate::render::is_wit_world_ref`] on the substrate
25470        // primitive's ASCII-lowercase-only accept-set, with a
25471        // parser-shaped reason string the test asserts round-trips
25472        // byte-for-byte between the direct-dispatch call (through the
25473        // predicate on the accessor's projection) and the
25474        // [`WitContract::target`] gate's produced reason field.
25475        let c = WitContract {
25476            de: "cart".into(),
25477            para: "catalog".into(),
25478            wit: "WASI:HTTP/proxy".into(),
25479            endpoint: Some("/lookup".into()),
25480            subject: None,
25481            slot: None,
25482        };
25483        let err = c.target().unwrap_err();
25484        let AplicacaoError::ContratoWitInvalid {
25485            ref de,
25486            ref para,
25487            ref wit,
25488            ref reason,
25489        } = err
25490        else {
25491            panic!("expected ContratoWitInvalid, got {err:?}");
25492        };
25493        assert_eq!(de, "cart");
25494        assert_eq!(para, "catalog");
25495        assert_eq!(wit, "WASI:HTTP/proxy");
25496        let expected_reason = crate::render::is_wit_world_ref(c.world_ref()).unwrap_err();
25497        assert_eq!(
25498            *reason, expected_reason,
25499            "WitContract::target's invalid-wit value-shape gate reason \
25500             must compose exactly is_wit_world_ref(self.world_ref()) — \
25501             a bypass here (e.g. a raw `&self.wit` field-access \
25502             regression, or a divergent predicate on a different \
25503             projection) would silently decouple the invalid-wit \
25504             diagnostic's reason field from the substrate-primitive \
25505             scalar accessor every peer per-`:contratos` extraction in \
25506             the same method body already routes through",
25507        );
25508    }
25509
25510    #[test]
25511    fn wit_contract_is_self_loop_predicate_is_const_fn() {
25512        // Fail-before-pass-after pin on the [`WitContract::is_self_loop`]
25513        // caller-callee identity-space predicate's `const`-eval-surface
25514        // posture. The wrapper below dispatches through
25515        // [`WitContract::is_self_loop`] and is well-formed only when the
25516        // callee is itself `pub const fn` — any future accidental
25517        // downgrade to non-`const` fails the wrapper at caixa-core build
25518        // time with E0015 (`cannot call non-const method`), strictly
25519        // stronger than a runtime `assert!` and strictly stronger than a
25520        // module-scope `const _: () = assert!(…)` pin (the type's
25521        // `String` / `Option<String>` carriers rule out `const`-context
25522        // value construction; the `const fn` wrapper is the load-bearing
25523        // shape that side-steps the destructor-in-const restriction on
25524        // the value axis while still pinning the `const`-fn posture on
25525        // the callee — mirror of the sibling
25526        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
25527        // (279823b) and
25528        // [`wit_contract_identity_projection_accessor_is_const_fn`]
25529        // (1ab648c) pins' discipline verbatim on the peer scalar-
25530        // accessor and composite-projection surfaces). Closes the last
25531        // unlifted per-`:contratos` shape/identity predicate on the
25532        // const-eval surface — the peer WIT-shape-partition family
25533        // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
25534        // [`WitContract::is_store`] / [`WitContract::is_capability`]
25535        // already carried the `pub const fn` posture on the peer
25536        // WIT-world-ref classifier axis (d46420c / 84c2325 / 279823b);
25537        // this pin extends the same posture onto the caller-callee
25538        // identity-space partition. Sweeps every WIT-shape arm on both
25539        // the equal-endpoints (self-edge) and distinct-endpoints
25540        // (inter-edge) arms of the identity-space partition, plus one
25541        // same-length distinct-byte pair to pin the mid-loop `!=` arm
25542        // past the leading length-mismatch shortcut.
25543        const fn is_self_loop_via_const_fn(c: &WitContract) -> bool {
25544            c.is_self_loop()
25545        }
25546        let mk = |de: &str, para: &str, wit: &str| WitContract {
25547            de: de.into(),
25548            para: para.into(),
25549            wit: wit.into(),
25550            endpoint: None,
25551            subject: None,
25552            slot: None,
25553        };
25554        for (nome, wit) in [
25555            ("cart", "wasi:http/proxy"),
25556            ("checkout", "nats:pub-sub"),
25557            ("kv", "wasi:keyvalue/store"),
25558            ("audit", "wasi:logging"),
25559        ] {
25560            let self_edge = mk(nome, nome, wit);
25561            assert!(
25562                is_self_loop_via_const_fn(&self_edge),
25563                "self-edge {nome:?} under {wit:?}"
25564            );
25565            assert_eq!(
25566                is_self_loop_via_const_fn(&self_edge),
25567                self_edge.is_self_loop()
25568            );
25569        }
25570        for (de, para, wit) in [
25571            ("cart", "catalog", "wasi:http/proxy"),
25572            ("checkout", "orders", "nats:pub-sub"),
25573            ("cart", "kv", "wasi:keyvalue/store"),
25574            ("audit", "sink", "wasi:logging"),
25575        ] {
25576            let inter_edge = mk(de, para, wit);
25577            assert!(
25578                !is_self_loop_via_const_fn(&inter_edge),
25579                "inter-edge {de:?}→{para:?} under {wit:?}",
25580            );
25581            assert_eq!(
25582                is_self_loop_via_const_fn(&inter_edge),
25583                inter_edge.is_self_loop()
25584            );
25585        }
25586        // Same-length distinct-byte pair — pins the mid-loop `!=` arm
25587        // past the leading `a.len() != b.len()` shortcut so the const-fn
25588        // wrapper exercises every arm of the byte-slice equality loop.
25589        let same_len_pair = mk("cart", "kart", "wasi:http/proxy");
25590        assert!(
25591            !is_self_loop_via_const_fn(&same_len_pair),
25592            "same-length distinct-byte"
25593        );
25594        assert_eq!(
25595            is_self_loop_via_const_fn(&same_len_pair),
25596            same_len_pair.is_self_loop()
25597        );
25598    }
25599
25600    #[test]
25601    fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
25602        // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
25603        // pin: [`WitContract::endpoint`] must return the `:contratos
25604        // :endpoint` field byte-for-byte, borrowed from the typed slot's
25605        // own `Option<String>` storage. Peer of the sibling
25606        // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
25607        // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
25608        // mesh-slot `Option<String>` optional-scalar axes — same "the
25609        // substrate-primitive accessor must byte-equal the raw field
25610        // access verbatim across every author-declared value" discipline
25611        // extended to the per-`:contratos` HTTP-payload-carrier arm.
25612        // Pins against a future silent detour that re-canonicalized the
25613        // endpoint (an accidental percent-encoding pass that didn't
25614        // reach the peer field-access site at the dedup key, a per-CR
25615        // fully-qualified prefix rewrite the operator authors on one
25616        // consumer without the other, or an M4 typed-path-template
25617        // `Display` re-canonicalization that silently drifted the
25618        // printer output from the source `caixa.lisp`). Four values
25619        // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
25620        // gate upstream admits (short root-path, dashed, param-shaped,
25621        // deep-hierarchy).
25622        for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
25623            let c = WitContract {
25624                de: "cart".into(),
25625                para: "catalog".into(),
25626                wit: "wasi:http/proxy".into(),
25627                endpoint: Some(endpoint.into()),
25628                subject: None,
25629                slot: None,
25630            };
25631            assert_eq!(
25632                c.endpoint(),
25633                Some(endpoint),
25634                "WitContract::endpoint must return :contratos :endpoint \
25635                 verbatim (got {:?}, expected Some({endpoint:?}))",
25636                c.endpoint(),
25637            );
25638            assert_eq!(
25639                c.endpoint(),
25640                c.endpoint.as_deref(),
25641                "WitContract::endpoint must byte-equal the .endpoint \
25642                 field's `.as_deref()` projection",
25643            );
25644        }
25645    }
25646
25647    #[test]
25648    fn wit_contract_endpoint_none_when_field_is_none() {
25649        // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
25650        // payload-carrier accessor pin: when the typed slot is absent —
25651        // the canonical shape under a non-HTTP `:wit` world per the
25652        // [`WitContract::target`]-enforced shape ↔ target partition
25653        // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
25654        // carries `:slot`, [`WitTarget::Capability`] carries none) —
25655        // [`WitContract::endpoint`] must return `None`. Pins against a
25656        // future silent detour that projected the absent slot to a
25657        // `Some("")` empty-string default (the canonical `Option<String>`
25658        // → `String` collapse footgun the sibling M2
25659        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
25660        // emptiness predicates already guard on the peer M2 typed-slot
25661        // surfaces), a `Some("None")` stringified-None round-trip, or a
25662        // `Some` arm whose contents were derived from a sibling slot (an
25663        // accidental fallback to the `:subject` / `:slot` payload that
25664        // read the pub-sub / store payload into the endpoint axis).
25665        // Three contracts sweep the accept-set every non-HTTP `:wit`
25666        // world lands on — pub-sub NATS, key/value, and payload-less
25667        // capability.
25668        for (wit, subject, slot) in [
25669            ("nats:pub-sub", Some("orders.paid"), None),
25670            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
25671            ("wasi:cli/environment", None, None),
25672        ] {
25673            let c = WitContract {
25674                de: "cart".into(),
25675                para: "downstream".into(),
25676                wit: wit.into(),
25677                endpoint: None,
25678                subject: subject.map(str::to_string),
25679                slot: slot.map(str::to_string),
25680            };
25681            assert!(
25682                c.endpoint().is_none(),
25683                "WitContract::endpoint must return None when the typed \
25684                 slot is absent under :wit {wit:?} (got {:?})",
25685                c.endpoint(),
25686            );
25687            assert_eq!(
25688                c.endpoint(),
25689                c.endpoint.as_deref(),
25690                "WitContract::endpoint must byte-equal the .endpoint \
25691                 field's `.as_deref()` projection in the absent arm",
25692            );
25693        }
25694    }
25695
25696    #[test]
25697    fn wit_contract_endpoint_borrows_from_endpoint_storage() {
25698        // The borrow-not-copy pin: [`WitContract::endpoint`] must return
25699        // an `Option<&str>` whose `Some` arm borrows from the typed
25700        // slot's own [`String`] storage — same-address invariant with
25701        // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
25702        // detour that allocated a fresh `String`
25703        // (`self.endpoint.clone().map(...)` in the body would type-check
25704        // but silently drop the borrow, and every downstream consumer
25705        // that assumed the returned slice outlives `&self` would break
25706        // on a stale-reference use-after-free — the [`WitContract::target`]
25707        // Http-arm payload extraction rebinds the returned `Option<&str>`
25708        // through `.ok_or_else(...)` and threads the `&str` payload into
25709        // [`WitTarget::Http { endpoint: &'a str }`], the
25710        // [`AplicacaoSpec::validate`] duplicate-`:contratos`
25711        // [`ContratoIdentity`] dedup key threads the returned
25712        // `Option<&str>` into the six-tuple's HTTP arm — each borrow
25713        // from the WitContract's own storage and each would silently
25714        // misbehave if this accessor produced a detached copy). Peer of
25715        // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
25716        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
25717        // shaped optional-scalar axes — first extension of the
25718        // `Option<&str>` borrow-not-copy discipline onto the
25719        // per-`:contratos` HTTP-shaped payload-carrier axis.
25720        let c = WitContract {
25721            de: "cart".into(),
25722            para: "catalog".into(),
25723            wit: "wasi:http/proxy".into(),
25724            endpoint: Some("/lookup".into()),
25725            subject: None,
25726            slot: None,
25727        };
25728        let ep = c.endpoint().expect("Some arm");
25729        let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
25730        assert_eq!(
25731            ep.as_ptr(),
25732            storage_slice.as_ptr(),
25733            "WitContract::endpoint must borrow from the .endpoint \
25734             String's backing storage — a fresh allocation here means \
25735             the accessor no longer names the substrate-primitive typed \
25736             dispatch and every downstream consumer would silently \
25737             carry a detached copy",
25738        );
25739        assert_eq!(
25740            ep.len(),
25741            storage_slice.len(),
25742            "WitContract::endpoint and .endpoint.as_deref() must byte-\
25743             equal in length as well as in address",
25744        );
25745    }
25746
25747    #[test]
25748    fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
25749        // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
25750        // pin: [`WitContract::subject`] must return the `:contratos
25751        // :subject` field byte-for-byte, borrowed from the typed slot's
25752        // own `Option<String>` storage. Peer of the sibling per-`:contratos`
25753        // [`WitContract::endpoint`] (7020470) accessor pin on the M3
25754        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
25755        // optional-scalar axis — same "the substrate-primitive accessor
25756        // must byte-equal the raw field access verbatim across every
25757        // author-declared value" discipline extended to the pub-sub arm.
25758        // Pins against a future silent detour that re-canonicalized the
25759        // subject (an accidental `.to_lowercase()` normalization that
25760        // didn't reach the peer field-access site at the dedup key, a
25761        // per-CR fully-qualified prefix rewrite the operator authors on
25762        // one consumer without the other, or an M4 typed-subject-template
25763        // `Display` re-canonicalization that silently drifted the printer
25764        // output from the source `caixa.lisp`). Four values sweep the
25765        // NATS accept-set every pub-sub author-declared subject lands on
25766        // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
25767        for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
25768            let c = WitContract {
25769                de: "cart".into(),
25770                para: "notifier".into(),
25771                wit: "nats:pub-sub".into(),
25772                endpoint: None,
25773                subject: Some(subject.into()),
25774                slot: None,
25775            };
25776            assert_eq!(
25777                c.subject(),
25778                Some(subject),
25779                "WitContract::subject must return :contratos :subject \
25780                 verbatim (got {:?}, expected Some({subject:?}))",
25781                c.subject(),
25782            );
25783            assert_eq!(
25784                c.subject(),
25785                c.subject.as_deref(),
25786                "WitContract::subject must byte-equal the .subject \
25787                 field's `.as_deref()` projection",
25788            );
25789        }
25790    }
25791
25792    #[test]
25793    fn wit_contract_subject_none_when_field_is_none() {
25794        // The absent-`:subject` arm of the per-`:contratos` pub-sub-
25795        // shaped payload-carrier accessor pin: when the typed slot is
25796        // absent — the canonical shape under a non-pub-sub `:wit` world
25797        // per the [`WitContract::target`]-enforced shape ↔ target
25798        // partition ([`WitTarget::Http`] carries `:endpoint`,
25799        // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
25800        // carries none) — [`WitContract::subject`] must return `None`.
25801        // Pins against a future silent detour that projected the absent
25802        // slot to a `Some("")` empty-string default (the canonical
25803        // `Option<String>` → `String` collapse footgun the sibling M2
25804        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
25805        // emptiness predicates already guard on the peer M2 typed-slot
25806        // surfaces), a `Some("None")` stringified-None round-trip, or a
25807        // `Some` arm whose contents were derived from a sibling slot (an
25808        // accidental fallback to the `:endpoint` / `:slot` payload that
25809        // read the HTTP / store payload into the subject axis). Three
25810        // contracts sweep the accept-set every non-pub-sub `:wit` world
25811        // lands on — HTTP proxy, key/value store, and payload-less
25812        // capability.
25813        for (wit, endpoint, slot) in [
25814            ("wasi:http/proxy", Some("/lookup"), None),
25815            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
25816            ("wasi:cli/environment", None, None),
25817        ] {
25818            let c = WitContract {
25819                de: "cart".into(),
25820                para: "downstream".into(),
25821                wit: wit.into(),
25822                endpoint: endpoint.map(str::to_string),
25823                subject: None,
25824                slot: slot.map(str::to_string),
25825            };
25826            assert!(
25827                c.subject().is_none(),
25828                "WitContract::subject must return None when the typed \
25829                 slot is absent under :wit {wit:?} (got {:?})",
25830                c.subject(),
25831            );
25832            assert_eq!(
25833                c.subject(),
25834                c.subject.as_deref(),
25835                "WitContract::subject must byte-equal the .subject \
25836                 field's `.as_deref()` projection in the absent arm",
25837            );
25838        }
25839    }
25840
25841    #[test]
25842    fn wit_contract_subject_borrows_from_subject_storage() {
25843        // The borrow-not-copy pin: [`WitContract::subject`] must return
25844        // an `Option<&str>` whose `Some` arm borrows from the typed
25845        // slot's own [`String`] storage — same-address invariant with
25846        // `c.subject.as_deref().unwrap()`. Pins against a future silent
25847        // detour that allocated a fresh `String`
25848        // (`self.subject.clone().map(...)` in the body would type-check
25849        // but silently drop the borrow, and every downstream consumer
25850        // that assumed the returned slice outlives `&self` would break
25851        // on a stale-reference use-after-free — the [`WitContract::target`]
25852        // PubSub-arm payload extraction rebinds the returned
25853        // `Option<&str>` through `.ok_or_else(...)` and threads the
25854        // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
25855        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
25856        // [`ContratoIdentity`] dedup key threads the returned
25857        // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
25858        // from the WitContract's own storage and each would silently
25859        // misbehave if this accessor produced a detached copy). Peer of
25860        // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
25861        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
25862        // shaped optional-scalar axis — second extension of the
25863        // `Option<&str>` borrow-not-copy discipline onto the
25864        // per-`:contratos` payload-carrier family, this time on the
25865        // pub-sub arm.
25866        let c = WitContract {
25867            de: "cart".into(),
25868            para: "notifier".into(),
25869            wit: "nats:pub-sub".into(),
25870            endpoint: None,
25871            subject: Some("orders.paid".into()),
25872            slot: None,
25873        };
25874        let sub = c.subject().expect("Some arm");
25875        let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
25876        assert_eq!(
25877            sub.as_ptr(),
25878            storage_slice.as_ptr(),
25879            "WitContract::subject must borrow from the .subject \
25880             String's backing storage — a fresh allocation here means \
25881             the accessor no longer names the substrate-primitive typed \
25882             dispatch and every downstream consumer would silently \
25883             carry a detached copy",
25884        );
25885        assert_eq!(
25886            sub.len(),
25887            storage_slice.len(),
25888            "WitContract::subject and .subject.as_deref() must byte-\
25889             equal in length as well as in address",
25890        );
25891    }
25892
25893    #[test]
25894    fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
25895        // The canonical per-`:contratos` key/value-store-shaped
25896        // `:slot`-scalar pin: [`WitContract::slot`] must return the
25897        // `:contratos :slot` field byte-for-byte, borrowed from the
25898        // typed slot's own `Option<String>` storage. Peer of the
25899        // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
25900        // [`WitContract::subject`] (90de675) accessor pins on the M3
25901        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
25902        // optional-scalar axis — same "the substrate-primitive
25903        // accessor must byte-equal the raw field access verbatim
25904        // across every author-declared value" discipline extended to
25905        // the store arm. Pins against a future silent detour that
25906        // re-canonicalized the slot template (an accidental
25907        // `.to_lowercase()` bucket-prefix normalization that didn't
25908        // reach the peer field-access site at the dedup key, a per-CR
25909        // fully-qualified prefix rewrite the operator authors on one
25910        // consumer without the other, or an M4 typed-key-template
25911        // `Display` re-canonicalization that silently drifted the
25912        // printer output from the source `caixa.lisp`). Four values
25913        // sweep the wasi:keyvalue accept-set every store-shaped
25914        // author-declared slot lands on (flat bucket, single-param
25915        // template, multi-param template, nested-hierarchy template).
25916        for slot in [
25917            "sessions",
25918            "carts/{cart_id}",
25919            "orders/{tenant}/{order_id}",
25920            "cache/tenant-a/orders/{id}",
25921        ] {
25922            let c = WitContract {
25923                de: "cart".into(),
25924                para: "kv".into(),
25925                wit: "wasi:keyvalue/store".into(),
25926                endpoint: None,
25927                subject: None,
25928                slot: Some(slot.into()),
25929            };
25930            assert_eq!(
25931                c.slot(),
25932                Some(slot),
25933                "WitContract::slot must return :contratos :slot \
25934                 verbatim (got {:?}, expected Some({slot:?}))",
25935                c.slot(),
25936            );
25937            assert_eq!(
25938                c.slot(),
25939                c.slot.as_deref(),
25940                "WitContract::slot must byte-equal the .slot field's \
25941                 `.as_deref()` projection",
25942            );
25943        }
25944    }
25945
25946    #[test]
25947    fn wit_contract_slot_none_when_field_is_none() {
25948        // The absent-`:slot` arm of the per-`:contratos` store-shaped
25949        // payload-carrier accessor pin: when the typed slot is absent —
25950        // the canonical shape under a non-store `:wit` world per the
25951        // [`WitContract::target`]-enforced shape ↔ target partition
25952        // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
25953        // carries `:subject`, [`WitTarget::Capability`] carries none) —
25954        // [`WitContract::slot`] must return `None`. Pins against a
25955        // future silent detour that projected the absent slot to a
25956        // `Some("")` empty-string default (the canonical
25957        // `Option<String>` → `String` collapse footgun the sibling M2
25958        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
25959        // emptiness predicates already guard on the peer M2 typed-slot
25960        // surfaces), a `Some("None")` stringified-None round-trip, or
25961        // a `Some` arm whose contents were derived from a sibling
25962        // slot (an accidental fallback to the `:endpoint` / `:subject`
25963        // payload that read the HTTP / pub-sub payload into the store
25964        // axis). Three contracts sweep the accept-set every non-store
25965        // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
25966        // payload-less capability.
25967        for (wit, endpoint, subject) in [
25968            ("wasi:http/proxy", Some("/lookup"), None),
25969            ("nats:pub-sub", None, Some("orders.paid")),
25970            ("wasi:cli/environment", None, None),
25971        ] {
25972            let c = WitContract {
25973                de: "cart".into(),
25974                para: "downstream".into(),
25975                wit: wit.into(),
25976                endpoint: endpoint.map(str::to_string),
25977                subject: subject.map(str::to_string),
25978                slot: None,
25979            };
25980            assert!(
25981                c.slot().is_none(),
25982                "WitContract::slot must return None when the typed \
25983                 slot is absent under :wit {wit:?} (got {:?})",
25984                c.slot(),
25985            );
25986            assert_eq!(
25987                c.slot(),
25988                c.slot.as_deref(),
25989                "WitContract::slot must byte-equal the .slot field's \
25990                 `.as_deref()` projection in the absent arm",
25991            );
25992        }
25993    }
25994
25995    #[test]
25996    fn wit_contract_slot_borrows_from_slot_storage() {
25997        // The borrow-not-copy pin: [`WitContract::slot`] must return
25998        // an `Option<&str>` whose `Some` arm borrows from the typed
25999        // slot's own [`String`] storage — same-address invariant with
26000        // `c.slot.as_deref().unwrap()`. Pins against a future silent
26001        // detour that allocated a fresh `String`
26002        // (`self.slot.clone().map(...)` in the body would type-check
26003        // but silently drop the borrow, and every downstream consumer
26004        // that assumed the returned slice outlives `&self` would
26005        // break on a stale-reference use-after-free — the
26006        // [`WitContract::target`] Store-arm payload extraction rebinds
26007        // the returned `Option<&str>` through `.ok_or_else(...)` and
26008        // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
26009        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
26010        // [`ContratoIdentity`] dedup key threads the returned
26011        // `Option<&str>` into the six-tuple's store arm — each borrow
26012        // from the WitContract's own storage and each would silently
26013        // misbehave if this accessor produced a detached copy). Peer
26014        // of the sibling per-`:contratos` [`WitContract::endpoint`]
26015        // (7020470) / [`WitContract::subject`] (90de675)
26016        // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
26017        // shaped optional-scalar axis — third and final extension of
26018        // the `Option<&str>` borrow-not-copy discipline onto the
26019        // per-`:contratos` payload-carrier family, this time on the
26020        // store arm.
26021        let c = WitContract {
26022            de: "cart".into(),
26023            para: "kv".into(),
26024            wit: "wasi:keyvalue/store".into(),
26025            endpoint: None,
26026            subject: None,
26027            slot: Some("carts/{cart_id}".into()),
26028        };
26029        let slot = c.slot().expect("Some arm");
26030        let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
26031        assert_eq!(
26032            slot.as_ptr(),
26033            storage_slice.as_ptr(),
26034            "WitContract::slot must borrow from the .slot String's \
26035             backing storage — a fresh allocation here means the \
26036             accessor no longer names the substrate-primitive typed \
26037             dispatch and every downstream consumer would silently \
26038             carry a detached copy",
26039        );
26040        assert_eq!(
26041            slot.len(),
26042            storage_slice.len(),
26043            "WitContract::slot and .slot.as_deref() must byte-equal \
26044             in length as well as in address",
26045        );
26046    }
26047
26048    #[test]
26049    fn membro_nome_returns_caixa_byte_equal_across_permutations() {
26050        // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
26051        // [`Membro::nome`] must return the `:membros :caixa` field
26052        // byte-for-byte, borrowed from the typed slot's own [`String`]
26053        // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
26054        // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
26055        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
26056        // slot-atom scalar-value axes — same "the substrate-primitive
26057        // accessor must byte-equal the raw field access verbatim across
26058        // every author-declared value" discipline extended to the
26059        // per-`:membros` member-identity arm. Pins against a future
26060        // silent detour that re-normalized the member identity (an
26061        // accidental `.to_lowercase()` — every `:membros :caixa` is
26062        // validated as a DNS-1123 label upstream via
26063        // [`validate_membro_caixa`], so any re-normalization is
26064        // redundant + a drift surface between the validator and the
26065        // accessor), a namespace-prefix rewrite (an accidental
26066        // `format!("{namespace}/{caixa}")` per-CR fully-qualified
26067        // rewrite that didn't land on the peer axes), or a per-cluster
26068        // alias stamp the operator authors on one consumer without the
26069        // other. Four values sweep the accept-set the DNS-1123 gate
26070        // upstream admits (short single-word / dashed / v-suffixed
26071        // member names).
26072        for name in ["cart", "checkout", "catalog", "orders-v2"] {
26073            let m = Membro {
26074                caixa: name.into(),
26075                versao: "^0.1".into(),
26076            };
26077            assert_eq!(
26078                m.nome(),
26079                name,
26080                "Membro::nome must return :membros :caixa verbatim \
26081                 (got {:?}, expected {name:?})",
26082                m.nome(),
26083            );
26084            assert_eq!(
26085                m.nome(),
26086                m.caixa.as_str(),
26087                "Membro::nome must byte-equal the .caixa field access",
26088            );
26089        }
26090    }
26091
26092    #[test]
26093    fn membro_nome_borrows_from_caixa_storage() {
26094        // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
26095        // slice that borrows from the typed slot's own [`String`]
26096        // storage — same-address invariant with `m.caixa.as_str()`. Pins
26097        // against a future silent detour that allocated a fresh `String`
26098        // (`self.caixa.clone()` in the body would type-check but
26099        // silently drop the borrow, and every downstream consumer that
26100        // assumed the returned slice outlives `&self` would break on a
26101        // stale-reference use-after-free — the `HashSet<&str>` collector
26102        // at [`AplicacaoSpec::validate`]'s `names` seed, the
26103        // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
26104        // [`AplicacaoSpec::detect_sync_cycles`], the
26105        // [`crate::render::insert_first_seen`] dedup key at
26106        // [`AplicacaoSpec::validate_membros`] — each borrow from the
26107        // Membro's own storage and each would silently misbehave if
26108        // this accessor produced a detached copy). Peer of the sibling
26109        // per-`:contratos` [`WitContract::source`] /
26110        // [`WitContract::destination`] and per-`:entrada`
26111        // [`Entrada::destination`] borrow-invariant pins on the mesh-
26112        // slot-atom scalar-value axes.
26113        let m = Membro {
26114            caixa: "checkout".into(),
26115            versao: "^0.1".into(),
26116        };
26117        let name = m.nome();
26118        let caixa_slice = m.caixa.as_str();
26119        assert_eq!(
26120            name.as_ptr(),
26121            caixa_slice.as_ptr(),
26122            "Membro::nome must borrow from the .caixa String's backing \
26123             storage — a fresh allocation here means the accessor no \
26124             longer names the substrate-primitive typed dispatch and \
26125             every downstream consumer would silently carry a detached \
26126             copy",
26127        );
26128        assert_eq!(
26129            name.len(),
26130            caixa_slice.len(),
26131            "Membro::nome and .caixa.as_str() must byte-equal in length \
26132             as well as in address",
26133        );
26134    }
26135
26136    #[test]
26137    fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
26138        // The canonical per-`:membros` member-`:versao`-scalar pin:
26139        // [`Membro::versao_requirement`] must return the
26140        // `:membros :versao` field byte-for-byte, borrowed from the typed
26141        // slot's own [`String`] storage. Sibling of the peer
26142        // `membro_nome_returns_caixa_byte_equal_across_permutations`
26143        // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
26144        // — same "the substrate-primitive accessor must byte-equal the
26145        // raw field access verbatim across every author-declared value"
26146        // discipline extended to the per-`:membros` member-`:versao`
26147        // requirement-string arm. Pins against a future silent detour
26148        // that re-canonicalized the requirement (an accidental
26149        // `.to_string()` via [`parse_requirement`] → [`Display`] round-
26150        // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
26151        // drifted the printer output away from the source `caixa.lisp`,
26152        // an accidental whitespace trim on `"^ 0.1"` that no consumer
26153        // ever produced from the field-access side, an accidental
26154        // per-cluster lacre-projected concrete-version rewrite that
26155        // didn't land on the peer field-access sites). Five values sweep
26156        // the accept-set the shared
26157        // [`crate::render::require_valid_versao_requirement`] gate
26158        // admits (caret / tilde / exact / wildcard / bare-major).
26159        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
26160            let m = Membro {
26161                caixa: "cart".into(),
26162                versao: req.into(),
26163            };
26164            assert_eq!(
26165                m.versao_requirement(),
26166                req,
26167                "Membro::versao_requirement must return :membros :versao \
26168                 verbatim (got {:?}, expected {req:?})",
26169                m.versao_requirement(),
26170            );
26171            assert_eq!(
26172                m.versao_requirement(),
26173                m.versao.as_str(),
26174                "Membro::versao_requirement must byte-equal the .versao \
26175                 field access",
26176            );
26177        }
26178    }
26179
26180    #[test]
26181    fn membro_versao_requirement_borrows_from_versao_storage() {
26182        // The borrow-not-copy pin: [`Membro::versao_requirement`] must
26183        // return a `&str` slice that borrows from the typed slot's own
26184        // [`String`] storage — same-address invariant with
26185        // `m.versao.as_str()`. Pins against a future silent detour that
26186        // allocated a fresh `String` (`self.versao.clone()` in the body
26187        // would type-check but silently drop the borrow, and every
26188        // downstream consumer that assumed the returned slice outlives
26189        // `&self` would break on a stale-reference use-after-free). Peer
26190        // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
26191        // per-`:contratos` [`WitContract::source`] /
26192        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
26193        // [`Entrada::destination`] (6db982c) borrow-invariant pins on
26194        // the mesh-slot-atom scalar-value axes.
26195        let m = Membro {
26196            caixa: "checkout".into(),
26197            versao: "^0.1".into(),
26198        };
26199        let req = m.versao_requirement();
26200        let versao_slice = m.versao.as_str();
26201        assert_eq!(
26202            req.as_ptr(),
26203            versao_slice.as_ptr(),
26204            "Membro::versao_requirement must borrow from the .versao \
26205             String's backing storage — a fresh allocation here means \
26206             the accessor no longer names the substrate-primitive typed \
26207             dispatch and every downstream consumer would silently carry \
26208             a detached copy",
26209        );
26210        assert_eq!(
26211            req.len(),
26212            versao_slice.len(),
26213            "Membro::versao_requirement and .versao.as_str() must byte-\
26214             equal in length as well as in address",
26215        );
26216    }
26217
26218    #[test]
26219    fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
26220        // Sibling-pair invariant pin composing both per-`:membros`
26221        // substrate-primitive typed dispatches — [`Membro::nome`]
26222        // (4a32abf) and [`Membro::versao_requirement`] — at the joint
26223        // `(nome(), versao_requirement())` call shape every renderer
26224        // that fans on per-member identity + version pin keys off. The
26225        // invariant, evaluated per-member:
26226        //
26227        //   (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
26228        //
26229        // Closes the last unlifted per-`:membros` scalar axis — every
26230        // downstream consumer that reads the pair now routes through
26231        // exactly two typed dispatches on the substrate primitive, not
26232        // one typed + one open-coded field access. A future refactor
26233        // that silently split either accessor's projection (an
26234        // accidental `nome()` namespace-prefix rewrite that didn't
26235        // reach the peer, an accidental `versao_requirement()` lacre-
26236        // projected concrete-version rewrite that didn't land on the
26237        // `nome()` peer) surfaces at caixa-core build time. Peer of the
26238        // sibling per-`:entrada` `(hostname(), destination())` and
26239        // per-`:contratos` `(source(), destination())` pair invariants
26240        // on the mesh-slot-atom scalar-value axes.
26241        for (caixa, versao) in [
26242            ("cart", "^0.1"),
26243            ("checkout", "~0.1.2"),
26244            ("catalog", "0.1.0"),
26245            ("orders-v2", "*"),
26246        ] {
26247            let m = Membro {
26248                caixa: caixa.into(),
26249                versao: versao.into(),
26250            };
26251            assert_eq!(
26252                (m.nome(), m.versao_requirement()),
26253                (m.caixa.as_str(), m.versao.as_str()),
26254                "(Membro::nome, Membro::versao_requirement) must project \
26255                 (.caixa, .versao) verbatim across every author-declared \
26256                 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
26257                m.nome(),
26258                m.versao_requirement(),
26259            );
26260        }
26261    }
26262
26263    #[test]
26264    fn validate_membros_empty_gate_routes_through_nome_accessor() {
26265        // Composition pin: [`AplicacaoSpec::validate_membros`]'s
26266        // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
26267        // not the raw `.caixa` field access. Structurally: setting
26268        // ONLY the `.caixa` field to `""` on an otherwise-well-formed
26269        // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
26270        // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
26271        // (i.e. the empty string) — so the emptiness predicate the
26272        // refusal arm reaches under is the accessor-projected value,
26273        // not a peer field that would silently drift under a future
26274        // accessor-side rewrite.
26275        //
26276        // Pins against a future silent detour that (a) re-derived the
26277        // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
26278        // instead of `self.nome().is_empty()`, silently disagreeing with
26279        // every peer consumer (the `validate_membro_caixa(m.nome())`
26280        // per-slot helper — which now owns the emptiness arm outright —
26281        // the dedup-key `insert_first_seen(&mut seen, m.nome(), …)`
26282        // below, and the emit-side per-`programs[]` entry-`name:` at
26283        // caixa-mesh/src/lib.rs:133), (b) accessor-side introduced a
26284        // per-tenant alias arm the caller was unaware of, silently
26285        // rewriting an author-declared `:caixa "checkout"` to `""` —
26286        // the raw-field-access gate would fail-open while the
26287        // accessor-routed peer consumers would fail-closed, splitting
26288        // the diagnostic from the actual failure surface.
26289        //
26290        // Peer of the sibling
26291        // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
26292        // (c0110f1) composition pin — same "the shape-gate predicate
26293        // must route through the substrate-primitive typed dispatch"
26294        // discipline extended onto the per-`:membros` empty-`:caixa`
26295        // refusal-arm axis. Closes the last unlifted `.caixa` production-
26296        // code read site on `Membro` — after this converge every
26297        // caixa-core `.caixa` field access outside the accessor's own
26298        // body is either a test-side field-setter (in-module tests
26299        // constructing invalid-shape inputs) or a doc-comment reference.
26300        let mut s = three_member_spec();
26301        s.membros[1].caixa = String::new();
26302        assert!(
26303            s.membros[1].nome().is_empty(),
26304            "Membro::nome must byte-equal the .caixa field access — an \
26305             accessor-side detour that no longer projects the raw field \
26306             would silently split this drift-detection test from the \
26307             validate() refusal arm",
26308        );
26309        assert_eq!(
26310            s.membros[1].nome(),
26311            s.membros[1].caixa.as_str(),
26312            "Membro::nome and .caixa.as_str() must byte-equal on an \
26313             empty-`:caixa` entry — the emptiness gate keys off the \
26314             accessor by construction",
26315        );
26316        assert_eq!(
26317            s.validate().unwrap_err(),
26318            AplicacaoError::MembroCaixaEmpty,
26319            "validate_membros' emptiness gate must fire MembroCaixaEmpty \
26320             on an entry whose accessor-projected `nome()` is empty",
26321        );
26322    }
26323
26324    #[test]
26325    fn validate_membros_empty_arm_is_owned_by_validate_membro_caixa_alone() {
26326        // Convergence pin, paired with the deletion of the redundant
26327        // outer `if m.nome().is_empty() { return Err(MembroCaixaEmpty); }`
26328        // guard formerly inline in [`AplicacaoSpec::validate_membros`]:
26329        // after the collapse, the `MembroCaixaEmpty` refusal on every
26330        // empty-`:caixa` per-member input is owned solely by the shared
26331        // [`validate_membro_caixa`] helper — the same per-slot substrate
26332        // primitive routing empty + shape arms uniformly onto
26333        // [`crate::render::require_valid_dns_1123_label`] that every
26334        // peer M3 mesh-slot per-slot gate ([`validate_placement_cluster`]
26335        // on `:placement :clusters`, [`validate_entrada_para`] on
26336        // `:entrada :para`, [`validate_contrato_caixa`] on `:contratos
26337        // :de`/`:para`) already funnels its own empty arm through.
26338        //
26339        // Two arms pin the collapse:
26340        //
26341        //   (1) The per-slot helper called with the empty string returns
26342        //       byte-equal to the previous inline arm's diagnostic — so
26343        //       a future rebrand of [`validate_membro_caixa`] that
26344        //       (accidentally) stopped returning [`MembroCaixaEmpty`] on
26345        //       empty input (an inadvertent switch to
26346        //       [`AplicacaoError::MembroCaixaInvalid`] via the parse-side
26347        //       `on_invalid` arm, an accidental re-routing to a shared
26348        //       `MembroError::Empty` under a future error-hierarchy
26349        //       flattening) would silently split the drift from the
26350        //       [`validate_membros`] caller and surface the wrong
26351        //       diagnostic on the author-facing empty-`:caixa` footgun.
26352        //
26353        //   (2) The whole-spec equivalence: an empty-`:caixa` entry
26354        //       anywhere in the `:membros` fan-out still trips
26355        //       [`MembroCaixaEmpty`] end-to-end via [`validate`], with
26356        //       no outer inline guard needed. Same shape as the
26357        //       whole-spec arm on [`validate_placement_cluster`] /
26358        //       [`validate_entrada_para`] / [`validate_contrato_caixa`]:
26359        //       one substrate primitive per axis, folding empty + shape.
26360        //
26361        // Same PRIME DIRECTIVE convergence the peer per-slot gate lifts
26362        // (906a5c6 validate_contratos, 20cd523 validate_entrada, f03a154
26363        // MeshPolicy::validate) already extend across the M3 mesh-slot
26364        // family — closes the last per-slot gate on the family carrying
26365        // an inline empty guard duplicating its own helper.
26366        assert_eq!(
26367            validate_membro_caixa(""),
26368            Err(AplicacaoError::MembroCaixaEmpty),
26369            "validate_membro_caixa must own the empty arm outright — a \
26370             regression here would silently split MembroCaixaEmpty from \
26371             validate_membros' end-to-end refusal shape after the outer \
26372             inline `if m.nome().is_empty()` guard collapse",
26373        );
26374        let mut s = three_member_spec();
26375        s.membros[0].caixa = String::new();
26376        assert_eq!(
26377            s.validate().unwrap_err(),
26378            AplicacaoError::MembroCaixaEmpty,
26379            "an empty-`:caixa` :membros head entry must trip \
26380             MembroCaixaEmpty end-to-end via validate() with the outer \
26381             inline guard removed — the per-slot helper alone is now \
26382             load-bearing",
26383        );
26384        let mut s = three_member_spec();
26385        s.membros[2].caixa = String::new();
26386        assert_eq!(
26387            s.validate().unwrap_err(),
26388            AplicacaoError::MembroCaixaEmpty,
26389            "an empty-`:caixa` :membros tail entry must trip \
26390             MembroCaixaEmpty end-to-end via validate() with the outer \
26391             inline guard removed — the per-slot helper alone reaches \
26392             every fan-out position",
26393        );
26394    }
26395
26396    #[test]
26397    fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
26398        // The canonical per-`:placement` Akka-cluster-sharding
26399        // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
26400        // the `:placement :shard-key` field byte-for-byte, borrowed
26401        // from the typed slot's own `Option<String>` storage. Peer of
26402        // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
26403        // per-`:contratos` [`WitContract::source`] /
26404        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
26405        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
26406        // slot-atom scalar-value axes — same "the substrate-primitive
26407        // accessor must byte-equal the raw field access verbatim across
26408        // every author-declared value" discipline extended to the
26409        // per-`:placement` Akka-cluster-sharding key extractor arm.
26410        // Pins against a future silent detour that re-normalized the
26411        // key (an accidental `.to_lowercase()` — every non-empty
26412        // `:shard-key` is validated as a printable-ASCII single-token
26413        // reference upstream via [`validate_placement_shard_key`], so
26414        // any re-normalization is redundant + a drift surface between
26415        // the validator and the accessor), a per-cluster alias rewrite
26416        // the operator authors on one consumer without the other, or an
26417        // accidental variable-prefix strip (`$tenantId` → `tenantId`)
26418        // that didn't land on the peer field-access sites. Four values
26419        // sweep the accept-set the shape gate admits — bare identifier,
26420        // `$`-prefixed variable, dotted path, `${}`-quoted variable —
26421        // the four canonical Akka-style entity-id extractor shapes the
26422        // future M4 cluster-sharding reconciler hashes.
26423        for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
26424            let p = Placement {
26425                estrategia: PlacementStrategy::Sharded,
26426                clusters: vec!["rio".into()],
26427                affinity: None,
26428                shard_key: Some(key.into()),
26429            };
26430            assert_eq!(
26431                p.shard_key(),
26432                Some(key),
26433                "Placement::shard_key must return :placement :shard-key \
26434                 verbatim (got {:?}, expected Some({key:?}))",
26435                p.shard_key(),
26436            );
26437            assert_eq!(
26438                p.shard_key(),
26439                p.shard_key.as_deref(),
26440                "Placement::shard_key must byte-equal the .shard_key \
26441                 field's `.as_deref()` projection",
26442            );
26443        }
26444    }
26445
26446    #[test]
26447    fn placement_shard_key_none_when_field_is_none() {
26448        // The absent-`:shard-key` arm of the per-`:placement`
26449        // Akka-cluster-sharding accessor pin: when the typed slot is
26450        // absent — the canonical shape under `:estrategia Replicated` /
26451        // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
26452        // enforced `shard_key.is_some() == matches!(estrategia,
26453        // Sharded)` partition — [`Placement::shard_key`] must return
26454        // `None`. Pins against a future silent detour that projected
26455        // the absent slot to a `Some("")` empty-string default (the
26456        // canonical `Option<String>` → `String` collapse footgun the
26457        // sibling M2 [`crate::LimitsSpec::is_empty`] /
26458        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
26459        // already guard on the peer M2 typed-slot surfaces), a
26460        // `Some("None")` stringified-None round-trip, or a `Some` arm
26461        // whose contents were derived from a sibling slot (an
26462        // accidental fallback to `estrategia.as_str()` that read the
26463        // strategy discriminator into the key axis). Two placements
26464        // sweep the accept-set every `validate`-passing non-`Sharded`
26465        // shape lands on — `Replicated` (Erlang/OTP distributed-app
26466        // takeover) and `SingleNode` (single-node hosting).
26467        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
26468            let p = Placement {
26469                estrategia,
26470                clusters: vec!["rio".into()],
26471                affinity: None,
26472                shard_key: None,
26473            };
26474            assert!(
26475                p.shard_key().is_none(),
26476                "Placement::shard_key must return None when the typed \
26477                 slot is absent under :estrategia {estrategia:?} (got {:?})",
26478                p.shard_key(),
26479            );
26480            assert_eq!(
26481                p.shard_key(),
26482                p.shard_key.as_deref(),
26483                "Placement::shard_key must byte-equal the .shard_key \
26484                 field's `.as_deref()` projection in the absent arm",
26485            );
26486        }
26487    }
26488
26489    #[test]
26490    fn placement_shard_key_borrows_from_shard_key_storage() {
26491        // The borrow-not-copy pin: [`Placement::shard_key`] must return
26492        // an `Option<&str>` whose `Some` arm borrows from the typed
26493        // slot's own [`String`] storage — same-address invariant with
26494        // `p.shard_key.as_deref().unwrap()`. Pins against a future
26495        // silent detour that allocated a fresh `String`
26496        // (`self.shard_key.clone().map(...)` in the body would type-
26497        // check but silently drop the borrow, and every downstream
26498        // consumer that assumed the returned slice outlives `&self`
26499        // would break on a stale-reference use-after-free — the
26500        // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
26501        // gate's `Some(k)`-bound match arm reads `k: &str` under the
26502        // accessor's return type and would silently misbehave if this
26503        // accessor produced a detached copy). Peer of the sibling
26504        // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
26505        // [`WitContract::source`] / [`WitContract::destination`]
26506        // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
26507        // (6db982c) borrow-invariant pins on the mesh-slot-atom
26508        // scalar-value axes — first extension of the discipline onto
26509        // an `Option<String>`-shaped optional-scalar axis.
26510        let p = Placement {
26511            estrategia: PlacementStrategy::Sharded,
26512            clusters: vec!["rio".into()],
26513            affinity: None,
26514            shard_key: Some("tenantId".into()),
26515        };
26516        let key = p.shard_key().expect("Some arm");
26517        let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
26518        assert_eq!(
26519            key.as_ptr(),
26520            storage_slice.as_ptr(),
26521            "Placement::shard_key must borrow from the .shard_key \
26522             String's backing storage — a fresh allocation here means \
26523             the accessor no longer names the substrate-primitive typed \
26524             dispatch and every downstream consumer would silently \
26525             carry a detached copy",
26526        );
26527        assert_eq!(
26528            key.len(),
26529            storage_slice.len(),
26530            "Placement::shard_key and .shard_key.as_deref() must byte-\
26531             equal in length as well as in address",
26532        );
26533    }
26534
26535    #[test]
26536    fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
26537        // The canonical per-`:placement` M3-Adaptive-compression-hint
26538        // scalar pin: [`Placement::affinity`] must return the
26539        // `:placement :affinity` field byte-for-byte, borrowed from the
26540        // typed slot's own `Option<String>` storage. Peer of the sibling
26541        // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
26542        // pin on the sibling `Option<&str>` optional-scalar axis — same
26543        // "the substrate-primitive accessor must byte-equal the raw
26544        // field access verbatim across every author-declared value"
26545        // discipline extended to the peer per-`:placement` M3-Adaptive-
26546        // compression-hint arm. Pins against a future silent detour
26547        // that re-normalized the hint (an accidental `.to_lowercase()`
26548        // — every `:affinity` is already validated as a DNS-1123 label
26549        // upstream via [`validate_placement_affinity`], so any re-
26550        // normalization is redundant + a drift surface between the
26551        // validator and the accessor), a per-cluster alias rewrite the
26552        // operator authors on one consumer without the other, or an
26553        // accidental hint-family collapse (`low-latency` → `latency`
26554        // that dropped the qualifier prefix). Four values sweep the
26555        // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
26556        // canonical adaptive-compression-weight biases the future M4
26557        // placement engine reads.
26558        for hint in [
26559            "data-locality",
26560            "low-latency",
26561            "high-throughput",
26562            "cost-optimized",
26563        ] {
26564            let p = Placement {
26565                estrategia: PlacementStrategy::Replicated,
26566                clusters: vec!["rio".into()],
26567                affinity: Some(hint.into()),
26568                shard_key: None,
26569            };
26570            assert_eq!(
26571                p.affinity(),
26572                Some(hint),
26573                "Placement::affinity must return :placement :affinity \
26574                 verbatim (got {:?}, expected Some({hint:?}))",
26575                p.affinity(),
26576            );
26577            assert_eq!(
26578                p.affinity(),
26579                p.affinity.as_deref(),
26580                "Placement::affinity must byte-equal the .affinity \
26581                 field's `.as_deref()` projection",
26582            );
26583        }
26584    }
26585
26586    #[test]
26587    fn placement_affinity_none_when_field_is_none() {
26588        // The absent-`:affinity` arm of the per-`:placement`
26589        // M3-Adaptive-compression-hint accessor pin: when the typed
26590        // slot is absent — the canonical shape of an Aplicacao that
26591        // leaves the compression weighting up to the placement engine's
26592        // cluster-default arm — [`Placement::affinity`] must return
26593        // `None`. Pins against a future silent detour that projected
26594        // the absent slot to a `Some("")` empty-string default (the
26595        // canonical `Option<String>` → `String` collapse footgun the
26596        // sibling M2 [`crate::LimitsSpec::is_empty`] /
26597        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
26598        // already guard on the peer M2 typed-slot surfaces), a
26599        // `Some("None")` stringified-None round-trip, a `Some` arm
26600        // whose contents were derived from a sibling slot (an
26601        // accidental fallback to `estrategia.as_str()` that read the
26602        // strategy discriminator into the hint axis), or a
26603        // `Some("default")` implicit-default that would silently biases
26604        // the routing without the author having written one. Three
26605        // placements sweep the accept-set every `validate`-passing
26606        // `:affinity None` shape lands on — one per PlacementStrategy
26607        // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
26608        // with a shard-key), since `:affinity` is orthogonal to
26609        // `:estrategia` in the typed grammar.
26610        for (estrategia, shard_key) in [
26611            (PlacementStrategy::SingleNode, None),
26612            (PlacementStrategy::Replicated, None),
26613            (PlacementStrategy::Sharded, Some("tenantId".to_string())),
26614        ] {
26615            let p = Placement {
26616                estrategia,
26617                clusters: vec!["rio".into()],
26618                affinity: None,
26619                shard_key,
26620            };
26621            assert!(
26622                p.affinity().is_none(),
26623                "Placement::affinity must return None when the typed \
26624                 slot is absent under :estrategia {estrategia:?} (got {:?})",
26625                p.affinity(),
26626            );
26627            assert_eq!(
26628                p.affinity(),
26629                p.affinity.as_deref(),
26630                "Placement::affinity must byte-equal the .affinity \
26631                 field's `.as_deref()` projection in the absent arm",
26632            );
26633        }
26634    }
26635
26636    #[test]
26637    fn placement_affinity_borrows_from_affinity_storage() {
26638        // The borrow-not-copy pin: [`Placement::affinity`] must return
26639        // an `Option<&str>` whose `Some` arm borrows from the typed
26640        // slot's own [`String`] storage — same-address invariant with
26641        // `p.affinity.as_deref().unwrap()`. Pins against a future
26642        // silent detour that allocated a fresh `String`
26643        // (`self.affinity.clone().map(...)` in the body would type-
26644        // check but silently drop the borrow, and every downstream
26645        // consumer that assumed the returned slice outlives `&self`
26646        // would break on a stale-reference use-after-free — the
26647        // [`AplicacaoSpec::validate_placement`] per-hint value-shape
26648        // gate reads the accessor's `&str` return through the
26649        // [`validate_placement_affinity`] `&str` parameter and would
26650        // silently misbehave if this accessor produced a detached
26651        // copy). Peer of the sibling per-`:placement`
26652        // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
26653        // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
26654        // extends the discipline onto the sibling per-`:placement`
26655        // M3-Adaptive-compression-hint arm.
26656        let p = Placement {
26657            estrategia: PlacementStrategy::Replicated,
26658            clusters: vec!["rio".into()],
26659            affinity: Some("data-locality".into()),
26660            shard_key: None,
26661        };
26662        let hint = p.affinity().expect("Some arm");
26663        let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
26664        assert_eq!(
26665            hint.as_ptr(),
26666            storage_slice.as_ptr(),
26667            "Placement::affinity must borrow from the .affinity \
26668             String's backing storage — a fresh allocation here means \
26669             the accessor no longer names the substrate-primitive typed \
26670             dispatch and every downstream consumer would silently \
26671             carry a detached copy",
26672        );
26673        assert_eq!(
26674            hint.len(),
26675            storage_slice.len(),
26676            "Placement::affinity and .affinity.as_deref() must byte-\
26677             equal in length as well as in address",
26678        );
26679    }
26680
26681    #[test]
26682    fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
26683        // The canonical per-`:placement` distribution-strategy-scalar
26684        // pin: [`Placement::estrategia`] must return the `:placement
26685        // :estrategia` field verbatim as a [`PlacementStrategy`],
26686        // `Copy`-projected from the typed slot's own `PlacementStrategy`
26687        // storage across every variant in the closed accept-set
26688        // (`SingleNode` — Erlang/OTP distributed-app takeover;
26689        // `Replicated` — active-active across every named cluster;
26690        // `Sharded` — Akka-style hash-keyed entity distribution). Pins
26691        // against a future silent detour that re-derived the strategy
26692        // from a peer axis (an accidental fallback to
26693        // `if shard_key.is_some() { Sharded } else { Replicated }`
26694        // collapse that read the shard-key axis into the strategy
26695        // discriminator), a variant remap the operator authors on one
26696        // consumer without the other, or a stale-derive detour that
26697        // substituted [`PlacementStrategy::default`] when the field
26698        // held any explicit variant (which would silently collapse the
26699        // distinction between "author explicitly declared `:estrategia
26700        // Replicated`" and "author omitted the slot and inherited the
26701        // default" the future per-cluster override slot depends on).
26702        // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
26703        // pin on the `Copy`-return `u16` scalar axis — same "the
26704        // substrate-primitive accessor must byte-equal the raw field
26705        // access verbatim across every author-declared value" discipline
26706        // extended onto the per-`:placement` distribution-strategy
26707        // `Copy`-composite-enum scalar axis.
26708        for estrategia in [
26709            PlacementStrategy::SingleNode,
26710            PlacementStrategy::Replicated,
26711            PlacementStrategy::Sharded,
26712        ] {
26713            // Route the paired `:shard-key` fixture-builder through the
26714            // typed cross-slot invariant predicate
26715            // [`PlacementStrategy::requires_shard_key`] rather than the
26716            // [`gen_platform::IsVariant`]-derived [`PlacementStrategy::is_sharded`]
26717            // arm-identity predicate — same discipline the sibling
26718            // `placement_strategy_variants_round_trip` fixture builder now
26719            // reads through.
26720            let shard_key = estrategia
26721                .requires_shard_key()
26722                .then(|| "tenantId".to_string());
26723            let p = Placement {
26724                estrategia,
26725                clusters: vec!["rio".into()],
26726                affinity: None,
26727                shard_key,
26728            };
26729            assert_eq!(
26730                p.estrategia(),
26731                estrategia,
26732                "Placement::estrategia must return :placement :estrategia \
26733                 verbatim (got {:?}, expected {estrategia:?})",
26734                p.estrategia(),
26735            );
26736            assert_eq!(
26737                p.estrategia(),
26738                p.estrategia,
26739                "Placement::estrategia accessor and .estrategia field \
26740                 access must byte-equal — the accessor is the substrate-\
26741                 primitive typed dispatch every downstream distribution-\
26742                 strategy consumer must route through",
26743            );
26744        }
26745    }
26746
26747    #[test]
26748    fn validate_placement_reads_through_lifted_estrategia_accessor() {
26749        // Three-consumer coherence pin: the
26750        // [`AplicacaoSpec::validate_placement`]
26751        // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
26752        // `estrategia:` field (which reads through
26753        // [`Placement::estrategia`] to name the strategy the empty
26754        // `:clusters` list was declared against), the same method's
26755        // `Sharded ↔ non-Sharded` `match` partition dispatch (which
26756        // reads through [`Placement::estrategia`] to fan across the
26757        // shape-gate cascades), and the non-`Sharded`-arm
26758        // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
26759        // `estrategia:` field (which reads through
26760        // [`Placement::estrategia`] to name the strategy the declared-
26761        // but-inert `:shard-key` was authored under) must all key off
26762        // the lifted accessor, so any future rebrand on the typed
26763        // slot's reader shape lands at exactly one place. Pins the
26764        // three-site coherence by exercising each error surface end-
26765        // to-end and asserting the surfaced `estrategia:` field byte-
26766        // equals the accessor's return. Peer of the sibling per-
26767        // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
26768        // pin on the M3 mesh-slot `Copy`-return scalar axis.
26769
26770        // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
26771        // whose `estrategia:` field must byte-equal the accessor's return
26772        // for every variant in the closed accept-set.
26773        for estrategia in [
26774            PlacementStrategy::SingleNode,
26775            PlacementStrategy::Replicated,
26776            PlacementStrategy::Sharded,
26777        ] {
26778            let mut spec = three_member_spec();
26779            spec.placement.estrategia = estrategia;
26780            spec.placement.clusters = Vec::new();
26781            // Route the paired `:shard-key` spec-mutator through the typed
26782            // cross-slot invariant predicate
26783            // [`PlacementStrategy::requires_shard_key`] rather than the
26784            // [`gen_platform::IsVariant`]-derived
26785            // [`PlacementStrategy::is_sharded`] arm-identity predicate —
26786            // same discipline the sibling
26787            // `placement_strategy_variants_round_trip` and
26788            // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
26789            // fixture builders now read through.
26790            spec.placement.shard_key = estrategia
26791                .requires_shard_key()
26792                .then(|| "tenantId".to_string());
26793            let err = spec.validate().unwrap_err();
26794            match err {
26795                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
26796                    assert_eq!(
26797                        e,
26798                        spec.placement.estrategia(),
26799                        "PlacementWithoutClusters.estrategia must byte-equal \
26800                         Placement::estrategia() — the error carrier reads \
26801                         through the lifted accessor",
26802                    );
26803                }
26804                other => panic!(
26805                    "expected PlacementWithoutClusters, got {other:?} for \
26806                     estrategia={estrategia:?}"
26807                ),
26808            }
26809        }
26810
26811        // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
26812        // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
26813        // must byte-equal the accessor's return for both non-`Sharded`
26814        // strategies.
26815        for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
26816            let mut spec = three_member_spec();
26817            spec.placement.estrategia = estrategia;
26818            spec.placement.shard_key = Some("tenantId".into());
26819            let err = spec.validate().unwrap_err();
26820            match err {
26821                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
26822                    assert_eq!(
26823                        e,
26824                        spec.placement.estrategia(),
26825                        "ShardKeyOnNonSharded.estrategia must byte-equal \
26826                         Placement::estrategia() — the non-Sharded-arm \
26827                         refusal reads through the lifted accessor",
26828                    );
26829                }
26830                other => panic!(
26831                    "expected ShardKeyOnNonSharded, got {other:?} for \
26832                     estrategia={estrategia:?}"
26833                ),
26834            }
26835        }
26836    }
26837
26838    // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
26839    //
26840    // The [`Placement::clusters`] accessor lift is the second slice-return
26841    // (`&[T]`) accessor on any typed slot — sibling to the seed M2
26842    // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
26843    // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
26844    // below cover (1) the accessor's byte-equal projection against the raw
26845    // field access across the empty / singleton / cohort fixtures the
26846    // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
26847    // and the per-cluster validate loop fan between, and (2) the two-
26848    // consumer coherence of the paired pre-flight refusal probe and the
26849    // per-cluster validate loop routing through the accessor on both arms.
26850
26851    #[test]
26852    fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
26853        // The canonical per-`:placement` cluster-pool-scalar-shape pin:
26854        // [`Placement::clusters`] must return the `:placement :clusters`
26855        // typed `Vec<String>` verbatim as a `&[String]` slice-view over
26856        // the same backing buffer the raw `self.clusters.as_slice()`
26857        // field access borrows from, byte-equal across every
26858        // representative fixture in the accept-set — the empty slice
26859        // (the pre-validation sentinel every
26860        // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
26861        // the singleton slice (the minimal `SingleNode`-shape cohort),
26862        // and multi-entry cohorts (the peer `Replicated` / `Sharded`
26863        // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
26864        //
26865        // Pins against a future silent detour that returned
26866        // `&Vec<String>` (which would type-check but leak the storage-
26867        // side `Vec`'s grow/push/reserve surface no consumer of the
26868        // typed view reaches for), a fresh-allocated `Vec<String>` copy
26869        // (which would type-check via a coercion but silently break
26870        // every downstream caller that relied on the slice sharing the
26871        // backing buffer's identity), or an out-of-order or length-
26872        // drifted projection (which would silently split the paired
26873        // pre-flight `.is_empty()` refusal probe's input from the per-
26874        // cluster validate loop's traversal input).
26875        //
26876        // Peer of the sibling M2
26877        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
26878        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
26879        // `:supervisor` static-child-list axis, extended onto the M3
26880        // per-`:placement` distribution-target-list `Vec`-carry axis.
26881        let fixtures: Vec<Vec<String>> = vec![
26882            Vec::new(),
26883            vec!["rio".into()],
26884            vec!["rio".into(), "mar".into()],
26885            vec!["rio".into(), "mar".into(), "plo".into()],
26886        ];
26887        for clusters in fixtures {
26888            let p = Placement {
26889                clusters: clusters.clone(),
26890                ..Placement::default()
26891            };
26892            assert_eq!(
26893                p.clusters(),
26894                clusters.as_slice(),
26895                "Placement::clusters must return :placement :clusters \
26896                 verbatim (got {:?}, expected {:?})",
26897                p.clusters(),
26898                clusters.as_slice(),
26899            );
26900            assert_eq!(
26901                p.clusters(),
26902                p.clusters.as_slice(),
26903                "Placement::clusters accessor and .clusters.as_slice() \
26904                 field access must byte-equal — the accessor is the \
26905                 substrate-primitive typed dispatch every downstream \
26906                 cluster-pool consumer must route through",
26907            );
26908            assert_eq!(
26909                p.clusters().len(),
26910                p.clusters.len(),
26911                "Placement::clusters().len() must byte-equal \
26912                 self.clusters.len() — a length-drift would silently \
26913                 split the paired pre-flight `.is_empty()` refusal \
26914                 probe input from the per-cluster validate loop's \
26915                 traversal input",
26916            );
26917        }
26918    }
26919
26920    #[test]
26921    fn validate_placement_reads_through_lifted_clusters_accessor() {
26922        // Two-consumer coherence pin: the
26923        // [`AplicacaoSpec::validate_placement`] pre-flight
26924        // `self.placement.clusters().is_empty()` refusal probe (which
26925        // must trip [`AplicacaoError::PlacementWithoutClusters`] when
26926        // the accessor projects the empty slice) and the per-cluster
26927        // validate loop's `for c in self.placement.clusters()`
26928        // traversal (which must reach every entry in the same order
26929        // the accessor projects, so both the per-entry value-shape
26930        // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
26931        // and the duplicate-detection HashSet insert that trips
26932        // [`AplicacaoError::PlacementClusterDuplicate`] key off the
26933        // accessor's projection) must both key off the lifted
26934        // accessor, so any future rebrand on the typed slot's reader
26935        // shape lands at exactly one place. Pins the two-site
26936        // coherence by exercising each production consumer end-to-end:
26937        // (1) the `PlacementWithoutClusters` refusal under the empty
26938        // slice, (2) the `PlacementClusterInvalid` refusal fires on
26939        // the second entry of a two-cluster cohort whose head is
26940        // valid but tail is not (which requires the loop to reach the
26941        // second entry through the accessor), and (3) the
26942        // `PlacementClusterDuplicate` refusal fires on the second
26943        // entry of a two-cluster cohort that shares a name (which
26944        // requires the loop to reach both entries — a first-entry-only
26945        // projection would silently pass since the dedup HashSet has
26946        // room for the first insert).
26947        //
26948        // Peer of the sibling M2
26949        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
26950        // (bc92bce) coherence pin on the per-`:supervisor` static-
26951        // child-list axis, extended onto the M3 per-`:placement`
26952        // distribution-target-list `Vec`-carry axis.
26953
26954        // (1) Pre-flight `.is_empty()` probe: the empty slice must
26955        // trip `PlacementWithoutClusters`.
26956        let mut spec = three_member_spec();
26957        spec.placement.clusters = Vec::new();
26958        match spec.validate().unwrap_err() {
26959            AplicacaoError::PlacementWithoutClusters { .. } => {}
26960            other => panic!("expected PlacementWithoutClusters, got {other:?}"),
26961        }
26962        assert!(
26963            spec.placement.clusters().is_empty(),
26964            "the pre-flight refusal input must be the empty slice per \
26965             the accessor's projection",
26966        );
26967
26968        // (2) Per-cluster validate loop: a two-cluster cohort with an
26969        // invalid tail entry must trip `PlacementClusterInvalid` on
26970        // the tail — the loop must reach the second entry through
26971        // the accessor.
26972        let mut spec = three_member_spec();
26973        spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
26974        match spec.validate().unwrap_err() {
26975            AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
26976                assert_eq!(
26977                    cluster, "BAD_CLUSTER",
26978                    "PlacementClusterInvalid.cluster must carry the \
26979                     tail entry the loop reached through the accessor",
26980                );
26981            }
26982            other => panic!("expected PlacementClusterInvalid, got {other:?}"),
26983        }
26984        assert_eq!(
26985            spec.placement.clusters().len(),
26986            2,
26987            "the per-cluster validate loop's traversal input must be \
26988             a two-element slice per the accessor's projection",
26989        );
26990
26991        // (3) Per-cluster validate loop: a two-cluster cohort that
26992        // shares a name must trip `PlacementClusterDuplicate` on the
26993        // second entry — the loop must reach both entries through the
26994        // accessor for the dedup HashSet's second insert to collide.
26995        let mut spec = three_member_spec();
26996        spec.placement.clusters = vec!["rio".into(), "rio".into()];
26997        match spec.validate().unwrap_err() {
26998            AplicacaoError::PlacementClusterDuplicate { cluster } => {
26999                assert_eq!(
27000                    cluster, "rio",
27001                    "PlacementClusterDuplicate.cluster must carry the \
27002                     shared cluster name verbatim",
27003                );
27004            }
27005            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
27006        }
27007        assert_eq!(
27008            spec.placement.clusters().len(),
27009            2,
27010            "the per-cluster validate loop's traversal input must be \
27011             a two-element slice per the accessor's projection",
27012        );
27013    }
27014
27015    #[test]
27016    fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
27017        // The canonical per-`:membros` member-list-slice-shape pin:
27018        // [`AplicacaoSpec::membros`] must return the `:membros` typed
27019        // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
27020        // same backing buffer the raw `self.membros.as_slice()` field
27021        // access borrows from, byte-equal across every representative
27022        // fixture in the accept-set — the empty slice (the pre-
27023        // validation sentinel every [`AplicacaoError::NoMembros`]
27024        // refusal keys off), the singleton slice (the minimal one-
27025        // Servico Aplicacao shape), and multi-entry cohorts (the peer
27026        // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
27027        // load-bearing identity of the application graph).
27028        //
27029        // Pins against a future silent detour that returned
27030        // `&Vec<Membro>` (which would type-check but leak the storage-
27031        // side `Vec`'s grow/push/reserve surface no consumer of the
27032        // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
27033        // (which would type-check via a coercion but silently break
27034        // every downstream caller that relied on the slice sharing the
27035        // backing buffer's identity), or an out-of-order or length-
27036        // drifted projection (which would silently split the paired
27037        // `HashSet<&str>` name-set seed's collect input from the
27038        // pre-flight `.is_empty()` refusal probe's input from the per-
27039        // member validate loop's traversal input from the
27040        // programs.yaml emitter's per-entry fan-out loop's input from
27041        // the `feira app graph` per-member print traversal's input).
27042        //
27043        // Peer of the sibling M2
27044        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
27045        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
27046        // `:supervisor` static-child-list axis and the sibling M3
27047        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
27048        // (a6e18d7) `&[String]` byte-equal pin on the per-
27049        // `:placement` distribution-target-list axis — extends the
27050        // slice-return-accessor byte-equal-projection discipline onto
27051        // the outermost M3 mesh-slot type's per-Aplicacao member-list
27052        // `Vec`-carry axis.
27053        let fixtures: Vec<Vec<Membro>> = vec![
27054            Vec::new(),
27055            vec![membro("catalog", "^0.1")],
27056            vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
27057            vec![
27058                membro("catalog", "^0.1"),
27059                membro("cart", "^0.1"),
27060                membro("payment", "^0.2"),
27061            ],
27062        ];
27063        for membros in fixtures {
27064            let s = AplicacaoSpec {
27065                membros: membros.clone(),
27066                contratos: Vec::new(),
27067                politicas: MeshPolicy::default(),
27068                placement: Placement::default(),
27069                entrada: None,
27070            };
27071            assert_eq!(
27072                s.membros(),
27073                membros.as_slice(),
27074                "AplicacaoSpec::membros must return :membros verbatim \
27075                 (got {:?}, expected {:?})",
27076                s.membros(),
27077                membros.as_slice(),
27078            );
27079            assert_eq!(
27080                s.membros(),
27081                s.membros.as_slice(),
27082                "AplicacaoSpec::membros accessor and .membros.as_slice() \
27083                 field access must byte-equal — the accessor is the \
27084                 substrate-primitive typed dispatch every downstream \
27085                 member-list consumer must route through",
27086            );
27087            assert_eq!(
27088                s.membros().len(),
27089                s.membros.len(),
27090                "AplicacaoSpec::membros().len() must byte-equal \
27091                 self.membros.len() — a length-drift would silently \
27092                 split the paired `HashSet<&str>` name-set seed's \
27093                 collect input from the pre-flight `.is_empty()` \
27094                 refusal probe input from the per-member validate \
27095                 loop's traversal input",
27096            );
27097        }
27098    }
27099
27100    #[test]
27101    fn validate_reads_through_lifted_membros_accessor() {
27102        // Three-consumer coherence pin: the
27103        // [`AplicacaoSpec::validate_membros`] pre-flight
27104        // `self.membros().is_empty()` refusal probe (which must trip
27105        // [`AplicacaoError::NoMembros`] when the accessor projects the
27106        // empty slice), the same method's per-member validate loop's
27107        // `for m in self.membros()` traversal (which must reach every
27108        // entry in the same order the accessor projects, so both the
27109        // per-entry empty-`:caixa` gate that trips
27110        // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
27111        // detection `insert_first_seen` that trips
27112        // [`AplicacaoError::MembroDuplicate`] key off the accessor's
27113        // projection), and the peer [`AplicacaoSpec::validate`]'s
27114        // `HashSet<&str>` name-set seed's
27115        // `self.membros().iter().map(Membro::nome).collect()` collect
27116        // input (which every `:contratos` `:de` / `:para` membership
27117        // lookup rejects an unknown name against) must all three key
27118        // off the lifted accessor, so any future rebrand on the typed
27119        // slot's reader shape lands at exactly one place. Pins the
27120        // three-site coherence by exercising each production consumer
27121        // end-to-end: (1) the `NoMembros` refusal under the empty
27122        // slice, (2) the `MembroCaixaEmpty` refusal fires on the
27123        // second entry of a two-member cohort whose head is valid but
27124        // tail has an empty `:caixa` (which requires the loop to
27125        // reach the second entry through the accessor), and (3) the
27126        // `MembroDuplicate` refusal fires on the second entry of a
27127        // two-member cohort that shares a `:caixa` name (which
27128        // requires the loop to reach both entries through the
27129        // accessor for the dedup HashSet's second insert to collide).
27130        //
27131        // Peer of the sibling M2
27132        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
27133        // (bc92bce) coherence pin on the per-`:supervisor` static-
27134        // child-list axis and the sibling M3
27135        // `validate_placement_reads_through_lifted_clusters_accessor`
27136        // (a6e18d7) coherence pin on the per-`:placement` distribution-
27137        // target-list axis — extends the slice-return-accessor
27138        // multi-consumer coherence discipline onto the outermost M3
27139        // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
27140
27141        // (1) Pre-flight `.is_empty()` probe: the empty slice must
27142        // trip `NoMembros`.
27143        let mut spec = three_member_spec();
27144        spec.membros = Vec::new();
27145        assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
27146        assert!(
27147            spec.membros().is_empty(),
27148            "the pre-flight refusal input must be the empty slice per \
27149             the accessor's projection",
27150        );
27151
27152        // (2) Per-member validate loop: a two-member cohort with an
27153        // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
27154        // the tail — the loop must reach the second entry through
27155        // the accessor.
27156        let mut spec = three_member_spec();
27157        spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
27158        assert_eq!(
27159            spec.validate().unwrap_err(),
27160            AplicacaoError::MembroCaixaEmpty,
27161        );
27162        assert_eq!(
27163            spec.membros().len(),
27164            2,
27165            "the per-member validate loop's traversal input must be \
27166             a two-element slice per the accessor's projection",
27167        );
27168
27169        // (3) Per-member validate loop: a two-member cohort that
27170        // shares a `:caixa` name must trip `MembroDuplicate` on the
27171        // second entry — the loop must reach both entries through the
27172        // accessor for the dedup HashSet's second insert to collide.
27173        let mut spec = three_member_spec();
27174        spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
27175        match spec.validate().unwrap_err() {
27176            AplicacaoError::MembroDuplicate { caixa } => {
27177                assert_eq!(
27178                    caixa, "catalog",
27179                    "MembroDuplicate.caixa must carry the shared \
27180                     member name verbatim",
27181                );
27182            }
27183            other => panic!("expected MembroDuplicate, got {other:?}"),
27184        }
27185        assert_eq!(
27186            spec.membros().len(),
27187            2,
27188            "the per-member validate loop's traversal input must be \
27189             a two-element slice per the accessor's projection",
27190        );
27191    }
27192
27193    #[test]
27194    fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
27195        // The canonical per-`:contratos` contract-list-slice-shape pin:
27196        // [`AplicacaoSpec::contratos`] must return the `:contratos`
27197        // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
27198        // slice-view over the same backing buffer the raw
27199        // `self.contratos.as_slice()` field access borrows from, byte-
27200        // equal across every representative fixture in the accept-set —
27201        // the empty slice (the pre-validation "internal-only mesh" shape
27202        // an Aplicacao whose members exchange no typed edges renders
27203        // through), the singleton slice (the minimal one-edge Aplicacao
27204        // shape), and multi-entry cohorts (the peer multi-edge shapes
27205        // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
27206        // of the application graph).
27207        //
27208        // Pins against a future silent detour that returned
27209        // `&Vec<WitContract>` (which would type-check but leak the
27210        // storage-side `Vec`'s grow/push/reserve surface no consumer of
27211        // the typed view reaches for), a fresh-allocated
27212        // `Vec<WitContract>` copy (which would type-check via a coercion
27213        // but silently break every downstream caller that relied on the
27214        // slice sharing the backing buffer's identity), or an out-of-
27215        // order or length-drifted projection (which would silently split
27216        // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
27217        // seed's traversal input from the `detect_sync_cycles` per-edge
27218        // adjacency-list seed's traversal input from the
27219        // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
27220        // BTreeMap grouping loop's traversal input from the
27221        // `feira app graph` per-contract print traversal's input).
27222        //
27223        // Peer of the immediately-adjacent sibling M3
27224        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
27225        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
27226        // node-list axis, the sibling M3
27227        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
27228        // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
27229        // distribution-target-list axis, and the sibling M2
27230        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
27231        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
27232        // `:supervisor` static-child-list axis — extends the slice-
27233        // return-accessor byte-equal-projection discipline onto the
27234        // outermost M3 mesh-slot type's per-Aplicacao contract-list
27235        // `Vec`-carry axis, closing the last unlifted per-
27236        // `AplicacaoSpec` `Vec`-carry axis.
27237        let fixtures: Vec<Vec<WitContract>> = vec![
27238            Vec::new(),
27239            vec![contract_http("cart", "catalog", "/products/:id")],
27240            vec![
27241                contract_http("cart", "catalog", "/products/:id"),
27242                contract_http("cart", "payment", "/charge"),
27243            ],
27244            vec![
27245                contract_http("cart", "catalog", "/products/:id"),
27246                contract_http("cart", "payment", "/charge"),
27247                contract_http("payment", "catalog", "/audit"),
27248            ],
27249        ];
27250        for contratos in fixtures {
27251            let s = AplicacaoSpec {
27252                membros: vec![
27253                    membro("catalog", "^0.1"),
27254                    membro("cart", "^0.1"),
27255                    membro("payment", "^0.2"),
27256                ],
27257                contratos: contratos.clone(),
27258                politicas: MeshPolicy::default(),
27259                placement: Placement::default(),
27260                entrada: None,
27261            };
27262            assert_eq!(
27263                s.contratos(),
27264                contratos.as_slice(),
27265                "AplicacaoSpec::contratos must return :contratos verbatim \
27266                 (got {:?}, expected {:?})",
27267                s.contratos(),
27268                contratos.as_slice(),
27269            );
27270            assert_eq!(
27271                s.contratos(),
27272                s.contratos.as_slice(),
27273                "AplicacaoSpec::contratos accessor and \
27274                 .contratos.as_slice() field access must byte-equal — \
27275                 the accessor is the substrate-primitive typed dispatch \
27276                 every downstream contract-list consumer must route \
27277                 through",
27278            );
27279            assert_eq!(
27280                s.contratos().len(),
27281                s.contratos.len(),
27282                "AplicacaoSpec::contratos().len() must byte-equal \
27283                 self.contratos.len() — a length-drift would silently \
27284                 split the paired per-edge validate-loop's traversal \
27285                 input from the sync-cycle adjacency-list seed's \
27286                 traversal input from the cilium_network_policies \
27287                 per-`(:de, :para)` BTreeMap grouping loop's traversal \
27288                 input from the `feira app graph` per-contract print \
27289                 traversal's input",
27290            );
27291        }
27292    }
27293
27294    #[test]
27295    fn validate_reads_through_lifted_contratos_accessor() {
27296        // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
27297        // per-`:contratos` validate-loop's `for c in self.contratos()`
27298        // traversal (which must reach every entry in the same order the
27299        // accessor projects, so both the per-entry
27300        // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
27301        // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
27302        // dedup `HashSet` insert key off the accessor's projection),
27303        // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
27304        // `for c in self.contratos()` adjacency-list seed (which drives
27305        // the sync-subgraph deadlock-detection gate via
27306        // [`AplicacaoError::SyncCycle`]), and the peer
27307        // [`caixa_mesh::cilium_network_policies`]'s
27308        // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
27309        // grouping loop (which drives the per-CNP fan-out) must all
27310        // three key off the lifted accessor, so any future rebrand on
27311        // the typed slot's reader shape lands at exactly one place. Pins
27312        // the three-site coherence by exercising the two caixa-core
27313        // production consumers end-to-end: (1) the empty-`:contratos`
27314        // slice must validate without a per-edge diagnostic (the
27315        // per-edge loop is a no-op under the empty projection), (2) the
27316        // `ContratoMemberMissing` refusal fires on the second entry of a
27317        // two-edge cohort whose head references a valid member but tail
27318        // references a phantom name (which requires the loop to reach
27319        // the second entry through the accessor), and (3) the
27320        // `SyncCycle` refusal fires on a self-referential two-edge
27321        // cohort through the sync-cycle detector's peer projection
27322        // (which requires the detector to iterate the accessor's
27323        // projection to add the back-edge to its adjacency list).
27324        //
27325        // Peer of the sibling M3
27326        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
27327        // three-consumer coherence pin on the per-`:membros` node-list
27328        // axis and the sibling M3
27329        // `validate_placement_reads_through_lifted_clusters_accessor`
27330        // (a6e18d7) coherence pin on the per-`:placement` distribution-
27331        // target-list axis — extends the slice-return-accessor multi-
27332        // consumer coherence discipline onto the outermost M3 mesh-slot
27333        // type's per-Aplicacao contract-list `Vec`-carry axis.
27334
27335        // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
27336        // and no per-edge diagnostic surfaces. Validate succeeds on
27337        // the well-formed `:membros` head.
27338        let mut spec = three_member_spec();
27339        spec.contratos = Vec::new();
27340        assert!(
27341            spec.validate().is_ok(),
27342            "empty :contratos must validate — the per-edge loop is a \
27343             no-op under the accessor's empty projection",
27344        );
27345        assert!(
27346            spec.contratos().is_empty(),
27347            "the per-edge validate loop's traversal input must be the \
27348             empty slice per the accessor's projection",
27349        );
27350
27351        // (2) Per-edge validate loop: a two-edge cohort whose tail
27352        // references a phantom `:para` member must trip
27353        // `ContratoMemberMissing` on the tail — the loop must reach
27354        // the second entry through the accessor for the membership
27355        // lookup to fail on the phantom name.
27356        let mut spec = three_member_spec();
27357        spec.contratos = vec![
27358            contract_http("cart", "catalog", "/products/:id"),
27359            contract_http("cart", "phantom", "/x"),
27360        ];
27361        let err = spec.validate().unwrap_err();
27362        assert!(
27363            matches!(
27364                err,
27365                AplicacaoError::ContratoMemberMissing { ref caixa }
27366                    if caixa == "phantom"
27367            ),
27368            "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
27369        );
27370        assert_eq!(
27371            spec.contratos().len(),
27372            2,
27373            "the per-edge validate loop's traversal input must be \
27374             a two-element slice per the accessor's projection",
27375        );
27376
27377        // (3) Sync-cycle detector: a two-edge synchronous cohort
27378        // whose second edge closes the sync-subgraph back onto the
27379        // first must trip [`AplicacaoError::ContratoCycle`] — the
27380        // detector must iterate the accessor's projection to add
27381        // both edges to its adjacency list, so a length-drift on
27382        // the accessor's projection would silently disagree with
27383        // the sync-cycle detector on which edge closes the loop.
27384        // Peer projection to the `validate` per-edge loop above:
27385        // the sync-cycle detector routes through the same lifted
27386        // accessor, so a rebrand of the reader shape lands at one
27387        // place. Uses a two-edge cohort (cart → catalog → cart)
27388        // because the per-edge `ContratoSelfLoop` gate fires before
27389        // the sync-cycle detector on a single self-referential edge
27390        // (`cart → cart`) — the cycle-detector's input must be a
27391        // multi-edge cohort for its per-edge traversal input to be
27392        // observably wider than the per-edge validate loop's input.
27393        let mut spec = three_member_spec();
27394        spec.contratos = vec![
27395            contract_http("cart", "catalog", "/products/:id"),
27396            contract_http("catalog", "cart", "/callback"),
27397        ];
27398        let err = spec.validate().unwrap_err();
27399        assert!(
27400            matches!(err, AplicacaoError::ContratoCycle { .. }),
27401            "expected ContratoCycle from the sync-cycle detector on a \
27402             two-edge back-edge cohort, got {err:?}",
27403        );
27404        assert_eq!(
27405            spec.contratos().len(),
27406            2,
27407            "the sync-cycle detector's traversal input must be a \
27408             two-element slice per the accessor's projection",
27409        );
27410    }
27411
27412    #[test]
27413    fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
27414        // The canonical per-`:politicas` outer-composite-reference-shape
27415        // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
27416        // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
27417        // the same backing storage the raw `&self.politicas` field
27418        // access borrows from, byte-equal across every representative
27419        // fixture in the accept-set — the default `MeshPolicy` (the
27420        // author-empty "no policy on any axis" shape whose
27421        // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
27422        // shapes carrying one axis at a time
27423        // (`{mtls_required, timeout, retries, circuit_breaker,
27424        // rate_limit}` — the minimal five-axis fan-out over the
27425        // per-axis lifted accessor family every downstream mesh-artifact
27426        // emitter dispatches on), and the multi-axis composite (the
27427        // canonical `three_member_spec` fixture's `{timeout, retries,
27428        // mtls_required}` triple — the load-bearing shape every
27429        // Aplicacao-scoped fixture in this suite constructs).
27430        //
27431        // Pins against a future silent detour that returned a fresh-
27432        // cloned `MeshPolicy` copy (which would type-check via a `Clone`
27433        // impl but silently break every downstream caller that relied
27434        // on the reference sharing the composite's backing identity), a
27435        // reference to an operator-resolved overlay (the future
27436        // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
27437        // acknowledges — its resolution must land at exactly this
27438        // accessor body, not silently divert the raw slot away from a
27439        // second consumer), or an axis-shuffled projection (a future
27440        // detour that swapped `timeout` and `retries` through the
27441        // accessor would silently split the paired `validate_politicas`
27442        // per-axis bracket-dispatch's traversal input from the peer
27443        // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
27444        // emitter's fan-out input from the peer
27445        // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
27446        // overlay emitter's fan-out input).
27447        //
27448        // Peer of the sibling M3
27449        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
27450        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
27451        // node-list `Vec`-carry axis and the sibling M3
27452        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
27453        // (0dcc926) `&[WitContract]` byte-equal pin on the per-
27454        // `:contratos` edge-list `Vec`-carry axis — extends the outer-
27455        // accessor byte-equal-projection discipline onto the outermost
27456        // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
27457        // reference axis, the first `&Composite`-return accessor on the
27458        // outer [`AplicacaoSpec`] type.
27459        let fixtures: Vec<MeshPolicy> = vec![
27460            MeshPolicy::default(),
27461            MeshPolicy {
27462                mtls_required: Some(true),
27463                ..MeshPolicy::default()
27464            },
27465            MeshPolicy {
27466                mtls_required: Some(false),
27467                ..MeshPolicy::default()
27468            },
27469            MeshPolicy {
27470                timeout: Some(Duration::from_secs(30)),
27471                ..MeshPolicy::default()
27472            },
27473            MeshPolicy {
27474                retries: Some(3),
27475                ..MeshPolicy::default()
27476            },
27477            MeshPolicy {
27478                circuit_breaker: Some(CircuitBreaker {
27479                    max_failures: 5,
27480                    window: Duration::from_secs(30),
27481                }),
27482                ..MeshPolicy::default()
27483            },
27484            MeshPolicy {
27485                rate_limit: Some(RateLimit {
27486                    rate: 100,
27487                    window: Duration::from_secs(1),
27488                }),
27489                ..MeshPolicy::default()
27490            },
27491            MeshPolicy {
27492                timeout: Some(Duration::from_secs(30)),
27493                retries: Some(3),
27494                mtls_required: Some(true),
27495                ..MeshPolicy::default()
27496            },
27497        ];
27498        for politicas in fixtures {
27499            let s = AplicacaoSpec {
27500                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
27501                contratos: Vec::new(),
27502                politicas: politicas.clone(),
27503                placement: Placement::default(),
27504                entrada: None,
27505            };
27506            assert_eq!(
27507                *s.politicas(),
27508                politicas,
27509                "AplicacaoSpec::politicas must return :politicas verbatim \
27510                 (got {:?}, expected {:?})",
27511                s.politicas(),
27512                politicas,
27513            );
27514            assert!(
27515                std::ptr::eq(s.politicas(), &s.politicas),
27516                "AplicacaoSpec::politicas accessor and &self.politicas \
27517                 field access must borrow the same backing storage — \
27518                 the accessor is the substrate-primitive typed dispatch \
27519                 every downstream mesh-policy composite consumer must \
27520                 route through, and a reference-identity split would \
27521                 silently break every consumer that relied on the \
27522                 borrow sharing the composite's storage",
27523            );
27524            assert_eq!(
27525                s.politicas().is_empty(),
27526                s.politicas.is_empty(),
27527                "AplicacaoSpec::politicas().is_empty() must byte-equal \
27528                 self.politicas.is_empty() — an emptiness-drift would \
27529                 silently split the paired `validate_politicas` \
27530                 per-axis bracket-dispatch's seed from the peer \
27531                 caixa-mesh CNP mTLS-overlay emitter's key from the \
27532                 peer caixa-mesh HTTPRoute timeout+retry overlay \
27533                 emitter's key",
27534            );
27535        }
27536    }
27537
27538    #[test]
27539    fn validate_politicas_reads_through_lifted_politicas_accessor() {
27540        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
27541        // per-axis bracket-dispatch seed (`let p = self.politicas();`,
27542        // followed by the per-axis fan-out `p.timeout()` /
27543        // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
27544        // the lifted axis-level accessor family) must key off the
27545        // lifted outer accessor, so any future rebrand on the typed
27546        // slot's outer-composite reader shape lands at exactly one
27547        // place. Pins the multi-axis coherence by exercising each
27548        // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
27549        // a `Some(Duration::ZERO)` timeout under the outer accessor's
27550        // reference projection, (2) `PolicyRetriesZero` fires on a
27551        // `Some(0)` retries under the same projection, and (3) an
27552        // empty [`MeshPolicy::default`] passes `validate_politicas` —
27553        // the outer accessor's reference-projection reaches every
27554        // per-axis branch without silently short-circuiting any.
27555        //
27556        // Peer of the sibling M3
27557        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
27558        // three-consumer coherence pin on the per-`:membros` node-list
27559        // axis and the sibling M3
27560        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
27561        // three-consumer coherence pin on the per-`:contratos`
27562        // edge-list axis — extends the multi-consumer coherence
27563        // discipline onto the outermost M3 mesh-slot type's per-
27564        // Aplicacao mesh-policy composite-reference axis, the first
27565        // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
27566        // type.
27567
27568        // (1) `PolicyTimeoutZero` refusal under the outer accessor's
27569        // reference projection: a `Some(Duration::ZERO)` timeout must
27570        // trip the zero-floor gate. The bracket-dispatch's first arm
27571        // reads `p.timeout()` on the reference returned by the outer
27572        // accessor.
27573        let mut spec = three_member_spec();
27574        spec.politicas.timeout = Some(Duration::ZERO);
27575        spec.politicas.retries = None;
27576        spec.politicas.circuit_breaker = None;
27577        spec.politicas.rate_limit = None;
27578        assert_eq!(
27579            spec.validate().unwrap_err(),
27580            AplicacaoError::PolicyTimeoutZero,
27581        );
27582        assert!(
27583            std::ptr::eq(spec.politicas(), &spec.politicas),
27584            "the `validate_politicas` per-axis bracket-dispatch's \
27585             traversal input must be the same backing composite the \
27586             accessor's reference projection borrows from",
27587        );
27588
27589        // (2) `PolicyRetriesZero` refusal under the outer accessor's
27590        // reference projection: a `Some(0)` retries must trip the
27591        // zero-floor gate. The bracket-dispatch's second arm reads
27592        // `p.retries()` on the reference returned by the outer accessor.
27593        let mut spec = three_member_spec();
27594        spec.politicas.timeout = None;
27595        spec.politicas.retries = Some(0);
27596        spec.politicas.circuit_breaker = None;
27597        spec.politicas.rate_limit = None;
27598        assert_eq!(
27599            spec.validate().unwrap_err(),
27600            AplicacaoError::PolicyRetriesZero,
27601        );
27602
27603        // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
27604        // — every per-axis arm short-circuits on `None`, so the outer
27605        // accessor's reference projection reaches the fall-through
27606        // `Ok(())` without any per-axis refusal firing.
27607        let mut spec = three_member_spec();
27608        spec.politicas = MeshPolicy::default();
27609        assert!(
27610            spec.validate().is_ok(),
27611            "an empty `MeshPolicy` must pass `validate_politicas` — \
27612             every per-axis arm short-circuits on `None` under the \
27613             outer accessor's reference projection",
27614        );
27615        assert!(
27616            spec.politicas().is_empty(),
27617            "the outer accessor's reference projection must be the \
27618             empty composite per the `MeshPolicy::default()` fixture",
27619        );
27620    }
27621
27622    #[test]
27623    #[allow(clippy::too_many_lines)]
27624    fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
27625        // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
27626        // per-axis bracket-dispatch's `:timeout` and `:retries` arms
27627        // must both key off the lifted axis-level accessors
27628        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
27629        // the peer `:circuit-breaker` / `:rate-limit` arms already
27630        // routing through [`MeshPolicy::circuit_breaker`] /
27631        // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
27632        // per axis on the substrate primitive" shape at the fan-out
27633        // (four axes, four accessors, no raw-field-access site
27634        // anywhere on the bracket-dispatch). Pins the per-axis
27635        // coherence at the accept-set boundaries the bracket carves:
27636        //   1. accessor byte-equal to raw field on every representative
27637        //      accept-set value (`None`, sub-cap, at-cap, past-cap
27638        //      sentinel) — a future accessor drift that no longer
27639        //      shipped the raw slot verbatim would surface here,
27640        //   2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
27641        //      routed through the accessor's projection, proving the
27642        //      first arm reads through the accessor rather than a
27643        //      silent-detour peer-axis field access,
27644        //   3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
27645        //      through the accessor's projection, proving the second
27646        //      arm reads through the accessor,
27647        //   4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
27648        //      passes validate under the accessor projection (paired
27649        //      with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
27650        //      sibling axis), pinning the upper-boundary accept-arm
27651        //      also routes through the accessor.
27652        //
27653        // Peer of the sibling M3
27654        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
27655        // outer-composite-reference coherence pin (which asserts the
27656        // `let p = self.politicas()` seed); extends the discipline onto
27657        // the per-axis fan-out layer that consumes the seed's
27658        // reference. Same shape as
27659        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
27660        // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
27661        // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
27662        // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
27663
27664        // (1) Accessor byte-equal to raw field on the `:timeout` axis
27665        // across the accept-set boundaries the bracket dispatch's
27666        // three-arm gate carves out
27667        // ([`crate::render::require_positive_canonical_bounded_duration`]
27668        // — zero-floor + canonical-form + upper-cap).
27669        for timeout in [
27670            None,
27671            Some(Duration::ZERO),
27672            Some(Duration::from_millis(1)),
27673            Some(POLICY_TIMEOUT_MAX),
27674        ] {
27675            let p = MeshPolicy {
27676                timeout,
27677                ..MeshPolicy::default()
27678            };
27679            assert_eq!(
27680                p.timeout(),
27681                p.timeout,
27682                "MeshPolicy::timeout accessor must byte-equal the raw \
27683                 .timeout field across every accept-set boundary the \
27684                 validate_politicas :timeout arm carves out — a drift \
27685                 here would silently split the validate bracket's arm \
27686                 from the peer caixa-mesh HTTPRoute timeout-overlay \
27687                 emitter's read",
27688            );
27689        }
27690
27691        // (2) Accessor byte-equal to raw field on the `:retries` axis
27692        // across the accept-set boundaries the bracket dispatch's
27693        // two-arm gate carves out
27694        // ([`crate::render::require_positive_bounded_u32`] — zero-floor
27695        // + upper-cap).
27696        for retries in [
27697            None,
27698            Some(0u32),
27699            Some(1u32),
27700            Some(POLICY_RETRIES_MAX),
27701            Some(POLICY_RETRIES_MAX + 1),
27702            Some(u32::MAX),
27703        ] {
27704            let p = MeshPolicy {
27705                retries,
27706                ..MeshPolicy::default()
27707            };
27708            assert_eq!(
27709                p.retries(),
27710                p.retries,
27711                "MeshPolicy::retries accessor must byte-equal the raw \
27712                 .retries field across every accept-set boundary the \
27713                 validate_politicas :retries arm carves out — a drift \
27714                 here would silently split the validate bracket's arm \
27715                 from the peer caixa-mesh HTTPRoute retry-overlay \
27716                 emitter's read",
27717            );
27718        }
27719
27720        // (3) `PolicyTimeoutZero` fires on the accessor-projected
27721        // zero-floor boundary. A silent detour that no longer read
27722        // through `p.timeout()` (a peer-axis field read, an accidental
27723        // Option::and-then chain that collapsed the None arm to Some,
27724        // an accessor rebrand that clamped the return through the
27725        // upper cap) would fail to refuse here.
27726        let mut spec = three_member_spec();
27727        spec.politicas.timeout = Some(Duration::ZERO);
27728        spec.politicas.retries = None;
27729        spec.politicas.circuit_breaker = None;
27730        spec.politicas.rate_limit = None;
27731        assert_eq!(
27732            spec.politicas().timeout(),
27733            Some(Duration::ZERO),
27734            "the accessor projection must reflect the fixture's \
27735             `Some(Duration::ZERO)` :timeout verbatim",
27736        );
27737        assert_eq!(
27738            spec.validate().unwrap_err(),
27739            AplicacaoError::PolicyTimeoutZero,
27740            "the validate_politicas :timeout zero-floor arm must fire \
27741             through the lifted accessor's projection — a silent \
27742             detour to a peer-axis field would fail to refuse",
27743        );
27744
27745        // (4) `PolicyRetriesZero` fires on the accessor-projected
27746        // zero-floor boundary on the sibling `:retries` axis.
27747        let mut spec = three_member_spec();
27748        spec.politicas.timeout = None;
27749        spec.politicas.retries = Some(0);
27750        spec.politicas.circuit_breaker = None;
27751        spec.politicas.rate_limit = None;
27752        assert_eq!(
27753            spec.politicas().retries(),
27754            Some(0),
27755            "the accessor projection must reflect the fixture's \
27756             `Some(0)` :retries verbatim",
27757        );
27758        assert_eq!(
27759            spec.validate().unwrap_err(),
27760            AplicacaoError::PolicyRetriesZero,
27761            "the validate_politicas :retries zero-floor arm must fire \
27762             through the lifted accessor's projection — a silent \
27763             detour to a peer-axis field would fail to refuse",
27764        );
27765
27766        // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
27767        // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
27768        // must pass validate under the accessor projection — pins the
27769        // upper-boundary accept-arm also routes through the lifted
27770        // accessor (a drift that clamped or short-circuited at the
27771        // upper boundary would fail the whole-spec validate here).
27772        let mut spec = three_member_spec();
27773        spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
27774        spec.politicas.retries = Some(POLICY_RETRIES_MAX);
27775        spec.politicas.circuit_breaker = None;
27776        spec.politicas.rate_limit = None;
27777        assert_eq!(
27778            spec.politicas().timeout(),
27779            Some(POLICY_TIMEOUT_MAX),
27780            "the accessor projection must reflect the fixture's \
27781             at-cap :timeout verbatim",
27782        );
27783        assert_eq!(
27784            spec.politicas().retries(),
27785            Some(POLICY_RETRIES_MAX),
27786            "the accessor projection must reflect the fixture's \
27787             at-cap :retries verbatim",
27788        );
27789        assert!(
27790            spec.validate().is_ok(),
27791            "at-cap :timeout + :retries must pass validate under the \
27792             accessor projection — the upper-boundary accept-arm on \
27793             both axes routes through the lifted accessor",
27794        );
27795    }
27796
27797    #[test]
27798    fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
27799        // The canonical per-`:placement` outer-composite-reference-shape
27800        // pin: [`AplicacaoSpec::placement`] must return the `:placement`
27801        // typed `Placement` verbatim as a `&Placement` reference over the
27802        // same backing storage the raw `&self.placement` field access
27803        // borrows from, byte-equal across every representative fixture in
27804        // the accept-set — the default `Placement` (the substrate seed
27805        // shape whose [`PlacementStrategy::default`] evaluates to
27806        // `SingleNode` with an empty `:clusters` pool and both
27807        // optional-scalar axes `None`), and every canonical strategy /
27808        // cluster-pool / optional-scalar combination the
27809        // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
27810        // three [`PlacementStrategy`] variants — `SingleNode`,
27811        // `Replicated`, `Sharded` — cross-projected with a non-empty
27812        // `:clusters` pool and, on the `Sharded` arm, a non-empty
27813        // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
27814        // canonical `three_member_spec` `Replicated` fixture's
27815        // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
27816        //
27817        // Pins against a future silent detour that returned a fresh-
27818        // cloned `Placement` copy (which would type-check via a `Clone`
27819        // impl but silently break every downstream caller that relied on
27820        // the reference sharing the composite's backing identity), a
27821        // reference to an operator-resolved overlay (the future per-
27822        // cluster `:placement-overrides` slot MESH-COMPOSITION §V
27823        // acknowledges — its resolution must land at exactly this
27824        // accessor body, not silently divert the raw slot away from a
27825        // second consumer), or an axis-shuffled projection (a future
27826        // detour that swapped `clusters` and `affinity` through the
27827        // accessor would silently split the paired `validate_placement`
27828        // per-axis bracket-dispatch's traversal input from the peer
27829        // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
27830        // programs.yaml distribution-annotation emitter's fan-out input
27831        // from the peer `feira app graph` per-Aplicacao print line's
27832        // input).
27833        //
27834        // Peer of the sibling M3
27835        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
27836        // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
27837        // outer mesh-policy composite-reference axis, and of the sibling
27838        // slice-return `aplicacao_spec_membros_returns_membros_slice_
27839        // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
27840        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
27841        // across_permutations` (0dcc926) `&[WitContract]` pins — extends
27842        // the outer-accessor byte-equal-projection discipline onto the
27843        // outermost M3 mesh-slot type's per-Aplicacao distribution
27844        // composite-reference axis, the second `&Composite`-return
27845        // accessor on the outer [`AplicacaoSpec`] type.
27846        let fixtures: Vec<Placement> = vec![
27847            Placement::default(),
27848            Placement {
27849                estrategia: PlacementStrategy::SingleNode,
27850                clusters: vec!["rio".into()],
27851                affinity: None,
27852                shard_key: None,
27853            },
27854            Placement {
27855                estrategia: PlacementStrategy::Replicated,
27856                clusters: vec!["rio".into(), "mar".into()],
27857                affinity: None,
27858                shard_key: None,
27859            },
27860            Placement {
27861                estrategia: PlacementStrategy::Replicated,
27862                clusters: vec!["rio".into(), "mar".into()],
27863                affinity: Some("data-locality".into()),
27864                shard_key: None,
27865            },
27866            Placement {
27867                estrategia: PlacementStrategy::Sharded,
27868                clusters: vec!["rio".into(), "mar".into()],
27869                affinity: None,
27870                shard_key: Some("tenantId".into()),
27871            },
27872            Placement {
27873                estrategia: PlacementStrategy::Sharded,
27874                clusters: vec!["rio".into(), "mar".into(), "sol".into()],
27875                affinity: Some("low-latency".into()),
27876                shard_key: Some("metadata.tenantId".into()),
27877            },
27878        ];
27879        for placement in fixtures {
27880            let s = AplicacaoSpec {
27881                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
27882                contratos: Vec::new(),
27883                politicas: MeshPolicy::default(),
27884                placement: placement.clone(),
27885                entrada: None,
27886            };
27887            assert_eq!(
27888                *s.placement(),
27889                placement,
27890                "AplicacaoSpec::placement must return :placement verbatim \
27891                 (got {:?}, expected {:?})",
27892                s.placement(),
27893                placement,
27894            );
27895            assert!(
27896                std::ptr::eq(s.placement(), &s.placement),
27897                "AplicacaoSpec::placement accessor and &self.placement \
27898                 field access must borrow the same backing storage — the \
27899                 accessor is the substrate-primitive typed dispatch every \
27900                 downstream distribution-composite consumer must route \
27901                 through, and a reference-identity split would silently \
27902                 break every consumer that relied on the borrow sharing \
27903                 the composite's storage",
27904            );
27905            assert_eq!(
27906                s.placement().estrategia(),
27907                s.placement.estrategia,
27908                "AplicacaoSpec::placement().estrategia() must byte-equal \
27909                 self.placement.estrategia — a strategy-drift would \
27910                 silently split the paired `validate_placement` \
27911                 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
27912                 peer caixa-mesh programs.yaml `placement.estrategia` \
27913                 emitter's key from the peer `feira app graph` printer's \
27914                 strategy label",
27915            );
27916            assert_eq!(
27917                s.placement().clusters(),
27918                s.placement.clusters.as_slice(),
27919                "AplicacaoSpec::placement().clusters() must byte-equal \
27920                 self.placement.clusters — a cluster-pool drift would \
27921                 silently split the paired `validate_placement` \
27922                 pre-flight `.is_empty()` refusal probe's traversal from \
27923                 the peer caixa-mesh programs.yaml `placement.clusters` \
27924                 emitter's fan-out from the peer `feira app graph` \
27925                 printer's cluster list",
27926            );
27927        }
27928    }
27929
27930    #[test]
27931    fn validate_placement_reads_through_lifted_placement_accessor() {
27932        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
27933        // per-axis bracket-dispatch seed (`let p = self.placement();`,
27934        // followed by the per-axis fan-out `p.clusters()` /
27935        // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
27936        // lifted axis-level accessor family) must key off the lifted
27937        // outer accessor, so any future rebrand on the typed slot's
27938        // outer-composite reader shape lands at exactly one place. Pins
27939        // the multi-axis coherence by exercising each per-axis refusal
27940        // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
27941        // `:clusters` pool under the outer accessor's reference
27942        // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
27943        // strategy with a `None` `:shard-key` under the same projection,
27944        // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
27945        // with a `Some` `:shard-key` under the same projection, and
27946        // (4) the canonical `three_member_spec` `Replicated` fixture
27947        // passes `validate_placement` under the outer accessor's
27948        // reference projection — the accessor's reference-projection
27949        // reaches every per-axis branch (cluster-pool refusal, `Sharded`
27950        // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
27951        // without silently short-circuiting any.
27952        //
27953        // Peer of the sibling M3
27954        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
27955        // (534dc21) multi-axis coherence pin on the per-`:politicas`
27956        // outer mesh-policy composite-reference axis — extends the
27957        // multi-consumer coherence discipline onto the outermost M3
27958        // mesh-slot type's per-Aplicacao distribution composite-
27959        // reference axis, the second `&Composite`-return accessor on
27960        // the outer [`AplicacaoSpec`] type.
27961
27962        // (1) `PlacementWithoutClusters` refusal under the outer
27963        // accessor's reference projection: an empty `:clusters` pool
27964        // must trip the pre-flight refusal probe. The bracket-dispatch's
27965        // first arm reads `p.clusters()` on the reference returned by
27966        // the outer accessor.
27967        let mut spec = three_member_spec();
27968        spec.placement.clusters = Vec::new();
27969        assert_eq!(
27970            spec.validate().unwrap_err(),
27971            AplicacaoError::PlacementWithoutClusters {
27972                estrategia: PlacementStrategy::Replicated,
27973            },
27974        );
27975        assert!(
27976            std::ptr::eq(spec.placement(), &spec.placement),
27977            "the `validate_placement` per-axis bracket-dispatch's \
27978             traversal input must be the same backing composite the \
27979             accessor's reference projection borrows from",
27980        );
27981
27982        // (2) `ShardedWithoutKey` refusal under the outer accessor's
27983        // reference projection: a `Sharded` strategy with a `None`
27984        // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
27985        // The bracket-dispatch's third arm reads `p.estrategia()` for
27986        // the match scrutinee then `p.shard_key()` for the cascade
27987        // scrutinee, both on the reference returned by the outer
27988        // accessor.
27989        let mut spec = three_member_spec();
27990        spec.placement.estrategia = PlacementStrategy::Sharded;
27991        spec.placement.shard_key = None;
27992        assert_eq!(
27993            spec.validate().unwrap_err(),
27994            AplicacaoError::ShardedWithoutKey,
27995        );
27996
27997        // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
27998        // reference projection: a non-`Sharded` strategy with a `Some`
27999        // `:shard-key` must trip the declared-but-inert refusal. The
28000        // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
28001        // + `p.estrategia()` for the diagnostic on the reference
28002        // returned by the outer accessor.
28003        let mut spec = three_member_spec();
28004        spec.placement.estrategia = PlacementStrategy::Replicated;
28005        spec.placement.shard_key = Some("tenantId".into());
28006        assert_eq!(
28007            spec.validate().unwrap_err(),
28008            AplicacaoError::ShardKeyOnNonSharded {
28009                estrategia: PlacementStrategy::Replicated,
28010                shard_key: "tenantId".into(),
28011            },
28012        );
28013
28014        // (4) Canonical `three_member_spec` `Replicated` fixture passes
28015        // `validate_placement` — every per-axis arm reaches the fall-
28016        // through `Ok(())` without any per-axis refusal firing under the
28017        // outer accessor's reference projection.
28018        let spec = three_member_spec();
28019        assert!(
28020            spec.validate().is_ok(),
28021            "the canonical Replicated placement fixture must pass \
28022             `validate_placement` — every per-axis arm short-circuits on \
28023             valid input under the outer accessor's reference projection",
28024        );
28025        assert_eq!(
28026            spec.placement().estrategia(),
28027            PlacementStrategy::Replicated,
28028            "the outer accessor's reference projection must be the \
28029             canonical Replicated fixture's strategy",
28030        );
28031        assert_eq!(
28032            spec.placement().clusters(),
28033            &["rio", "mar"],
28034            "the outer accessor's reference projection must be the \
28035             canonical Replicated fixture's cluster pool",
28036        );
28037    }
28038
28039    #[test]
28040    fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
28041        // The canonical per-`:entrada` outer-composite-optional-
28042        // reference-shape pin: [`AplicacaoSpec::entrada`] must return
28043        // the `:entrada` typed `Option<Entrada>` verbatim as an
28044        // `Option<&Entrada>` reference over the same backing storage
28045        // the raw `self.entrada.as_ref()` field access borrows from,
28046        // byte-equal across every representative fixture in the
28047        // accept-set — the author-omitted `None` shape (the
28048        // "internal-only mesh" partition every downstream external-
28049        // gateway emitter treats as "emit nothing"), the minimal
28050        // singleton `:entrada` composite (host + destination + empty
28051        // paths + default port), the paths-carrying composite (the
28052        // canonical `three_member_spec` fixture's ["/api" "/health"]
28053        // path-list shape every HTTPRoute per-rule fan-out emitter
28054        // reads), and the non-default port composite (the canonical
28055        // custom-port shape the port-fallback resolver reads).
28056        //
28057        // Pins against a future silent detour that returned a fresh-
28058        // cloned `Entrada` copy (which would type-check via a `Clone`
28059        // impl but silently break every downstream caller that
28060        // relied on the reference sharing the composite's backing
28061        // identity), a reference to an operator-resolved overlay
28062        // (the future per-cluster `:entrada-overrides` slot the
28063        // MESH-COMPOSITION §V federation roadmap acknowledges — its
28064        // resolution must land at exactly this accessor body, not
28065        // silently divert the raw slot away from a second consumer),
28066        // a `None` → `Some(Entrada::default)` cluster-default
28067        // projection (which would collapse the load-bearing
28068        // "author-omitted `:entrada` ⇒ internal-only mesh" partition
28069        // the peer `gateway_routes` early-return + `feira app graph`
28070        // internal-only-mesh partition both read), or an axis-
28071        // shuffled projection (a future detour that swapped
28072        // `host` and `para` through the accessor would silently
28073        // split the paired `validate` per-`:entrada` shape-and-
28074        // membership gate's traversal input from the peer
28075        // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
28076        // fan-out input from the peer `feira app graph` external-
28077        // gateway summary line).
28078        //
28079        // Peer of the sibling M3
28080        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
28081        // (534dc21) `&MeshPolicy` byte-equal pin on the per-
28082        // `:politicas` outer mesh-policy composite-reference axis
28083        // and of the sibling M3
28084        // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
28085        // (9abb8f0) `&Placement` byte-equal pin on the per-
28086        // `:placement` outer distribution-composite composite-
28087        // reference axis — extends the outer-accessor byte-equal-
28088        // projection discipline onto the last unlifted outermost M3
28089        // mesh-slot type's per-Aplicacao external-gateway composite-
28090        // reference axis, the third and final `&Composite`-return
28091        // accessor on the outer [`AplicacaoSpec`] type.
28092        let fixtures: Vec<Option<Entrada>> = vec![
28093            None,
28094            Some(Entrada {
28095                host: "checkout.quero.cloud".into(),
28096                para: "cart".into(),
28097                paths: Vec::new(),
28098                port: DEFAULT_SERVICO_PORT,
28099            }),
28100            Some(Entrada {
28101                host: "checkout.quero.cloud".into(),
28102                para: "cart".into(),
28103                paths: vec!["/api".into(), "/health".into()],
28104                port: DEFAULT_SERVICO_PORT,
28105            }),
28106            Some(Entrada {
28107                host: "checkout.quero.cloud".into(),
28108                para: "cart".into(),
28109                paths: vec!["/api".into()],
28110                port: 9443,
28111            }),
28112        ];
28113        for entrada in fixtures {
28114            let s = AplicacaoSpec {
28115                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
28116                contratos: Vec::new(),
28117                politicas: MeshPolicy::default(),
28118                placement: Placement::default(),
28119                entrada: entrada.clone(),
28120            };
28121            assert_eq!(
28122                s.entrada(),
28123                entrada.as_ref(),
28124                "AplicacaoSpec::entrada must return :entrada verbatim \
28125                 (got {:?}, expected {:?})",
28126                s.entrada(),
28127                entrada.as_ref(),
28128            );
28129            match (s.entrada(), s.entrada.as_ref()) {
28130                (Some(a), Some(b)) => assert!(
28131                    std::ptr::eq(a, b),
28132                    "AplicacaoSpec::entrada accessor and \
28133                     self.entrada.as_ref() field access must borrow \
28134                     the same backing storage — the accessor is the \
28135                     substrate-primitive typed dispatch every \
28136                     downstream external-gateway composite consumer \
28137                     must route through, and a reference-identity \
28138                     split would silently break every consumer that \
28139                     relied on the borrow sharing the composite's \
28140                     storage",
28141                ),
28142                (None, None) => {}
28143                _ => panic!(
28144                    "AplicacaoSpec::entrada presence bit must byte-\
28145                     equal self.entrada.is_some() — a presence-bit \
28146                     drift would silently split the paired `validate` \
28147                     per-`:entrada` shape-and-membership gate's \
28148                     traversal head from the peer \
28149                     caixa-mesh gateway_routes early-return partition \
28150                     from the peer `feira app graph` internal-only-\
28151                     mesh partition",
28152                ),
28153            }
28154            assert_eq!(
28155                s.entrada().is_some(),
28156                s.entrada.is_some(),
28157                "AplicacaoSpec::entrada().is_some() must byte-equal \
28158                 self.entrada.is_some() — a presence-bit drift would \
28159                 silently split every downstream `Option<&Entrada>` \
28160                 consumer's partition on the internal-only-mesh arm",
28161            );
28162        }
28163    }
28164
28165    #[test]
28166    fn validate_reads_through_lifted_entrada_accessor() {
28167        // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
28168        // per-`:entrada` shape-and-membership gate (`if let Some(e) =
28169        // self.entrada() { … }`, followed by the per-axis fan-out
28170        // `validate_entrada_para(&e.para)` /
28171        // `EntradaMemberMissing` membership lookup /
28172        // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
28173        // per-`e.paths` `validate_entrada_path` traversal) must key
28174        // off the lifted outer accessor, so any future rebrand on
28175        // the typed slot's outer-composite reader shape lands at
28176        // exactly one place. Pins the multi-axis coherence by
28177        // exercising each per-axis refusal end-to-end: (1) the
28178        // author-omitted `None` shape short-circuits past every
28179        // per-`:entrada` refusal (the internal-only mesh partition
28180        // the accessor's `None` arm names), (2) `EntradaMemberMissing`
28181        // fires on a well-shaped but phantom `:para` under the outer
28182        // accessor's reference projection, and (3) the canonical
28183        // `three_member_spec` `:entrada` fixture passes `validate`
28184        // under the outer accessor's reference projection.
28185        //
28186        // Peer of the sibling M3
28187        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
28188        // (534dc21) multi-axis coherence pin on the per-`:politicas`
28189        // outer mesh-policy composite-reference axis and the sibling
28190        // M3
28191        // [`validate_placement_reads_through_lifted_placement_accessor`]
28192        // (9abb8f0) multi-axis coherence pin on the per-`:placement`
28193        // outer distribution-composite composite-reference axis —
28194        // extends the multi-consumer coherence discipline onto the
28195        // last unlifted outermost M3 mesh-slot type's per-Aplicacao
28196        // external-gateway composite-reference axis, the third and
28197        // final `&Composite`-return accessor on the outer
28198        // [`AplicacaoSpec`] type.
28199
28200        // (1) `None` :entrada — the internal-only-mesh partition
28201        // short-circuits past every per-`:entrada` refusal. The outer
28202        // accessor's reference projection reaches the fall-through
28203        // `Ok(())` on the `None` arm without any per-axis refusal
28204        // firing.
28205        let mut spec = three_member_spec();
28206        spec.entrada = None;
28207        assert!(
28208            spec.validate().is_ok(),
28209            "an author-omitted `:entrada` must pass `validate` — the \
28210             internal-only-mesh partition short-circuits past every \
28211             per-`:entrada` refusal under the outer accessor's \
28212             reference projection",
28213        );
28214        assert!(
28215            spec.entrada().is_none(),
28216            "the outer accessor's reference projection must name the \
28217             internal-only-mesh partition per the `None` fixture",
28218        );
28219
28220        // (2) `EntradaMemberMissing` refusal under the outer accessor's
28221        // reference projection: a well-shaped but phantom `:para` must
28222        // trip the membership-lookup refusal. The gate's second arm
28223        // reads `e.para` on the reference returned by the outer
28224        // accessor.
28225        let mut spec = three_member_spec();
28226        if let Some(e) = spec.entrada.as_mut() {
28227            e.para = "phantom".into();
28228        }
28229        assert_eq!(
28230            spec.validate().unwrap_err(),
28231            AplicacaoError::EntradaMemberMissing {
28232                para: "phantom".into(),
28233            },
28234        );
28235        match (spec.entrada(), spec.entrada.as_ref()) {
28236            (Some(a), Some(b)) => assert!(
28237                std::ptr::eq(a, b),
28238                "the `validate` per-`:entrada` gate's traversal head \
28239                 must be the same backing composite the accessor's \
28240                 reference projection borrows from",
28241            ),
28242            _ => panic!("fixture must carry Some(:entrada)"),
28243        }
28244
28245        // (3) Canonical `three_member_spec` `:entrada` fixture passes
28246        // `validate` — every per-axis arm reaches the fall-through
28247        // `Ok(())` without any per-axis refusal firing under the
28248        // outer accessor's reference projection.
28249        let spec = three_member_spec();
28250        assert!(
28251            spec.validate().is_ok(),
28252            "the canonical `:entrada` fixture must pass `validate` — \
28253             every per-axis arm short-circuits on valid input under \
28254             the outer accessor's reference projection",
28255        );
28256        assert!(
28257            spec.entrada().is_some(),
28258            "the outer accessor's reference projection must be the \
28259             canonical `:entrada` fixture's composite",
28260        );
28261    }
28262
28263    #[test]
28264    fn membro_names_matches_inline_membros_projection() {
28265        // Substrate-primitive ≡ inline-projection pin on
28266        // [`AplicacaoSpec::membro_names`]: the lifted membership oracle
28267        // must be byte-for-byte the set the pre-lift inline
28268        // `self.membros().iter().map(Membro::nome).collect()` builder
28269        // produced, on every membership shape the three
28270        // Servico-name-*reference* axes (`:contratos :de`, `:contratos
28271        // :para`, `:entrada :para`) resolve against. Pins the
28272        // projection so a future rebrand of the node-identity axis
28273        // lands at the primitive rather than diverging between the
28274        // per-`:contratos` membership arms still inline at `validate`
28275        // and the lifted `validate_entrada` gate.
28276        for membros in [
28277            vec![],
28278            vec![membro("cart", "^0.1")],
28279            vec![
28280                membro("catalog", "^0.1"),
28281                membro("cart", "^0.1"),
28282                membro("payment", "^0.2"),
28283            ],
28284        ] {
28285            let mut spec = three_member_spec();
28286            spec.membros = membros;
28287            let inline: std::collections::HashSet<&str> =
28288                spec.membros().iter().map(Membro::nome).collect();
28289            assert_eq!(
28290                spec.membro_names(),
28291                inline,
28292                "the lifted membership oracle must discriminate the \
28293                 same node set as the pre-lift inline projection",
28294            );
28295        }
28296    }
28297
28298    #[test]
28299    fn validate_entrada_matches_gate_on_every_per_axis_shape() {
28300        // Per-slot-gate ≡ validate equivalence pin on the lifted
28301        // [`AplicacaoSpec::validate_entrada`]: the named per-slot gate
28302        // must discriminate the same set as [`AplicacaoSpec::validate`]
28303        // on every `:entrada`-covered input, so a future consumer that
28304        // re-validates the one slot (the M4 admission webhook
28305        // re-checking `:entrada` after a gateway-host patch) accepts
28306        // exactly what `feira build` accepts and surfaces the same
28307        // diagnostic on the same input. Covers each of the five gated
28308        // axes plus the two clean-pass shapes (`None` — the
28309        // internal-only-mesh partition — and the canonical fixture).
28310        //
28311        // Peer of the sibling per-slot equivalence pins
28312        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
28313        // / `_on_cross_axis_and_clean_pass_shapes` (f03a154) on the
28314        // `:politicas` slot's compound entry gate, extended here onto
28315        // the `:entrada` slot's newly-named per-slot gate.
28316        /// One `:entrada` equivalence case: a label, the per-axis
28317        /// mutation applied to the canonical fixture's composite, and
28318        /// the diagnostic both the per-slot gate and `validate` must
28319        /// surface on it (`None` = clean pass).
28320        type EntradaCase = (&'static str, fn(&mut Entrada), Option<AplicacaoError>);
28321
28322        let cases: &[EntradaCase] = &[
28323            (
28324                ":para shape — empty",
28325                |e| e.para = String::new(),
28326                Some(AplicacaoError::EntradaParaEmpty),
28327            ),
28328            (
28329                ":para membership — well-shaped phantom",
28330                |e| e.para = "phantom".into(),
28331                Some(AplicacaoError::EntradaMemberMissing {
28332                    para: "phantom".into(),
28333                }),
28334            ),
28335            (
28336                ":host emptiness",
28337                |e| e.host = String::new(),
28338                Some(AplicacaoError::EmptyEntradaHost),
28339            ),
28340            (
28341                ":port structural floor",
28342                |e| e.port = 0,
28343                Some(AplicacaoError::EntradaPortZero),
28344            ),
28345            (
28346                ":paths per-entry emptiness",
28347                |e| e.paths = vec![String::new()],
28348                Some(AplicacaoError::EntradaPathEmpty),
28349            ),
28350            (
28351                ":paths leading-slash grammar",
28352                |e| e.paths = vec!["api/cart".into()],
28353                Some(AplicacaoError::EntradaPathNotAbsolute {
28354                    path: "api/cart".into(),
28355                }),
28356            ),
28357            (
28358                ":paths set-not-multiset",
28359                |e| e.paths = vec!["/api/cart".into(), "/api/cart".into()],
28360                Some(AplicacaoError::EntradaPathDuplicate {
28361                    path: "/api/cart".into(),
28362                }),
28363            ),
28364            ("clean pass — canonical fixture", |_| {}, None),
28365        ];
28366        for (label, mutate, expected) in cases {
28367            let mut spec = three_member_spec();
28368            mutate(spec.entrada.as_mut().expect("fixture carries :entrada"));
28369            assert_eq!(
28370                spec.validate_entrada().err(),
28371                *expected,
28372                "per-slot gate disagreed with the expected diagnostic on {label}",
28373            );
28374            assert_eq!(
28375                spec.validate().err(),
28376                *expected,
28377                "`validate` disagreed with the per-slot gate on {label}",
28378            );
28379        }
28380
28381        // The `None` arm is the internal-only-mesh partition: a clean
28382        // pass through both the per-slot gate and `validate`, not a
28383        // refusal.
28384        let mut spec = three_member_spec();
28385        spec.entrada = None;
28386        assert_eq!(spec.validate_entrada().err(), None);
28387        assert_eq!(spec.validate().err(), None);
28388    }
28389
28390    #[test]
28391    fn validate_entrada_resolves_membership_through_own_oracle() {
28392        // Self-containment pin on the lifted per-slot gate:
28393        // [`AplicacaoSpec::validate_entrada`] resolves `:entrada :para`
28394        // against the oracle *it* builds through
28395        // [`AplicacaoSpec::membro_names`], not one threaded down from
28396        // [`AplicacaoSpec::validate`]. A spec whose `:membros` no
28397        // longer contains the `:entrada :para` target must trip
28398        // `EntradaMemberMissing` when the per-slot gate is called
28399        // directly — the shape a future single-slot re-validator
28400        // (the M4 admission webhook) reaches the axis through, without
28401        // re-walking `:membros` / `:contratos` / the sync-cycle
28402        // detector first. Same self-contained posture
28403        // [`AplicacaoSpec::detect_sync_cycles`] already carries for
28404        // the M4 per-edge policy resolver.
28405        let mut spec = three_member_spec();
28406        spec.membros.retain(|m| m.nome() != "cart");
28407        assert_eq!(
28408            spec.validate_entrada().unwrap_err(),
28409            AplicacaoError::EntradaMemberMissing {
28410                para: "cart".into(),
28411            },
28412            "the per-slot gate must resolve `:para` against the oracle \
28413             it builds itself, with no membership set threaded in",
28414        );
28415        assert!(
28416            !spec.membro_names().contains("cart"),
28417            "fixture must have dropped the `:entrada :para` target \
28418             from the graph's node set",
28419        );
28420    }
28421
28422    #[test]
28423    fn validate_contratos_matches_gate_on_every_per_axis_shape() {
28424        // Per-slot-gate ≡ validate equivalence pin on the lifted
28425        // [`AplicacaoSpec::validate_contratos`]: the named per-slot
28426        // gate must discriminate the same set as
28427        // [`AplicacaoSpec::validate`] on every `:contratos`-covered
28428        // input, so a future consumer that re-validates the one slot
28429        // (the M4 admission webhook re-checking `:contratos` after a
28430        // per-`(:de, :para)` edge patch, the per-`:contratos`-edge
28431        // `:politicas` override MESH-COMPOSITION §III.2 #3
28432        // acknowledges — which resolves an effective per-edge
28433        // [`MeshPolicy`] and must re-check the edge's identity closure
28434        // before it can key a per-edge override off the endpoint
28435        // tuple) accepts exactly what `feira build` accepts and
28436        // surfaces the same diagnostic on the same input. Covers each
28437        // of the six gated axes (`:de`/`:para` per-arm shape,
28438        // per-arm graph-membership, structural self-loop, `:wit`
28439        // emptiness) plus the clean-pass canonical fixture; the
28440        // reason-carrying arms (`ContratoCaixaInvalid` on `:de`/`:para`
28441        // shape, `ContratoWitInvalid` on WIT-shape ↔ target dispatch,
28442        // `ContratoDuplicate` on whole-edge dedup) whose `reason:` /
28443        // `target:` carriers depend on library implementation
28444        // details are pinned separately below with a `matches!`
28445        // predicate on the arm identity plus the mirror equivalence
28446        // between the two entry points.
28447        //
28448        // Peer of the sibling per-slot equivalence pins
28449        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
28450        // / `_on_cross_axis_and_clean_pass_shapes` (f03a154) on the
28451        // `:politicas` slot's compound entry gate, and
28452        // `validate_entrada_matches_gate_on_every_per_axis_shape`
28453        // (20cd523) on the `:entrada` slot's per-slot gate — extended
28454        // here onto the `:contratos` slot's newly-named per-slot gate,
28455        // closing the last unlifted per-slot gate on the M3 mesh-slot
28456        // family.
28457        /// One `:contratos` equivalence case: a label, the per-axis
28458        /// mutation applied to the canonical fixture's spec, and the
28459        /// diagnostic both the per-slot gate and `validate` must
28460        /// surface on it (`None` = clean pass).
28461        type ContratoCase = (&'static str, fn(&mut AplicacaoSpec), Option<AplicacaoError>);
28462
28463        let cases: &[ContratoCase] = &[
28464            (
28465                ":de shape — empty",
28466                |s| s.contratos[0].de = String::new(),
28467                Some(AplicacaoError::ContratoCaixaEmpty {
28468                    slot: crate::render::CONTRATO_AUTHOR_KEY_DE,
28469                }),
28470            ),
28471            (
28472                ":para shape — empty",
28473                |s| s.contratos[0].para = String::new(),
28474                Some(AplicacaoError::ContratoCaixaEmpty {
28475                    slot: crate::render::CONTRATO_AUTHOR_KEY_PARA,
28476                }),
28477            ),
28478            (
28479                ":de membership — well-shaped phantom",
28480                |s| s.contratos[0].de = "phantom".into(),
28481                Some(AplicacaoError::ContratoMemberMissing {
28482                    caixa: "phantom".into(),
28483                }),
28484            ),
28485            (
28486                ":para membership — well-shaped phantom",
28487                |s| s.contratos[0].para = "phantom".into(),
28488                Some(AplicacaoError::ContratoMemberMissing {
28489                    caixa: "phantom".into(),
28490                }),
28491            ),
28492            (
28493                "structural self-loop",
28494                |s| s.contratos[0].para = "cart".into(),
28495                Some(AplicacaoError::ContratoSelfLoop {
28496                    caixa: "cart".into(),
28497                    wit: "wasi:http/proxy".into(),
28498                }),
28499            ),
28500            (
28501                ":wit emptiness",
28502                |s| s.contratos[0].wit = String::new(),
28503                Some(AplicacaoError::EmptyWit {
28504                    de: "cart".into(),
28505                    para: "catalog".into(),
28506                }),
28507            ),
28508            ("clean pass — canonical fixture", |_| {}, None),
28509        ];
28510        for (label, mutate, expected) in cases {
28511            let mut spec = three_member_spec();
28512            mutate(&mut spec);
28513            assert_eq!(
28514                spec.validate_contratos().err(),
28515                *expected,
28516                "per-slot gate disagreed with the expected diagnostic on {label}",
28517            );
28518            assert_eq!(
28519                spec.validate().err(),
28520                *expected,
28521                "`validate` disagreed with the per-slot gate on {label}",
28522            );
28523        }
28524    }
28525
28526    #[test]
28527    fn validate_contratos_matches_gate_on_reason_carrying_arms() {
28528        // Companion pin to
28529        // [`validate_contratos_matches_gate_on_every_per_axis_shape`]:
28530        // the per-slot gate ≡ `validate` equivalence on the three
28531        // `:contratos` refusal arms whose diagnostic carries a
28532        // library-owned string ([`AplicacaoError::ContratoCaixaInvalid`]
28533        // and [`AplicacaoError::ContratoWrongTarget`] via the paired
28534        // `is_dns_1123_label` / `WitContract::target` shape helpers,
28535        // and [`AplicacaoError::ContratoDuplicate`] via [`WitTarget::label`]'s
28536        // library-formatted `target:` scalar). Value equality between
28537        // the per-slot gate and `validate` outputs pins the full
28538        // `Option<AplicacaoError>` (including reason-strings), and the
28539        // per-arm `matches!` predicate pins the arm-discriminator
28540        // identity on the specific `Contrato*` variant. Split from
28541        // the primary equivalence pin so each pin body stays under
28542        // [`clippy::too_many_lines`], the same shape the peer
28543        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
28544        // / `_on_cross_axis_and_clean_pass_shapes` split (f03a154)
28545        // carries on the `:politicas` slot's compound entry gate.
28546        type ContratoReasonCase = (
28547            &'static str,
28548            fn(&mut AplicacaoSpec),
28549            fn(&AplicacaoError) -> bool,
28550        );
28551        let cases: &[ContratoReasonCase] = &[
28552            (
28553                ":de shape — DNS-1123 invalid",
28554                |s| s.contratos[0].de = "Cart".into(),
28555                |err| {
28556                    matches!(
28557                        err,
28558                        AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. }
28559                            if *slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
28560                    )
28561                },
28562            ),
28563            (
28564                ":wit target-shape mismatch — payload on capability arm",
28565                |s| s.contratos[0].wit = "wasi:junk/nope".into(),
28566                |err| {
28567                    matches!(
28568                        err,
28569                        AplicacaoError::ContratoWrongTarget { de, para, wit, .. }
28570                            if de == "cart" && para == "catalog" && wit == "wasi:junk/nope"
28571                    )
28572                },
28573            ),
28574            (
28575                "whole-edge dedup — six-axis identity collision",
28576                |s| {
28577                    let dup = s.contratos[0].clone();
28578                    s.contratos.push(dup);
28579                },
28580                |err| {
28581                    matches!(
28582                        err,
28583                        AplicacaoError::ContratoDuplicate { de, para, wit, .. }
28584                            if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
28585                    )
28586                },
28587            ),
28588        ];
28589        for (label, mutate, arm_matches) in cases {
28590            let mut spec = three_member_spec();
28591            mutate(&mut spec);
28592            let per_slot = spec.validate_contratos().err();
28593            let gate = spec.validate().err();
28594            assert_eq!(
28595                per_slot, gate,
28596                "per-slot gate and `validate` must return byte-equal \
28597                 `Option<AplicacaoError>` on {label} (including \
28598                 library-owned reason strings)",
28599            );
28600            let err = per_slot
28601                .as_ref()
28602                .unwrap_or_else(|| panic!("expected refusal on {label}, got clean pass"));
28603            assert!(
28604                arm_matches(err),
28605                "per-slot gate surfaced the wrong arm on {label}: got {err:?}",
28606            );
28607        }
28608    }
28609
28610    #[test]
28611    fn validate_contratos_resolves_membership_through_own_oracle() {
28612        // Self-containment pin on the lifted per-slot gate:
28613        // [`AplicacaoSpec::validate_contratos`] resolves each edge's
28614        // `:de` / `:para` against the oracle *it* builds through
28615        // [`AplicacaoSpec::membro_names`], not one threaded down from
28616        // [`AplicacaoSpec::validate`]. A spec whose `:membros` no
28617        // longer contains a `:contratos` edge's endpoint must trip
28618        // `ContratoMemberMissing` when the per-slot gate is called
28619        // directly — the shape a future single-slot re-validator
28620        // (the M4 admission webhook re-checking `:contratos` after a
28621        // per-`(:de, :para)` edge patch, the M4 per-edge policy
28622        // resolver on the `:politicas` override axis) reaches the
28623        // axis through, without re-walking `:membros` / `:entrada` /
28624        // `:placement` / `:politicas` first. Same self-contained
28625        // posture the peer per-slot gates
28626        // [`AplicacaoSpec::detect_sync_cycles`] and
28627        // [`AplicacaoSpec::validate_entrada`] already carry for the
28628        // same M4 consumers.
28629        let mut spec = three_member_spec();
28630        spec.membros.retain(|m| m.nome() != "catalog");
28631        assert_eq!(
28632            spec.validate_contratos().unwrap_err(),
28633            AplicacaoError::ContratoMemberMissing {
28634                caixa: "catalog".into(),
28635            },
28636            "the per-slot gate must resolve `:de` / `:para` against \
28637             the oracle it builds itself, with no membership set \
28638             threaded in",
28639        );
28640        assert!(
28641            !spec.membro_names().contains("catalog"),
28642            "fixture must have dropped the `:contratos` edge's \
28643             `:para` target from the graph's node set",
28644        );
28645    }
28646
28647    #[test]
28648    fn validate_contratos_folds_cycle_axis_matches_gate() {
28649        // Fold-into-per-slot-gate equivalence pin on the
28650        // cross-edge cycle axis: an [`AplicacaoError::ContratoCycle`]
28651        // surfaces byte-equal through both
28652        // [`AplicacaoSpec::validate_contratos`] and
28653        // [`AplicacaoSpec::validate`] on a fixture whose only defect is
28654        // a synchronous-edge cycle in `:contratos`. Pins the fold that
28655        // moved the cross-edge cycle axis onto the per-slot gate — a
28656        // future silent regression that de-folded the axis back to the
28657        // outer [`AplicacaoSpec::validate`] dispatch (a rebase artifact,
28658        // a peer per-slot gate lift that skipped the cross-axis half of
28659        // the [`MeshPolicy::validate`]-analogous discipline) would
28660        // surface here as `Some(ContratoCycle)` from `validate` and
28661        // `None` from `validate_contratos`.
28662        //
28663        // Cycle fixture is the same shape as the peer
28664        // [`rejects_three_node_synchronous_cycle`] test carries: a
28665        // clean 3-cycle over the HTTP subgraph (catalog → cart →
28666        // payment → catalog), so the per-entry cascade (shape +
28667        // membership + self-loop + `:wit` emptiness + WIT-target +
28668        // whole-edge dedup) passes cleanly and the sole surviving
28669        // refusal shape is the cross-edge cycle axis. The `cycle`
28670        // vector is normalized to a sorted body set for the equality
28671        // compare (the traversal path's starting node depends on
28672        // BTreeMap iteration order, which is deterministic but is not
28673        // the load-bearing property this pin covers).
28674        //
28675        // Peer of the sibling per-slot ≡ `validate` equivalence pins
28676        // [`validate_contratos_matches_gate_on_every_per_axis_shape`]
28677        // (per-entry axes) and
28678        // [`validate_contratos_matches_gate_on_reason_carrying_arms`]
28679        // (parser-owned reason arms) already carry on the six
28680        // per-entry axes — this extends the discipline onto the
28681        // cross-edge cycle axis newly folded into the per-slot gate,
28682        // matching the peer per-slot compound gate
28683        // [`AplicacaoSpec::validate_politicas`] (f03a154) which folded
28684        // both per-axis and cross-axis surfaces on `:politicas`.
28685        let mut spec = three_member_spec();
28686        spec.contratos = vec![
28687            contract_http("catalog", "cart", "/x"),
28688            contract_http("cart", "payment", "/y"),
28689            contract_http("payment", "catalog", "/z"),
28690        ];
28691        let per_slot_err = spec.validate_contratos().unwrap_err();
28692        let gate_err = spec.validate().unwrap_err();
28693        assert_eq!(
28694            per_slot_err, gate_err,
28695            "the per-slot gate and `validate` must return byte-equal \
28696             `AplicacaoError::ContratoCycle` on a cycle-only fixture \
28697             — the fold pins the cross-edge axis onto the per-slot \
28698             gate the same way the peer `validate_politicas` fold \
28699             pinned the `:politicas` cross-axis surface",
28700        );
28701        match per_slot_err {
28702            AplicacaoError::ContratoCycle { ref cycle } => {
28703                assert_eq!(
28704                    cycle.first(),
28705                    cycle.last(),
28706                    "cycle traversal must close on the back-edge \
28707                     target — the diagnostic shape the peer \
28708                     `rejects_three_node_synchronous_cycle` pins",
28709                );
28710                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
28711                assert_eq!(body.len(), 3, "3-cycle must visit 3 distinct nodes");
28712                assert!(body.contains("cart"));
28713                assert!(body.contains("catalog"));
28714                assert!(body.contains("payment"));
28715            }
28716            other => panic!("expected ContratoCycle, got {other:?}"),
28717        }
28718    }
28719
28720    #[test]
28721    fn validate_contratos_per_entry_arm_fires_before_cycle_arm() {
28722        // Diagnostic-ordering pin on the fold: a `:contratos` fixture
28723        // carrying *both* a per-entry defect (a self-loop, the
28724        // structural-self-edge arm on the per-entry cascade — chosen
28725        // because it never masks or is masked by the cycle diagnostic
28726        // on the peer arms) *and* a would-be synchronous-edge cycle in
28727        // the remaining edges must surface the per-entry diagnostic
28728        // first through both [`AplicacaoSpec::validate_contratos`] and
28729        // [`AplicacaoSpec::validate`] — pinning the fold's canonical
28730        // per-entry-before-cross-edge dispatch ordering, byte-equal to
28731        // the pre-fold `validate`-side sequence
28732        // (`validate_contratos()? → detect_sync_cycles()?`) the
28733        // dispatch encoded verbatim. A silent regression that reversed
28734        // the ordering inside the fold would surface here as a cycle
28735        // diagnostic on a fixture carrying an earlier per-entry defect
28736        // — masking the narrower "this edge is degenerate" arm behind
28737        // the coarser "this graph deadlocks" arm.
28738        //
28739        // Peer of the diagnostic-ordering property the pre-fold
28740        // dispatch encoded at the [`AplicacaoSpec::validate`]
28741        // altitude (`validate_contratos()? → detect_sync_cycles()?`),
28742        // now enforced inside the per-slot gate's own body, so a future
28743        // consumer that reaches only the per-slot gate (the M4
28744        // admission webhook re-checking `:contratos` after a per-edge
28745        // patch) inherits the ordering property by construction.
28746        let mut spec = three_member_spec();
28747        // The three-member fixture already has cart → catalog and
28748        // cart → payment; adding catalog → cart closes a 2-cycle on
28749        // the HTTP subgraph.
28750        spec.contratos
28751            .push(contract_http("catalog", "cart", "/refresh"));
28752        // Add a self-loop on `payment` — the per-entry structural-
28753        // self-edge arm — which must surface first.
28754        spec.contratos
28755            .push(contract_http("payment", "payment", "/loop"));
28756        let per_slot_err = spec.validate_contratos().unwrap_err();
28757        let gate_err = spec.validate().unwrap_err();
28758        assert_eq!(
28759            per_slot_err, gate_err,
28760            "per-slot gate and `validate` must agree on the ordering \
28761             fixture's surfaced diagnostic — a divergence here means \
28762             the fold reshaped one dispatch's ordering without the \
28763             other",
28764        );
28765        assert!(
28766            matches!(
28767                per_slot_err,
28768                AplicacaoError::ContratoSelfLoop { ref caixa, .. }
28769                    if caixa == "payment"
28770            ),
28771            "the per-entry structural-self-edge arm must fire before \
28772             the cross-edge cycle arm — pinning the fold's per-entry-\
28773             before-cross-edge dispatch ordering byte-equal to the \
28774             pre-fold `validate_contratos()? → detect_sync_cycles()?` \
28775             sequence; got {per_slot_err:?}",
28776        );
28777    }
28778
28779    #[test]
28780    fn validate_contratos_cycle_axis_is_self_contained_on_slot() {
28781        // Self-containment pin on the folded cross-edge cycle axis:
28782        // [`AplicacaoSpec::validate_contratos`] surfaces
28783        // [`AplicacaoError::ContratoCycle`] directly against `&self`
28784        // without depending on the peer per-slot gates
28785        // ([`AplicacaoSpec::validate_membros`],
28786        // [`AplicacaoSpec::validate_entrada`],
28787        // [`AplicacaoSpec::validate_placement`],
28788        // [`AplicacaoSpec::validate_politicas`]) running first — the
28789        // shape a future single-slot re-validator (the M4 admission
28790        // webhook re-checking `:contratos` after a per-`(:de, :para)`
28791        // edge patch, the per-edge policy resolver MESH-COMPOSITION
28792        // §III.2 #3 acknowledges) reaches *both* structural axes on
28793        // the slot through one call. A spec with a per-`:politicas`
28794        // refusal shape (zero `:timeout`, the first per-axis arm the
28795        // peer [`MeshPolicy::validate`] gate covers) AND a
28796        // synchronous-edge cycle in `:contratos` must:
28797        //
28798        //   - surface [`AplicacaoError::ContratoCycle`] through the
28799        //     per-slot gate `validate_contratos` directly (proves the
28800        //     cycle axis reaches the per-slot altitude without the
28801        //     peer `:politicas` gate running first);
28802        //   - surface [`AplicacaoError::ContratoCycle`] through
28803        //     `validate` (which reaches `validate_contratos` before
28804        //     `validate_politicas` per the fixed dispatch order), so
28805        //     the fold's cross-slot ordering (`:membros` →
28806        //     `:contratos` → `:entrada` → `:placement` → `:politicas`)
28807        //     is byte-equal to the pre-fold dispatch's ordering.
28808        //
28809        // Same self-contained-on-`&self` posture the peer per-slot
28810        // gates [`AplicacaoSpec::validate_entrada`] (20cd523),
28811        // [`AplicacaoSpec::validate_contratos`] per-entry axis
28812        // (906a5c6), and [`AplicacaoSpec::validate_politicas`]
28813        // (f03a154) already carry — extended here onto the newly-
28814        // folded cross-edge cycle axis. Peer of the sibling per-slot
28815        // self-containment pins
28816        // `validate_entrada_resolves_membership_through_own_oracle`
28817        // and `validate_contratos_resolves_membership_through_own_oracle`
28818        // on the per-entry membership axis — extends the discipline
28819        // onto the cross-edge cycle axis of the same per-slot gate.
28820        let mut spec = three_member_spec();
28821        // Poison `:politicas` — zero-`:timeout` trips the first per-
28822        // axis arm the [`MeshPolicy::validate`] gate covers, so any
28823        // dispatch that reached `:politicas` would surface a
28824        // `:politicas` diagnostic instead of `ContratoCycle`.
28825        spec.politicas.timeout = Some(Duration::from_secs(0));
28826        // Close a synchronous-edge cycle on the HTTP subgraph.
28827        spec.contratos
28828            .push(contract_http("catalog", "cart", "/refresh"));
28829        let per_slot_err = spec.validate_contratos().unwrap_err();
28830        assert!(
28831            matches!(per_slot_err, AplicacaoError::ContratoCycle { .. }),
28832            "the per-slot gate must surface `ContratoCycle` directly \
28833             against `&self` — a peer per-slot gate's regression \
28834             would surface a non-`ContratoCycle` diagnostic here; \
28835             got {per_slot_err:?}",
28836        );
28837        let gate_err = spec.validate().unwrap_err();
28838        assert!(
28839            matches!(gate_err, AplicacaoError::ContratoCycle { .. }),
28840            "`validate`'s five-slot dispatch must reach the fold's \
28841             cross-edge cycle axis on `:contratos` before the peer \
28842             `:politicas` gate — a dispatch-order regression would \
28843             surface a `:politicas` diagnostic here; got {gate_err:?}",
28844        );
28845        // Sanity: the poisoned `:politicas` alone would trip
28846        // [`MeshPolicy::validate`] under the peer per-slot gate, so
28847        // the cycle-first surfacing above is a real ordering property,
28848        // not a case where the `:politicas` axis silently accepts the
28849        // fixture.
28850        let mut politicas_only = three_member_spec();
28851        politicas_only.politicas.timeout = Some(Duration::from_secs(0));
28852        assert!(
28853            politicas_only.validate_politicas().is_err(),
28854            "the poisoned `:politicas` fixture must trip the peer \
28855             per-slot gate on its own — otherwise the self-contained \
28856             cycle-first surfacing above would not be an ordering \
28857             property",
28858        );
28859    }
28860
28861    #[test]
28862    fn wit_contract_require_endpoints_in_folds_per_arm_membership_cascade() {
28863        // Fail-before-pass-after equivalence pin on the lifted
28864        // per-edge substrate primitive [`WitContract::require_endpoints_in`]:
28865        // both arms (`:de` phantom and `:para` phantom) must fire the
28866        // `AplicacaoError::ContratoMemberMissing` diagnostic with a
28867        // `caixa` carrier byte-equal to the offending accessor's
28868        // projection, and `:de` must fire before `:para` when both
28869        // arms would trip on the same call — preserving the canonical
28870        // edge-direction order the peer per-arm shape gate
28871        // [`validate_contrato_caixa`], the [`WitContract::is_self_loop`]
28872        // diagnostic, and every peer per-arm ordering in
28873        // [`AplicacaoSpec::validate_contratos`] already carry.
28874        //
28875        // Two-endpoint oracle covers exactly enough graph nodes to
28876        // exercise each arm in isolation: the `:de` arm fires when
28877        // the source is off-oracle and the destination is on-oracle,
28878        // the `:para` arm fires when the source is on-oracle and the
28879        // destination is off-oracle, and the `:de`-before-`:para`
28880        // ordering falls out from a probe where *both* endpoints are
28881        // off-oracle — the diagnostic's `caixa` field must byte-equal
28882        // the source, not the destination, pinning the primitive's
28883        // arm ordering as `:de` first.
28884        let mut names: std::collections::HashSet<&str> = std::collections::HashSet::new();
28885        names.insert("cart");
28886        names.insert("catalog");
28887
28888        // `:de` phantom, `:para` on-oracle
28889        let de_phantom = contract_http("phantom-de", "catalog", "/x");
28890        let err = de_phantom.require_endpoints_in(&names).unwrap_err();
28891        assert_eq!(
28892            err,
28893            AplicacaoError::ContratoMemberMissing {
28894                caixa: de_phantom.source().to_string(),
28895            },
28896            "the `:de` phantom arm must fire ContratoMemberMissing \
28897             with `caixa` byte-equal to `WitContract::source` — a \
28898             bypass here (a raw `.de.clone()` regression, a divergent \
28899             accessor on a per-CR alias table) would silently split \
28900             the primitive's diagnostic from the substrate-primitive \
28901             scalar accessor every downstream consumer routes through",
28902        );
28903
28904        // `:de` on-oracle, `:para` phantom
28905        let para_phantom = contract_http("cart", "phantom-para", "/x");
28906        let err = para_phantom.require_endpoints_in(&names).unwrap_err();
28907        assert_eq!(
28908            err,
28909            AplicacaoError::ContratoMemberMissing {
28910                caixa: para_phantom.destination().to_string(),
28911            },
28912            "the `:para` phantom arm must fire ContratoMemberMissing \
28913             with `caixa` byte-equal to `WitContract::destination` — \
28914             symmetric callee-side pin to the `:de` arm above",
28915        );
28916
28917        // Both endpoints off-oracle: the `:de` arm must fire first,
28918        // pinning the primitive's canonical edge-direction order.
28919        let both_phantom = contract_http("phantom-de", "phantom-para", "/x");
28920        let err = both_phantom.require_endpoints_in(&names).unwrap_err();
28921        assert_eq!(
28922            err,
28923            AplicacaoError::ContratoMemberMissing {
28924                caixa: both_phantom.source().to_string(),
28925            },
28926            "when both endpoints are off-oracle, the `:de` arm must \
28927             fire before the `:para` arm — preserving byte-equal \
28928             ordering with the pre-lift inline cascade in \
28929             `validate_contratos` and with every peer per-arm \
28930             ordering the sibling per-edge substrate primitives \
28931             already carry",
28932        );
28933
28934        // Both endpoints on-oracle: clean pass.
28935        let clean = contract_http("cart", "catalog", "/x");
28936        clean.require_endpoints_in(&names).unwrap();
28937    }
28938
28939    #[test]
28940    fn validate_contratos_membership_gate_routes_through_require_endpoints_in() {
28941        // Convergence pin: the whole-spec end-to-end route through
28942        // [`AplicacaoSpec::validate_contratos`] must reach the
28943        // per-edge substrate primitive
28944        // [`WitContract::require_endpoints_in`] on every membership
28945        // arm — the diagnostic fired at the per-slot altitude must
28946        // byte-equal the diagnostic the primitive fires when called
28947        // directly on the same edge and the same oracle. Pins the
28948        // primitive as the sole load-bearing gate on the membership
28949        // axis, so any future silent detour that re-inlined the twin
28950        // `if !names.contains(...)` cascade back into the per-slot
28951        // gate (a rebase-artifact regression, an M4 admission-webhook
28952        // consumer that bypassed the primitive) would surface here as
28953        // a byte-equal miss between the two dispatches.
28954        //
28955        // Same equivalence-pin discipline the peer
28956        // [`validate_contratos_matches_gate_on_every_per_axis_shape`]
28957        // pin already carries on the per-slot gate ≡ `validate` axis,
28958        // extended here onto the per-slot gate ≡ per-edge primitive
28959        // axis at one altitude deeper.
28960        for phantom_edge in [
28961            contract_http("phantom-de", "catalog", "/x"),
28962            contract_http("cart", "phantom-para", "/x"),
28963        ] {
28964            let mut spec = three_member_spec();
28965            spec.contratos.push(phantom_edge.clone());
28966            let per_slot_err = spec.validate_contratos().unwrap_err();
28967            let primitive_err = phantom_edge
28968                .require_endpoints_in(&spec.membro_names())
28969                .unwrap_err();
28970            assert_eq!(
28971                per_slot_err, primitive_err,
28972                "the per-slot gate must reach the per-edge substrate \
28973                 primitive on every membership arm — a bypass here \
28974                 would silently split the two dispatches on the \
28975                 same edge + same oracle input",
28976            );
28977            // And the diagnostic's `caixa` carrier must byte-equal
28978            // the offending accessor's projection at both altitudes,
28979            // pinning the accessor routing across the whole-spec
28980            // path.
28981            let AplicacaoError::ContratoMemberMissing { ref caixa } = per_slot_err else {
28982                panic!("expected ContratoMemberMissing, got {per_slot_err:?}");
28983            };
28984            let expected = if spec.membro_names().contains(phantom_edge.source()) {
28985                phantom_edge.destination()
28986            } else {
28987                phantom_edge.source()
28988            };
28989            assert_eq!(
28990                caixa, expected,
28991                "the whole-spec ContratoMemberMissing.caixa carrier \
28992                 must byte-equal the offending edge's accessor \
28993                 projection — a bypass here would silently split \
28994                 the wrap envelope's `caixa` field from the \
28995                 substrate-primitive scalar accessor every \
28996                 downstream consumer routes through",
28997            );
28998        }
28999    }
29000
29001    #[test]
29002    fn port_for_destination_reads_through_lifted_entrada_accessor() {
29003        // Peer coherence pin: the
29004        // [`AplicacaoSpec::port_for_destination`] per-destination
29005        // L4-port fallback resolver's composite-projection seed
29006        // (`self.entrada().filter(…).map_or(…)`) must key off the
29007        // lifted outer accessor. Pins the coherence by exercising
29008        // the resolver end-to-end: (1) the `None` `:entrada` shape
29009        // falls through to `DEFAULT_SERVICO_PORT` under the outer
29010        // accessor's reference projection, (2) a non-matching
29011        // destination falls through to `DEFAULT_SERVICO_PORT` under
29012        // the outer accessor's reference projection, and (3) the
29013        // matching destination resolves to the `:entrada :port`
29014        // value under the outer accessor's reference projection.
29015        //
29016        // Peer of the sibling
29017        // [`validate_reads_through_lifted_entrada_accessor`] multi-
29018        // consumer coherence pin on the same per-`:entrada` outer-
29019        // composite axis — extends the multi-consumer coherence
29020        // discipline onto the second per-`:entrada` production
29021        // consumer, the L4-port fallback resolver.
29022
29023        // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
29024        // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
29025        // arm under the outer accessor's reference projection.
29026        let mut spec = three_member_spec();
29027        spec.entrada = None;
29028        assert_eq!(
29029            spec.port_for_destination("cart"),
29030            DEFAULT_SERVICO_PORT,
29031            "the port-fallback resolver must fall through to \
29032             DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
29033             under the outer accessor's reference projection",
29034        );
29035
29036        // (2) Non-matching destination — the resolver's `filter(…)`
29037        // arm rejects a mismatched destination and falls through
29038        // to `DEFAULT_SERVICO_PORT` under the outer accessor's
29039        // reference projection.
29040        let mut spec = three_member_spec();
29041        if let Some(e) = spec.entrada.as_mut() {
29042            e.para = "cart".into();
29043            e.port = 9443;
29044        }
29045        assert_eq!(
29046            spec.port_for_destination("catalog"),
29047            DEFAULT_SERVICO_PORT,
29048            "the port-fallback resolver must fall through to \
29049             DEFAULT_SERVICO_PORT on a non-matching destination \
29050             under the outer accessor's reference projection",
29051        );
29052
29053        // (3) Matching destination — the resolver's `map_or(…)` arm
29054        // returns the `:entrada :port` value under the outer
29055        // accessor's reference projection.
29056        let mut spec = three_member_spec();
29057        if let Some(e) = spec.entrada.as_mut() {
29058            e.para = "cart".into();
29059            e.port = 9443;
29060        }
29061        assert_eq!(
29062            spec.port_for_destination("cart"),
29063            9443,
29064            "the port-fallback resolver must return the \
29065             `:entrada :port` value on a matching destination \
29066             under the outer accessor's reference projection",
29067        );
29068    }
29069
29070    #[test]
29071    fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
29072        // The canonical per-`:politicas` `:mtls-required` mTLS-
29073        // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
29074        // must return the `:politicas :mtls-required` typed bool
29075        // verbatim as an `Option<bool>`, byte-equal to the raw field
29076        // access across every value in the three-way accept-set —
29077        // `None` (cluster default applies), `Some(true)` (mTLS
29078        // handshake enforced — the sandboxing-by-default arm the
29079        // MeshPolicy's docstring names), `Some(false)` (handshake
29080        // skipped — the explicit debug-edge opt-out).
29081        //
29082        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
29083        // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
29084        // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
29085        // shape — first `Option<Copy-T>`-return accessor on the M3
29086        // mesh-slot family. Pins against a future silent detour that
29087        // re-derived the toggle from a peer axis (an accidental
29088        // `.circuit_breaker.is_some()` collapse that assumed mTLS on
29089        // whenever a breaker is set), a `None` → `Some(false)` cluster-
29090        // default projection (the canonical `Option<bool>` → `bool`
29091        // collapse footgun the surrounding `is_empty()` predicate
29092        // guards on the peer emptiness axis), or a `Some(true)` /
29093        // `Some(false)` variant swap that landed on one consumer
29094        // without the other.
29095        for required in [None, Some(true), Some(false)] {
29096            let p = MeshPolicy {
29097                mtls_required: required,
29098                ..MeshPolicy::default()
29099            };
29100            assert_eq!(
29101                p.mtls_required(),
29102                required,
29103                "MeshPolicy::mtls_required must return :politicas \
29104                 :mtls-required verbatim (got {:?}, expected {required:?})",
29105                p.mtls_required(),
29106            );
29107            assert_eq!(
29108                p.mtls_required(),
29109                p.mtls_required,
29110                "MeshPolicy::mtls_required must byte-equal the raw \
29111                 .mtls_required field access across every value in the \
29112                 three-way accept-set",
29113            );
29114        }
29115    }
29116
29117    #[test]
29118    fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
29119        // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
29120        // arm must key off [`MeshPolicy::mtls_required`], not the raw
29121        // `.mtls_required` field access. Structurally: toggling ONLY
29122        // the `mtls_required` slot on an otherwise-default MeshPolicy
29123        // must flip `is_empty()` from `true` (all-`None`) to `false`
29124        // (one axis carries a value); the flip must be observed for
29125        // both `Some(true)` and `Some(false)` since the emptiness
29126        // semantic reads "any axis carries a value" — not "any axis
29127        // carries a truthy value" — the same non-collapsing shape the
29128        // sibling M2 [`crate::LimitsSpec::is_empty`] /
29129        // [`crate::BehaviorSpec::is_empty`] predicates carry on their
29130        // peer `Option<T>`-typed slot surfaces.
29131        //
29132        // Pins against a future silent detour that re-derived the
29133        // emptiness predicate off a peer axis (an accidental
29134        // `.rate_limit.is_none()`-only chain that dropped the
29135        // `mtls_required` arm entirely), a `mtls_required == Some(_)`
29136        // collapse to a truthy-only check (which would silently
29137        // classify `Some(false)` as empty), or an accessor-side
29138        // detour that no longer names the substrate-primitive typed
29139        // dispatch (an accidental `self.mtls_required.unwrap_or(false)
29140        // == false` fallback in the accessor that would silently
29141        // classify both `None` and `Some(false)` as the same value).
29142        //
29143        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
29144        // (7cd2a28) accessor-composition pin on the sibling optional-
29145        // scalar axis — same "the emptiness / shape-gate predicate
29146        // must route through the substrate-primitive typed dispatch"
29147        // discipline extended onto the peer per-`:politicas` emptiness
29148        // predicate.
29149        let empty = MeshPolicy::default();
29150        assert!(
29151            empty.is_empty(),
29152            "MeshPolicy::default() must be is_empty() — every axis \
29153             defaults to None",
29154        );
29155        for required in [Some(true), Some(false)] {
29156            let p = MeshPolicy {
29157                mtls_required: required,
29158                ..MeshPolicy::default()
29159            };
29160            assert!(
29161                !p.is_empty(),
29162                "MeshPolicy::is_empty must return false when \
29163                 :mtls-required is {required:?} — the emptiness \
29164                 predicate reads \"any axis carries a value\", not \
29165                 \"any axis carries a truthy value\"",
29166            );
29167            assert_eq!(
29168                p.mtls_required().is_none(),
29169                p.is_empty(),
29170                "when :mtls-required is the only set axis, \
29171                 is_empty() must equal mtls_required().is_none() — \
29172                 the accessor and the emptiness predicate must \
29173                 route through the same substrate-primitive typed \
29174                 dispatch on the :mtls-required arm",
29175            );
29176        }
29177    }
29178
29179    #[test]
29180    fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
29181        // The by-copy pin: [`MeshPolicy::mtls_required`] returns
29182        // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
29183        // accessor must return by value, not by reference. Peer of the
29184        // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
29185        // borrow-invariant pin on the sibling `Option<String>` slot,
29186        // but extended onto the peer `Option<bool>` copy-invariant
29187        // shape — the accessor's returned `Option<bool>` must outlive
29188        // `&self` (multiple calls must return equal values from a
29189        // dropped-`&self` copy, since the returned Option carries no
29190        // borrow), and calling the accessor twice on the same
29191        // MeshPolicy must yield the same `Option<bool>` verbatim
29192        // (idempotent, no side effects on `&self`).
29193        //
29194        // Pins against a future silent detour that returned
29195        // `Option<&bool>` (which would type-check but silently break
29196        // every downstream caller — [`single_field_overlay`]'s first
29197        // parameter is `Option<T: Clone>`, and `&bool` would fold to a
29198        // detached copy at the call site), an accidental
29199        // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
29200        // would also type-check but return `Option<&bool>`), or a
29201        // one-arm-only accessor that reads `Some(*b)` in the Some arm
29202        // but reads a fresh Default::default() in the None arm.
29203        for required in [None, Some(true), Some(false)] {
29204            let p = MeshPolicy {
29205                mtls_required: required,
29206                ..MeshPolicy::default()
29207            };
29208            let first = p.mtls_required();
29209            let second = p.mtls_required();
29210            assert_eq!(
29211                first, second,
29212                "MeshPolicy::mtls_required must be idempotent — two \
29213                 successive calls on the same &self must return the \
29214                 same Option<bool>",
29215            );
29216            assert_eq!(
29217                first, required,
29218                "MeshPolicy::mtls_required must return :politicas \
29219                 :mtls-required verbatim by copy — got {first:?}, \
29220                 expected {required:?}",
29221            );
29222        }
29223    }
29224
29225    #[test]
29226    fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
29227        // The canonical per-`:politicas` `:retries` transient-failure-
29228        // retry-budget scalar pin: [`MeshPolicy::retries`] must return
29229        // the `:politicas :retries` typed `u32` verbatim as an
29230        // `Option<u32>`, byte-equal to the raw field access across every
29231        // representative value in the accept-set — `None` (cluster
29232        // default applies — typically "no retries beyond a single
29233        // dispatch attempt" the caixa-mesh `retry_overlay` builder
29234        // documents), `Some(1)` (the lower boundary of the
29235        // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
29236        // `AplicacaoSpec::validate_politicas` gate carves out on the
29237        // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
29238        // (the upper boundary the same gate carves out on the sibling
29239        // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
29240        // past-the-guard sentinel that pins the accessor doesn't perform
29241        // a silent bounds-collapse at the return path).
29242        //
29243        // Sibling of the peer per-`:politicas`
29244        // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
29245        // sibling `Option<Copy-T>` optional-scalar axis, extended to the
29246        // peer per-`:politicas` `Option<u32>` shape — second
29247        // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
29248        // Pins against a future silent detour that re-derived the retry
29249        // cap from a peer axis (an accidental `.circuit_breaker
29250        // .as_ref().map(|b| b.max_failures)` collapse that read the
29251        // breaker's max-failure count as a retry budget), a
29252        // `None → Some(0)` cluster-default projection (which would
29253        // silently re-introduce the `PolicyRetriesZero` refusal case at
29254        // the emit boundary), or a bounds-collapsing accessor that
29255        // clamped the return through `POLICY_RETRIES_MAX` (the
29256        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
29257        // must ship the raw slot verbatim so a validate-time gate
29258        // regression surfaces at the emit boundary rather than being
29259        // silently absorbed).
29260        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
29261            let p = MeshPolicy {
29262                retries,
29263                ..MeshPolicy::default()
29264            };
29265            assert_eq!(
29266                p.retries(),
29267                retries,
29268                "MeshPolicy::retries must return :politicas :retries \
29269                 verbatim (got {:?}, expected {retries:?})",
29270                p.retries(),
29271            );
29272            assert_eq!(
29273                p.retries(),
29274                p.retries,
29275                "MeshPolicy::retries must byte-equal the raw .retries \
29276                 field access across every value in the accept-set",
29277            );
29278        }
29279    }
29280
29281    #[test]
29282    fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
29283        // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
29284        // must key off [`MeshPolicy::retries`], not the raw `.retries`
29285        // field access. Structurally: toggling ONLY the `retries` slot
29286        // on an otherwise-default MeshPolicy must flip `is_empty()`
29287        // from `true` (all-`None`) to `false` (one axis carries a
29288        // value); the flip must be observed for every value in the
29289        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
29290        // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
29291        // the emptiness semantic reads "any axis carries a value" —
29292        // not "any axis carries a value the validate gate accepts" —
29293        // the same non-collapsing shape the peer M2
29294        // [`crate::LimitsSpec::is_empty`] /
29295        // [`crate::BehaviorSpec::is_empty`] predicates carry.
29296        //
29297        // Pins against a future silent detour that re-derived the
29298        // emptiness predicate off a peer axis (an accidental
29299        // `.rate_limit.is_none()`-only chain that dropped the
29300        // `retries` arm entirely), a `retries == Some(_)` collapse
29301        // that key-off a validate-gate-clamped bounds check (which
29302        // would silently classify a past-the-guard `Some(u32::MAX)`
29303        // as empty because it fails the `1..=POLICY_RETRIES_MAX`
29304        // check), or an accessor-side detour that no longer names the
29305        // substrate-primitive typed dispatch.
29306        //
29307        // Sibling of the peer per-`:politicas`
29308        // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
29309        // pin on the sibling `Option<Copy-T>` optional-scalar axis —
29310        // same "the emptiness predicate must route through the
29311        // substrate-primitive typed dispatch" discipline extended onto
29312        // the peer per-`:politicas` `Option<u32>` axis.
29313        let empty = MeshPolicy::default();
29314        assert!(
29315            empty.is_empty(),
29316            "MeshPolicy::default() must be is_empty() — every axis \
29317             defaults to None",
29318        );
29319        for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
29320            let p = MeshPolicy {
29321                retries,
29322                ..MeshPolicy::default()
29323            };
29324            assert!(
29325                !p.is_empty(),
29326                "MeshPolicy::is_empty must return false when \
29327                 :retries is {retries:?} — the emptiness \
29328                 predicate reads \"any axis carries a value\", not \
29329                 \"any axis carries a value the validate gate \
29330                 accepts\"",
29331            );
29332            assert_eq!(
29333                p.retries().is_none(),
29334                p.is_empty(),
29335                "when :retries is the only set axis, is_empty() \
29336                 must equal retries().is_none() — the accessor and \
29337                 the emptiness predicate must route through the same \
29338                 substrate-primitive typed dispatch on the :retries \
29339                 arm",
29340            );
29341        }
29342    }
29343
29344    #[test]
29345    fn mesh_policy_retries_projects_option_u32_by_copy() {
29346        // The by-copy pin: [`MeshPolicy::retries`] returns
29347        // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
29348        // accessor must return by value, not by reference. Sibling of
29349        // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
29350        // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
29351        // extended onto the sibling `Option<u32>` copy-invariant
29352        // shape — the accessor's returned `Option<u32>` must outlive
29353        // `&self` (multiple calls must return equal values from a
29354        // dropped-`&self` copy, since the returned Option carries no
29355        // borrow), and calling the accessor twice on the same
29356        // MeshPolicy must yield the same `Option<u32>` verbatim
29357        // (idempotent, no side effects on `&self`).
29358        //
29359        // Pins against a future silent detour that returned
29360        // `Option<&u32>` (which would type-check but silently break
29361        // every downstream caller — [`crate::render::single_field_overlay`]'s
29362        // first parameter is `Option<T: Clone>`, and `&u32` would
29363        // fold to a detached copy at the call site), an accidental
29364        // `Option::as_ref()` projection (`self.retries.as_ref()` would
29365        // also type-check but return `Option<&u32>`), or a one-arm-
29366        // only accessor that reads `Some(*n)` in the Some arm but
29367        // reads a fresh `Default::default()` (`0_u32`) in the None
29368        // arm.
29369        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
29370            let p = MeshPolicy {
29371                retries,
29372                ..MeshPolicy::default()
29373            };
29374            let first = p.retries();
29375            let second = p.retries();
29376            assert_eq!(
29377                first, second,
29378                "MeshPolicy::retries must be idempotent — two \
29379                 successive calls on the same &self must return the \
29380                 same Option<u32>",
29381            );
29382            assert_eq!(
29383                first, retries,
29384                "MeshPolicy::retries must return :politicas :retries \
29385                 verbatim by copy — got {first:?}, expected {retries:?}",
29386            );
29387        }
29388    }
29389
29390    #[test]
29391    fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
29392        // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
29393        // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
29394        // return the `:politicas :timeout` typed [`Duration`] verbatim
29395        // as an `Option<Duration>`, byte-equal to the raw field access
29396        // across every representative value in the accept-set — `None`
29397        // (cluster default applies — typically the gateway class's
29398        // implementation-side per-request wall-clock cap the caixa-mesh
29399        // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
29400        // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
29401        // set the surrounding `AplicacaoSpec::validate_politicas` gate
29402        // carves out on the sibling `PolicyTimeoutZero` /
29403        // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
29404        // (the upper boundary the same gate carves out on the sibling
29405        // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
29406        // (a past-the-guard sentinel that pins the accessor doesn't
29407        // perform a silent bounds-collapse into `None` on the zero-
29408        // Duration arm — validate rejects zero but the accessor must
29409        // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
29410        // past-the-guard sentinel that pins the accessor doesn't
29411        // perform a silent bounds-collapse at the return path).
29412        //
29413        // Sibling of the peer per-`:politicas`
29414        // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
29415        // `Option<u32>` optional-scalar axis and the peer per-
29416        // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
29417        // pin on the sibling `Option<bool>` optional-scalar axis,
29418        // extended onto the peer per-`:politicas` `Option<Duration>`
29419        // shape — third `Option<Copy-T>`-return accessor on the M3
29420        // mesh-slot family. Pins against a future silent detour that
29421        // re-derived the per-call cap from a peer axis (an accidental
29422        // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
29423        // read the breaker's rolling-window duration as a per-call
29424        // deadline), a `None → Some(Duration::MAX)` cluster-default
29425        // projection (which would silently re-introduce the
29426        // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
29427        // blocking" arm at the emit boundary), or a bounds-collapsing
29428        // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
29429        // (the `AplicacaoSpec::validate` gate owns the bounds; the
29430        // accessor must ship the raw slot verbatim so a validate-time
29431        // gate regression surfaces at the emit boundary rather than
29432        // being silently absorbed).
29433        for timeout in [
29434            None,
29435            Some(Duration::from_millis(1)),
29436            Some(POLICY_TIMEOUT_MAX),
29437            Some(Duration::ZERO),
29438            Some(Duration::MAX),
29439        ] {
29440            let p = MeshPolicy {
29441                timeout,
29442                ..MeshPolicy::default()
29443            };
29444            assert_eq!(
29445                p.timeout(),
29446                timeout,
29447                "MeshPolicy::timeout must return :politicas :timeout \
29448                 verbatim (got {:?}, expected {timeout:?})",
29449                p.timeout(),
29450            );
29451            assert_eq!(
29452                p.timeout(),
29453                p.timeout,
29454                "MeshPolicy::timeout must byte-equal the raw .timeout \
29455                 field access across every value in the accept-set",
29456            );
29457        }
29458    }
29459
29460    #[test]
29461    fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
29462        // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
29463        // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
29464        // field access. Structurally: toggling ONLY the `timeout` slot
29465        // on an otherwise-default MeshPolicy must flip `is_empty()`
29466        // from `true` (all-`None`) to `false` (one axis carries a
29467        // value); the flip must be observed for every value in the
29468        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
29469        // gate accepts (`Some(Duration::from_millis(1))`,
29470        // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
29471        // reads "any axis carries a value" — not "any axis carries a
29472        // value the validate gate accepts" — the same non-collapsing
29473        // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
29474        // [`crate::BehaviorSpec::is_empty`] predicates carry.
29475        //
29476        // Pins against a future silent detour that re-derived the
29477        // emptiness predicate off a peer axis (an accidental
29478        // `.rate_limit.is_none()`-only chain that dropped the
29479        // `timeout` arm entirely), a `timeout == Some(_)` collapse
29480        // that key-off a validate-gate-clamped bounds check (which
29481        // would silently classify a past-the-guard `Some(Duration::MAX)`
29482        // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
29483        // check), or an accessor-side detour that no longer names the
29484        // substrate-primitive typed dispatch.
29485        //
29486        // Sibling of the peer per-`:politicas`
29487        // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
29488        // the sibling `Option<u32>` optional-scalar axis and the peer
29489        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
29490        // accessor-composition pin on the sibling `Option<bool>`
29491        // optional-scalar axis — same "the emptiness predicate must
29492        // route through the substrate-primitive typed dispatch"
29493        // discipline extended onto the peer per-`:politicas`
29494        // `Option<Duration>` axis.
29495        let empty = MeshPolicy::default();
29496        assert!(
29497            empty.is_empty(),
29498            "MeshPolicy::default() must be is_empty() — every axis \
29499             defaults to None",
29500        );
29501        for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
29502            let p = MeshPolicy {
29503                timeout,
29504                ..MeshPolicy::default()
29505            };
29506            assert!(
29507                !p.is_empty(),
29508                "MeshPolicy::is_empty must return false when \
29509                 :timeout is {timeout:?} — the emptiness \
29510                 predicate reads \"any axis carries a value\", not \
29511                 \"any axis carries a value the validate gate \
29512                 accepts\"",
29513            );
29514            assert_eq!(
29515                p.timeout().is_none(),
29516                p.is_empty(),
29517                "when :timeout is the only set axis, is_empty() \
29518                 must equal timeout().is_none() — the accessor and \
29519                 the emptiness predicate must route through the same \
29520                 substrate-primitive typed dispatch on the :timeout \
29521                 arm",
29522            );
29523        }
29524    }
29525
29526    #[test]
29527    fn mesh_policy_timeout_projects_option_duration_by_copy() {
29528        // The by-copy pin: [`MeshPolicy::timeout`] returns
29529        // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
29530        // and the accessor must return by value, not by reference.
29531        // Sibling of the peer per-`:politicas`
29532        // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
29533        // sibling `Option<u32>` optional-scalar axis and the peer
29534        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
29535        // by-copy pin on the sibling `Option<bool>` optional-scalar
29536        // axis, extended onto the peer per-`:politicas`
29537        // `Option<Duration>` copy-invariant shape — the accessor's
29538        // returned `Option<Duration>` must outlive `&self` (multiple
29539        // calls must return equal values from a dropped-`&self`
29540        // copy, since the returned Option carries no borrow), and
29541        // calling the accessor twice on the same MeshPolicy must
29542        // yield the same `Option<Duration>` verbatim (idempotent, no
29543        // side effects on `&self`).
29544        //
29545        // Pins against a future silent detour that returned
29546        // `Option<&Duration>` (which would type-check but silently
29547        // break every downstream caller — [`crate::render::single_field_overlay`]'s
29548        // first parameter is `Option<T: Clone>`, and `&Duration`
29549        // would fold to a detached copy at the call site), an
29550        // accidental `Option::as_ref()` projection
29551        // (`self.timeout.as_ref()` would also type-check but return
29552        // `Option<&Duration>`), or a one-arm-only accessor that
29553        // reads `Some(*d)` in the Some arm but reads a fresh
29554        // `Default::default()` (`Duration::ZERO`) in the None arm
29555        // (which would silently re-classify every unset `:timeout`
29556        // as the `PolicyTimeoutZero`-refused zero-Duration value at
29557        // the accessor boundary).
29558        for timeout in [
29559            None,
29560            Some(Duration::from_millis(1)),
29561            Some(POLICY_TIMEOUT_MAX),
29562            Some(Duration::ZERO),
29563            Some(Duration::MAX),
29564        ] {
29565            let p = MeshPolicy {
29566                timeout,
29567                ..MeshPolicy::default()
29568            };
29569            let first = p.timeout();
29570            let second = p.timeout();
29571            assert_eq!(
29572                first, second,
29573                "MeshPolicy::timeout must be idempotent — two \
29574                 successive calls on the same &self must return the \
29575                 same Option<Duration>",
29576            );
29577            assert_eq!(
29578                first, timeout,
29579                "MeshPolicy::timeout must return :politicas :timeout \
29580                 verbatim by copy — got {first:?}, expected {timeout:?}",
29581            );
29582        }
29583    }
29584
29585    #[test]
29586    fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
29587        // The canonical per-`:politicas` `:rate-limit` Envoy-
29588        // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
29589        // [`MeshPolicy::rate_limit`] must return the `:politicas
29590        // :rate-limit` typed [`RateLimit`] verbatim as an
29591        // `Option<RateLimit>`, byte-equal to the raw field access
29592        // across every representative value in the accept-set — `None`
29593        // (cluster default applies — no per-Aplicacao rate declaration,
29594        // the gateway-class per-listener default arm the future caixa-
29595        // mesh `local_rate_limit_overlay` emitter documents),
29596        // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
29597        // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
29598        // accept-set the surrounding
29599        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
29600        // sibling `PolicyRateLimitZero` refusal, paired with the
29601        // canonical-window "1 second" arm of the three-unit
29602        // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
29603        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
29604        // (the upper boundary the same gate carves out on the sibling
29605        // `PolicyRateLimitExceedsCap` refusal, paired with the
29606        // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
29607        // (a past-the-guard sentinel that pins the accessor doesn't
29608        // perform a silent bounds-collapse into `None` on the
29609        // zero-rate/zero-window arm — validate rejects zero but the
29610        // accessor must ship the raw slot verbatim so a validate-time
29611        // gate regression surfaces at the emit boundary rather than
29612        // being silently absorbed), and
29613        // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
29614        // (a past-the-guard sentinel that pins the accessor doesn't
29615        // perform a silent bounds-collapse at the return path).
29616        //
29617        // First `Option<Copy-composite-T>`-return accessor pin on the
29618        // M3 mesh-slot family (peer of the sibling per-`:politicas`
29619        // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
29620        // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
29621        // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
29622        // Copy accessor pins, extended onto the peer per-`:politicas`
29623        // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
29624        // and the accessor returns by value). Pins against a future
29625        // silent detour that re-derived the rate declaration from a
29626        // peer axis (an accidental
29627        // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
29628        // collapse that read the breaker's trip threshold + rolling
29629        // window as a rate declaration), a `None → Some(default())`
29630        // cluster-default projection (which would silently re-
29631        // introduce a "cluster default is 0/s" arm the emit boundary
29632        // would take as "declared but inert" — the canonical
29633        // declared-but-inert footgun the sibling
29634        // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
29635        // amplification-shape axis), a bounds-collapsing accessor
29636        // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
29637        // clamped `rl.window` through [`is_canonical_rate_limit_window`]
29638        // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
29639        // accessor must ship the raw slot verbatim), or a
29640        // by-reference detour (`Option<&RateLimit>`) that broke every
29641        // downstream consumer keying off `Option<RateLimit>` by-copy.
29642        for rl in [
29643            None,
29644            Some(RateLimit {
29645                rate: 1,
29646                window: Duration::from_secs(1),
29647            }),
29648            Some(RateLimit {
29649                rate: POLICY_RATE_LIMIT_MAX,
29650                window: Duration::from_secs(3600),
29651            }),
29652            Some(RateLimit {
29653                rate: 0,
29654                window: Duration::ZERO,
29655            }),
29656            Some(RateLimit {
29657                rate: u32::MAX,
29658                window: Duration::MAX,
29659            }),
29660        ] {
29661            let p = MeshPolicy {
29662                rate_limit: rl,
29663                ..MeshPolicy::default()
29664            };
29665            assert_eq!(
29666                p.rate_limit(),
29667                rl,
29668                "MeshPolicy::rate_limit must return :politicas :rate-limit \
29669                 verbatim (got {:?}, expected {rl:?})",
29670                p.rate_limit(),
29671            );
29672            assert_eq!(
29673                p.rate_limit(),
29674                p.rate_limit,
29675                "MeshPolicy::rate_limit must byte-equal the raw \
29676                 .rate_limit field access across every value in the \
29677                 accept-set",
29678            );
29679        }
29680    }
29681
29682    #[test]
29683    fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
29684        // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
29685        // must key off [`MeshPolicy::rate_limit`], not the raw
29686        // `.rate_limit` field access. Structurally: toggling ONLY the
29687        // `rate_limit` slot on an otherwise-default MeshPolicy must
29688        // flip `is_empty()` from `true` (all-`None`) to `false` (one
29689        // axis carries a value); the flip must be observed for every
29690        // representative value in the accept-set the surrounding
29691        // [`AplicacaoSpec::validate_politicas`] gate accepts
29692        // (`Some(RateLimit { rate: 1, window: 1s })`,
29693        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
29694        // since the emptiness semantic reads "any axis carries a
29695        // value" — not "any axis carries a value the validate gate
29696        // accepts" — the same non-collapsing shape the peer M2
29697        // [`crate::LimitsSpec::is_empty`] /
29698        // [`crate::BehaviorSpec::is_empty`] predicates carry.
29699        //
29700        // Pins against a future silent detour that re-derived the
29701        // emptiness predicate off a peer axis (an accidental
29702        // `.timeout.is_none()`-only chain that dropped the
29703        // `rate_limit` arm entirely — the last unlifted inline field
29704        // access on `is_empty` before this lift), a `rate_limit ==
29705        // Some(_)` collapse that key-off a validate-gate-clamped
29706        // bounds check (which would silently classify a past-the-
29707        // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
29708        // because it fails the value-shape gate), or an accessor-
29709        // side detour that no longer names the substrate-primitive
29710        // typed dispatch.
29711        //
29712        // Fourth "the emptiness predicate must route through the
29713        // substrate-primitive typed dispatch" composition pin on the
29714        // M3 mesh-slot family — closes the last unlifted composition
29715        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
29716        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
29717        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
29718        // 7073d0f is_empty-composition pins on the sibling primitive-
29719        // Copy axes, extended onto the peer per-`:politicas`
29720        // composite-Copy `Option<RateLimit>` axis).
29721        let empty = MeshPolicy::default();
29722        assert!(
29723            empty.is_empty(),
29724            "MeshPolicy::default() must be is_empty() — every axis \
29725             defaults to None",
29726        );
29727        for rl in [
29728            RateLimit {
29729                rate: 1,
29730                window: Duration::from_secs(1),
29731            },
29732            RateLimit {
29733                rate: POLICY_RATE_LIMIT_MAX,
29734                window: Duration::from_secs(3600),
29735            },
29736        ] {
29737            let p = MeshPolicy {
29738                rate_limit: Some(rl),
29739                ..MeshPolicy::default()
29740            };
29741            assert!(
29742                !p.is_empty(),
29743                "MeshPolicy::is_empty must return false when \
29744                 :rate-limit is {rl:?} — the emptiness predicate \
29745                 reads \"any axis carries a value\", not \"any axis \
29746                 carries a value the validate gate accepts\"",
29747            );
29748            assert_eq!(
29749                p.rate_limit().is_none(),
29750                p.is_empty(),
29751                "when :rate-limit is the only set axis, is_empty() \
29752                 must equal rate_limit().is_none() — the accessor \
29753                 and the emptiness predicate must route through the \
29754                 same substrate-primitive typed dispatch on the \
29755                 :rate-limit arm",
29756            );
29757        }
29758    }
29759
29760    #[test]
29761    fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
29762        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
29763        // `:rate-limit` value-shape gate must key off
29764        // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
29765        // field bind. Structurally: a `MeshPolicy` whose only set
29766        // axis is a `Some(RateLimit { rate: 0, .. })` must surface
29767        // the `PolicyRateLimitZero` refusal exactly, and the same
29768        // MeshPolicy with the rate at the canonical lower boundary
29769        // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
29770        // The pair jointly pins the accessor + validate-gate
29771        // composition: any future silent detour that had the accessor
29772        // omit the `Some(RateLimit { rate: 0, .. })` arm (a
29773        // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
29774        // silently absorb the `PolicyRateLimitZero` refusal at the
29775        // accessor boundary — the composition pin catches that at
29776        // caixa-core build time.
29777        //
29778        // Sibling of the peer [`validate_politicas`]
29779        // `:mtls-required` / `:retries` / `:timeout` composition pins
29780        // on the sibling primitive-Copy optional-scalar axes — same
29781        // "the validate / shape-gate predicate must route through the
29782        // substrate-primitive typed dispatch" discipline extended
29783        // onto the peer per-`:politicas` composite-Copy
29784        // `Option<RateLimit>` axis. Second composition-with-accessor
29785        // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
29786        // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
29787        let mut spec = three_member_spec();
29788        spec.politicas = MeshPolicy {
29789            rate_limit: Some(RateLimit {
29790                rate: 0,
29791                window: Duration::from_secs(1),
29792            }),
29793            ..MeshPolicy::default()
29794        };
29795        assert!(
29796            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
29797            "validate_politicas must reject rate == 0 with \
29798             PolicyRateLimitZero — the accessor and the validate gate \
29799             must route through the same substrate-primitive typed \
29800             dispatch on the :rate-limit zero-floor arm",
29801        );
29802        spec.politicas = MeshPolicy {
29803            rate_limit: Some(RateLimit {
29804                rate: 1,
29805                window: Duration::from_secs(1),
29806            }),
29807            ..MeshPolicy::default()
29808        };
29809        assert!(
29810            spec.validate().is_ok(),
29811            "validate_politicas must accept rate == 1 (the canonical \
29812             lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
29813             set) with a canonical 1s window",
29814        );
29815    }
29816
29817    #[test]
29818    fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
29819        // The canonical per-`:politicas` `:circuit-breaker` Envoy-
29820        // `outlier_detection`-mesh consecutive-failure-ejection scalar
29821        // pin: [`MeshPolicy::circuit_breaker`] must return the
29822        // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
29823        // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
29824        // raw field access across every representative value in the
29825        // accept-set — `None` (cluster default applies — no
29826        // per-Aplicacao breaker declaration, the gateway-class per-
29827        // listener default arm the future caixa-mesh
29828        // `outlier_detection_overlay` emitter documents),
29829        // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
29830        // (the lower boundary of the accept-set the surrounding
29831        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
29832        // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
29833        // refusals),
29834        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
29835        // (the upper boundary the same gate carves out on the sibling
29836        // `PolicyBreakerMaxFailuresExceedsCap` /
29837        // `PolicyBreakerWindowExceedsCap` refusals),
29838        // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
29839        // (a past-the-guard sentinel that pins the accessor doesn't
29840        // perform a silent bounds-collapse into `None` on the
29841        // zero-failures/zero-window arm — validate rejects zero but
29842        // the accessor must ship the raw slot verbatim so a validate-
29843        // time gate regression surfaces at the emit boundary rather
29844        // than being silently absorbed), and
29845        // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
29846        // (a past-the-guard sentinel that pins the accessor doesn't
29847        // perform a silent bounds-collapse at the return path).
29848        //
29849        // Second `Option<Copy-composite-T>`-return accessor pin on the
29850        // M3 mesh-slot family (peer of the sibling per-`:politicas`
29851        // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
29852        // composite-Copy accessor pin, and of the sibling per-
29853        // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
29854        // [`MeshPolicy::retries`] bdfb399 /
29855        // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
29856        // accessor pins). Pins against a future silent detour that
29857        // re-derived the breaker declaration from a peer axis (an
29858        // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
29859        // collapse that read the rate-limit's bucket capacity + refill
29860        // period as a breaker declaration), a `None → Some(default())`
29861        // cluster-default projection (which would silently re-
29862        // introduce the `PolicyBreakerZeroFailures` /
29863        // `PolicyBreakerZeroWindow` refusal cases at the emit
29864        // boundary), a bounds-collapsing accessor that clamped
29865        // `cb.max_failures` through
29866        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
29867        // through [`POLICY_BREAKER_WINDOW_MAX`] (the
29868        // [`AplicacaoSpec::validate`] gate owns the bounds; the
29869        // accessor must ship the raw slot verbatim), or a
29870        // by-reference detour (`Option<&CircuitBreaker>`) that broke
29871        // every downstream consumer keying off `Option<CircuitBreaker>`
29872        // by-copy.
29873        for cb in [
29874            None,
29875            Some(CircuitBreaker {
29876                max_failures: 1,
29877                window: Duration::from_millis(1),
29878            }),
29879            Some(CircuitBreaker {
29880                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
29881                window: POLICY_BREAKER_WINDOW_MAX,
29882            }),
29883            Some(CircuitBreaker {
29884                max_failures: 0,
29885                window: Duration::ZERO,
29886            }),
29887            Some(CircuitBreaker {
29888                max_failures: u32::MAX,
29889                window: Duration::MAX,
29890            }),
29891        ] {
29892            let p = MeshPolicy {
29893                circuit_breaker: cb,
29894                ..MeshPolicy::default()
29895            };
29896            assert_eq!(
29897                p.circuit_breaker(),
29898                cb,
29899                "MeshPolicy::circuit_breaker must return :politicas \
29900                 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
29901                p.circuit_breaker(),
29902            );
29903            assert_eq!(
29904                p.circuit_breaker(),
29905                p.circuit_breaker,
29906                "MeshPolicy::circuit_breaker must byte-equal the raw \
29907                 .circuit_breaker field access across every value in \
29908                 the accept-set",
29909            );
29910        }
29911    }
29912
29913    #[test]
29914    fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
29915        // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
29916        // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
29917        // `.circuit_breaker` field access. Structurally: toggling ONLY
29918        // the `circuit_breaker` slot on an otherwise-default MeshPolicy
29919        // must flip `is_empty()` from `true` (all-`None`) to `false`
29920        // (one axis carries a value); the flip must be observed for
29921        // every representative value in the accept-set the surrounding
29922        // [`AplicacaoSpec::validate_politicas`] gate accepts
29923        // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
29924        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
29925        // since the emptiness semantic reads "any axis carries a
29926        // value" — not "any axis carries a value the validate gate
29927        // accepts" — the same non-collapsing shape the peer M2
29928        // [`crate::LimitsSpec::is_empty`] /
29929        // [`crate::BehaviorSpec::is_empty`] predicates carry.
29930        //
29931        // Pins against a future silent detour that re-derived the
29932        // emptiness predicate off a peer axis (an accidental
29933        // `.rate_limit.is_none()`-only chain that dropped the
29934        // `circuit_breaker` arm entirely — the last unlifted inline
29935        // field access on `is_empty` before this lift), a
29936        // `circuit_breaker == Some(_)` collapse that key-off a
29937        // validate-gate-clamped bounds check (which would silently
29938        // classify a past-the-guard `Some(CircuitBreaker { max_failures:
29939        // 0, window: 0s })` as empty because it fails the value-shape
29940        // gate), or an accessor-side detour that no longer names the
29941        // substrate-primitive typed dispatch.
29942        //
29943        // Fifth "the emptiness predicate must route through the
29944        // substrate-primitive typed dispatch" composition pin on the
29945        // M3 mesh-slot family — closes the last unlifted composition
29946        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
29947        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
29948        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
29949        // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
29950        // composition pins on the sibling primitive-Copy + composite-
29951        // Copy axes, extended onto the peer per-`:politicas`
29952        // composite-Copy `Option<CircuitBreaker>` axis).
29953        let empty = MeshPolicy::default();
29954        assert!(
29955            empty.is_empty(),
29956            "MeshPolicy::default() must be is_empty() — every axis \
29957             defaults to None",
29958        );
29959        for cb in [
29960            CircuitBreaker {
29961                max_failures: 1,
29962                window: Duration::from_millis(1),
29963            },
29964            CircuitBreaker {
29965                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
29966                window: POLICY_BREAKER_WINDOW_MAX,
29967            },
29968        ] {
29969            let p = MeshPolicy {
29970                circuit_breaker: Some(cb),
29971                ..MeshPolicy::default()
29972            };
29973            assert!(
29974                !p.is_empty(),
29975                "MeshPolicy::is_empty must return false when \
29976                 :circuit-breaker is {cb:?} — the emptiness predicate \
29977                 reads \"any axis carries a value\", not \"any axis \
29978                 carries a value the validate gate accepts\"",
29979            );
29980            assert_eq!(
29981                p.circuit_breaker().is_none(),
29982                p.is_empty(),
29983                "when :circuit-breaker is the only set axis, \
29984                 is_empty() must equal circuit_breaker().is_none() — \
29985                 the accessor and the emptiness predicate must route \
29986                 through the same substrate-primitive typed dispatch \
29987                 on the :circuit-breaker arm",
29988            );
29989        }
29990    }
29991
29992    #[test]
29993    fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
29994        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
29995        // `:circuit-breaker` value-shape gate must key off
29996        // [`MeshPolicy::circuit_breaker`], not the raw
29997        // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
29998        // whose only set axis is a `Some(CircuitBreaker { max_failures:
29999        // 0, .. })` must surface the `PolicyBreakerZeroFailures`
30000        // refusal exactly, and the same MeshPolicy with the breaker at
30001        // the canonical lower boundary
30002        // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
30003        // pass validate. The pair jointly pins the accessor +
30004        // validate-gate composition: any future silent detour that had
30005        // the accessor omit the `Some(CircuitBreaker { max_failures:
30006        // 0, .. })` arm (a
30007        // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
30008        // collapse) would silently absorb the
30009        // `PolicyBreakerZeroFailures` refusal at the accessor
30010        // boundary — the composition pin catches that at caixa-core
30011        // build time.
30012        //
30013        // Sibling of the peer [`validate_politicas`]
30014        // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
30015        // composition pins on the sibling primitive-Copy + composite-
30016        // Copy optional-scalar axes — same "the validate / shape-gate
30017        // predicate must route through the substrate-primitive typed
30018        // dispatch" discipline extended onto the peer per-`:politicas`
30019        // composite-Copy `Option<CircuitBreaker>` axis. Second
30020        // composition-with-accessor pin on the M3 mesh-slot
30021        // `Option<CircuitBreaker>` arm alongside the
30022        // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
30023        let mut spec = three_member_spec();
30024        spec.politicas = MeshPolicy {
30025            circuit_breaker: Some(CircuitBreaker {
30026                max_failures: 0,
30027                window: Duration::from_millis(1),
30028            }),
30029            ..MeshPolicy::default()
30030        };
30031        assert!(
30032            matches!(
30033                spec.validate(),
30034                Err(AplicacaoError::PolicyBreakerZeroFailures)
30035            ),
30036            "validate_politicas must reject max_failures == 0 with \
30037             PolicyBreakerZeroFailures — the accessor and the validate \
30038             gate must route through the same substrate-primitive \
30039             typed dispatch on the :circuit-breaker zero-floor arm",
30040        );
30041        spec.politicas = MeshPolicy {
30042            circuit_breaker: Some(CircuitBreaker {
30043                max_failures: 1,
30044                window: Duration::from_millis(1),
30045            }),
30046            ..MeshPolicy::default()
30047        };
30048        assert!(
30049            spec.validate().is_ok(),
30050            "validate_politicas must accept a CircuitBreaker at the \
30051             canonical lower boundary (max_failures = 1, window = \
30052             1ms) — the accessor and the validate gate must route \
30053             through the same substrate-primitive typed dispatch on \
30054             the :circuit-breaker arm",
30055        );
30056    }
30057
30058    #[test]
30059    fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
30060        // The canonical per-`:politicas :circuit-breaker` `:max-failures`
30061        // Envoy-outlier-detection trip-threshold scalar pin:
30062        // [`CircuitBreaker::max_failures`] must return the
30063        // `:politicas :circuit-breaker :max-failures` typed `u32`
30064        // verbatim, byte-equal to the raw field access across every
30065        // representative value in the accept-set — `1` (the lower
30066        // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
30067        // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
30068        // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
30069        // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
30070        // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
30071        // refusal), `0` (a past-the-guard sentinel that pins the accessor
30072        // doesn't perform a silent bounds-collapse into `1` on the zero
30073        // arm — validate rejects zero but the accessor must ship the
30074        // raw slot verbatim so a validate-time gate regression surfaces
30075        // at the emit boundary rather than being silently absorbed),
30076        // `u32::MAX` (a past-the-guard sentinel that pins the accessor
30077        // doesn't perform a silent bounds-collapse through
30078        // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
30079        //
30080        // First sub-struct required-scalar accessor pin on the M3
30081        // mesh-slot family — sibling in shape to the peer per-`:membros`
30082        // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
30083        // (a40b0e3) required-`String`-carry accessor pins and the peer
30084        // per-`:contratos` [`WitContract::source`] /
30085        // [`WitContract::destination`] (7f0fd43) required-`String`-carry
30086        // accessor pins, extended onto the peer per-`CircuitBreaker`
30087        // required-`u32` scalar-value axis. Pins against a future silent
30088        // detour that re-derived the trip threshold from a peer axis (an
30089        // accidental `self.window.as_secs() as u32` collapse that read
30090        // the breaker's rolling-window duration as a failure count), a
30091        // `0 → 1` cluster-default projection (which would silently absorb
30092        // the `PolicyBreakerZeroFailures` refusal case at the accessor
30093        // boundary), or a bounds-collapsing accessor that clamped the
30094        // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
30095        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
30096        // must ship the raw slot verbatim).
30097        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
30098            let cb = CircuitBreaker {
30099                max_failures,
30100                window: Duration::from_secs(60),
30101            };
30102            assert_eq!(
30103                cb.max_failures(),
30104                max_failures,
30105                "CircuitBreaker::max_failures must return :politicas \
30106                 :circuit-breaker :max-failures verbatim (got {}, \
30107                 expected {max_failures})",
30108                cb.max_failures(),
30109            );
30110            assert_eq!(
30111                cb.max_failures(),
30112                cb.max_failures,
30113                "CircuitBreaker::max_failures must byte-equal the raw \
30114                 .max_failures field access across every value in the \
30115                 u32 accept-set",
30116            );
30117        }
30118    }
30119
30120    #[test]
30121    fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
30122        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
30123        // `:circuit-breaker :max-failures` zero-floor arm must key off
30124        // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
30125        // field access. Structurally: a `CircuitBreaker { max_failures:
30126        // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
30127        // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
30128        // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
30129        // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
30130        // pass validate. The pair jointly pins the accessor +
30131        // validate-gate composition: any future silent detour that had
30132        // the accessor return a fresh `1` on the zero arm (a
30133        // `.max_failures().max(1)` collapse) would silently absorb the
30134        // `PolicyBreakerZeroFailures` refusal at the accessor boundary
30135        // and the validate gate would accept a struct-literal
30136        // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
30137        // catches that at caixa-core build time.
30138        //
30139        // Peer of the sibling per-`:politicas`
30140        // [`MeshPolicy::mtls_required`] (c0110f1) /
30141        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
30142        // (7073d0f) accessor-composition pins on the sibling optional-
30143        // scalar axes — same "the validate / shape-gate predicate must
30144        // route through the substrate-primitive typed dispatch"
30145        // discipline extended onto the peer per-`CircuitBreaker`
30146        // required-scalar composition axis.
30147        let mut spec = three_member_spec();
30148        spec.politicas = MeshPolicy {
30149            circuit_breaker: Some(CircuitBreaker {
30150                max_failures: 0,
30151                window: Duration::from_secs(60),
30152            }),
30153            ..MeshPolicy::default()
30154        };
30155        assert!(
30156            matches!(
30157                spec.validate(),
30158                Err(AplicacaoError::PolicyBreakerZeroFailures)
30159            ),
30160            "validate_politicas must reject max_failures == 0 with \
30161             PolicyBreakerZeroFailures — the accessor and the validate \
30162             gate must route through the same substrate-primitive typed \
30163             dispatch on the :max-failures zero-floor arm",
30164        );
30165        spec.politicas = MeshPolicy {
30166            circuit_breaker: Some(CircuitBreaker {
30167                max_failures: 1,
30168                window: Duration::from_secs(60),
30169            }),
30170            ..MeshPolicy::default()
30171        };
30172        assert!(
30173            spec.validate().is_ok(),
30174            "validate_politicas must accept max_failures == 1 (the \
30175             lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
30176             accept-set)",
30177        );
30178    }
30179
30180    #[test]
30181    fn circuit_breaker_max_failures_projects_u32_by_copy() {
30182        // The by-copy pin: [`CircuitBreaker::max_failures`] returns
30183        // `u32` by copy — `u32` is `Copy` and the accessor must return
30184        // by value, not by reference. Peer of the sibling
30185        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
30186        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
30187        // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
30188        // optional-scalar axes, extended onto the peer
30189        // per-`CircuitBreaker` required-`u32` copy-invariant shape —
30190        // the accessor's returned `u32` must outlive `&self` (multiple
30191        // calls must return equal values from a dropped-`&self` copy,
30192        // since the returned scalar carries no borrow), and calling
30193        // the accessor twice on the same CircuitBreaker must yield the
30194        // same `u32` verbatim (idempotent, no side effects on `&self`).
30195        //
30196        // Pins against a future silent detour that returned `&u32`
30197        // (which would type-check but silently break every downstream
30198        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
30199        // first parameter is `u32`, and `&u32` would fold to a detached
30200        // copy at the call site with a `*` deref the sibling accessors
30201        // don't need), an accidental `.max_failures.wrapping_add(0)`
30202        // detour that returned a fresh copy through an arithmetic
30203        // no-op (breaking a future `const fn` regression), or a
30204        // one-arm-only accessor that returned a saturating value on
30205        // some sentinel input (breaking the pass-through invariant the
30206        // sibling required-scalar accessors carry).
30207        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
30208            let cb = CircuitBreaker {
30209                max_failures,
30210                window: Duration::from_secs(60),
30211            };
30212            let first = cb.max_failures();
30213            let second = cb.max_failures();
30214            assert_eq!(
30215                first, second,
30216                "CircuitBreaker::max_failures must be idempotent — two \
30217                 successive calls on the same &self must return the \
30218                 same u32",
30219            );
30220            assert_eq!(
30221                first, max_failures,
30222                "CircuitBreaker::max_failures must return :politicas \
30223                 :circuit-breaker :max-failures verbatim by copy — \
30224                 got {first}, expected {max_failures}",
30225            );
30226        }
30227    }
30228
30229    #[test]
30230    fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
30231        // The canonical per-`:politicas :circuit-breaker` `:window`
30232        // Envoy-outlier-detection rolling-observation-interval scalar
30233        // pin: [`CircuitBreaker::window`] must return the
30234        // `:politicas :circuit-breaker :window` typed `Duration`
30235        // verbatim, byte-equal to the raw field access across every
30236        // representative value in the accept-set — `Duration::from_millis(1)`
30237        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
30238        // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
30239        // gate carves out on the sibling `PolicyBreakerZeroWindow`
30240        // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
30241        // same gate carves out on the sibling
30242        // `PolicyBreakerWindowExceedsCap` refusal),
30243        // `Duration::ZERO` (a past-the-guard sentinel that pins the
30244        // accessor doesn't perform a silent bounds-collapse into
30245        // `Duration::from_millis(1)` on the zero arm — validate rejects
30246        // zero but the accessor must ship the raw slot verbatim so a
30247        // validate-time gate regression surfaces at the emit boundary
30248        // rather than being silently absorbed),
30249        // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
30250        // far above the 1h cap — that pins the accessor doesn't perform
30251        // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
30252        // at the return path).
30253        //
30254        // Second sub-struct required-scalar accessor pin on the M3
30255        // mesh-slot family — sibling in shape to the just-landed
30256        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
30257        // (3a74062) required-`u32` accessor pin on the peer
30258        // per-`CircuitBreaker` required-axis, extended onto the
30259        // per-sub-struct required-`Duration` axis. Pins against a
30260        // future silent detour that re-derived the observation window
30261        // from a peer axis (an accidental
30262        // `Duration::from_secs(self.max_failures as u64)` collapse that
30263        // read the breaker's trip count as an observation-interval
30264        // duration), a `Duration::ZERO → Duration::from_millis(1)`
30265        // cluster-default projection (which would silently absorb the
30266        // `PolicyBreakerZeroWindow` refusal case at the accessor
30267        // boundary), or a bounds-collapsing accessor that clamped the
30268        // return through `POLICY_BREAKER_WINDOW_MAX` (the
30269        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
30270        // must ship the raw slot verbatim).
30271        for window in [
30272            Duration::from_millis(1),
30273            POLICY_BREAKER_WINDOW_MAX,
30274            Duration::ZERO,
30275            Duration::from_secs(86_400),
30276        ] {
30277            let cb = CircuitBreaker {
30278                max_failures: 5,
30279                window,
30280            };
30281            assert_eq!(
30282                cb.window(),
30283                window,
30284                "CircuitBreaker::window must return :politicas \
30285                 :circuit-breaker :window verbatim (got {:?}, \
30286                 expected {window:?})",
30287                cb.window(),
30288            );
30289            assert_eq!(
30290                cb.window(),
30291                cb.window,
30292                "CircuitBreaker::window must byte-equal the raw \
30293                 .window field access across every value in the \
30294                 Duration accept-set",
30295            );
30296        }
30297    }
30298
30299    #[test]
30300    fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
30301        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
30302        // `:circuit-breaker :window` zero-floor arm must key off
30303        // [`CircuitBreaker::window`], not the raw `.window` field
30304        // access. Structurally: a `CircuitBreaker { window:
30305        // Duration::ZERO, .. }` embedded in a
30306        // `:politicas :circuit-breaker` slot must surface the
30307        // `PolicyBreakerZeroWindow` refusal exactly, and a
30308        // `CircuitBreaker { window: Duration::from_millis(1), .. }`
30309        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
30310        // accept-set) must pass validate. The pair jointly pins the
30311        // accessor + validate-gate composition: any future silent
30312        // detour that had the accessor return a fresh
30313        // `Duration::from_millis(1)` on the zero arm (a
30314        // `.window().max(Duration::from_millis(1))` collapse) would
30315        // silently absorb the `PolicyBreakerZeroWindow` refusal at the
30316        // accessor boundary and the validate gate would accept a
30317        // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
30318        // — the composition pin catches that at caixa-core build time.
30319        //
30320        // Peer of the sibling per-`CircuitBreaker`
30321        // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
30322        // pin on the peer required-scalar `:max-failures` axis — same
30323        // "the validate / shape-gate predicate must route through the
30324        // substrate-primitive typed dispatch" discipline extended onto
30325        // the peer per-`CircuitBreaker` required-`Duration` composition
30326        // axis.
30327        let mut spec = three_member_spec();
30328        spec.politicas = MeshPolicy {
30329            circuit_breaker: Some(CircuitBreaker {
30330                max_failures: 5,
30331                window: Duration::ZERO,
30332            }),
30333            ..MeshPolicy::default()
30334        };
30335        assert!(
30336            matches!(
30337                spec.validate(),
30338                Err(AplicacaoError::PolicyBreakerZeroWindow)
30339            ),
30340            "validate_politicas must reject window == Duration::ZERO \
30341             with PolicyBreakerZeroWindow — the accessor and the \
30342             validate gate must route through the same substrate-\
30343             primitive typed dispatch on the :window zero-floor arm",
30344        );
30345        spec.politicas = MeshPolicy {
30346            circuit_breaker: Some(CircuitBreaker {
30347                max_failures: 5,
30348                window: Duration::from_millis(1),
30349            }),
30350            ..MeshPolicy::default()
30351        };
30352        assert!(
30353            spec.validate().is_ok(),
30354            "validate_politicas must accept window == \
30355             Duration::from_millis(1) (the lower boundary of the \
30356             1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
30357        );
30358    }
30359
30360    #[test]
30361    fn circuit_breaker_window_projects_duration_by_copy() {
30362        // The by-copy pin: [`CircuitBreaker::window`] returns
30363        // `Duration` by copy — `Duration` is `Copy` and the accessor
30364        // must return by value, not by reference. Peer of the sibling
30365        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
30366        // (3a74062) by-copy pin on the peer required-scalar
30367        // `:max-failures` axis, extended onto the peer
30368        // per-`CircuitBreaker` required-`Duration` copy-invariant shape
30369        // — the accessor's returned `Duration` must outlive `&self`
30370        // (multiple calls must return equal values from a
30371        // dropped-`&self` copy, since the returned scalar carries no
30372        // borrow), and calling the accessor twice on the same
30373        // CircuitBreaker must yield the same `Duration` verbatim
30374        // (idempotent, no side effects on `&self`).
30375        //
30376        // Pins against a future silent detour that returned
30377        // `&Duration` (which would type-check but silently break every
30378        // downstream `Duration`-by-value consumer —
30379        // [`crate::render::require_positive_canonical_bounded_duration`]'s
30380        // first parameter is `Duration`, and `&Duration` would fold to
30381        // a detached copy at the call site with a `*` deref the sibling
30382        // accessors don't need), an accidental `.window + Duration::ZERO`
30383        // detour that returned a fresh copy through an arithmetic
30384        // no-op (breaking a future `const fn` regression), or a
30385        // one-arm-only accessor that returned a saturating value on
30386        // some sentinel input (breaking the pass-through invariant the
30387        // sibling required-scalar accessors carry).
30388        for window in [
30389            Duration::from_millis(1),
30390            POLICY_BREAKER_WINDOW_MAX,
30391            Duration::ZERO,
30392            Duration::from_secs(86_400),
30393        ] {
30394            let cb = CircuitBreaker {
30395                max_failures: 5,
30396                window,
30397            };
30398            let first = cb.window();
30399            let second = cb.window();
30400            assert_eq!(
30401                first, second,
30402                "CircuitBreaker::window must be idempotent — two \
30403                 successive calls on the same &self must return the \
30404                 same Duration",
30405            );
30406            assert_eq!(
30407                first, window,
30408                "CircuitBreaker::window must return :politicas \
30409                 :circuit-breaker :window verbatim by copy — \
30410                 got {first:?}, expected {window:?}",
30411            );
30412        }
30413    }
30414
30415    #[test]
30416    fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
30417        // Apex-identity pair-invariant pin composing both substrate-
30418        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
30419        // and [`WitContract::destination`] — at the emit-side call shape
30420        // every per-`(:de, :para)` CNP L4 port reader now takes. The
30421        // invariant, evaluated per-edge:
30422        //
30423        //   spec.port_for_destination(c.destination()) == expected_port
30424        //
30425        // where `expected_port` is `entrada.port` when
30426        // `c.destination() == entrada.destination()` and
30427        // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
30428        // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
30429        // pin on the per-`:entrada` axis — that pin encodes the apex
30430        // ingress L4 identity via `entrada.destination()`; this pin
30431        // encodes the per-edge L4 identity via `c.destination()`, and
30432        // both compose on the same substrate-primitive resolver so a
30433        // future refactor that silently split either accessor's apex
30434        // behavior surfaces at caixa-core build time.
30435        let mut spec = three_member_spec();
30436        if let Some(e) = spec.entrada.as_mut() {
30437            e.para = "cart".into();
30438            e.port = 8443;
30439        }
30440        let apex_contract = WitContract {
30441            de: "checkout".into(),
30442            para: "cart".into(),
30443            wit: "wasi:http/proxy".into(),
30444            endpoint: Some("/hello".into()),
30445            subject: None,
30446            slot: None,
30447        };
30448        assert_eq!(
30449            spec.port_for_destination(apex_contract.destination()),
30450            8443,
30451            "`spec.port_for_destination(c.destination())` must equal \
30452             `entrada.port` when the contract callee names the ingress \
30453             apex — the CNP per-edge L4 port and the HTTPRoute apex \
30454             backendRef port share this substrate-primitive resolver.",
30455        );
30456        let non_apex_contract = WitContract {
30457            de: "cart".into(),
30458            para: "payment".into(),
30459            wit: "wasi:http/proxy".into(),
30460            endpoint: Some("/charge".into()),
30461            subject: None,
30462            slot: None,
30463        };
30464        assert_eq!(
30465            spec.port_for_destination(non_apex_contract.destination()),
30466            DEFAULT_SERVICO_PORT,
30467            "`spec.port_for_destination(c.destination())` must fall back \
30468             to the substrate-canonical port floor when the contract \
30469             callee is not the ingress apex — the resolver's non-apex \
30470             arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
30471        );
30472    }
30473
30474    #[test]
30475    fn membro_key_consts_are_lower_camel_case_shape() {
30476        // Shape-pin: every `MEMBRO_KEY_*` const must be a
30477        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
30478        // `kebab-case` hyphens, no leading colon, no `PascalCase`
30479        // leading capital, no whitespace / dots) — the canonical shape
30480        // the `#[serde(rename_all = "camelCase")]` derive produces on
30481        // [`Membro`]. A future flip to a non-camelCase attribute at
30482        // the derive surfaces both here (this test fails on the
30483        // stale-constant shape) and at
30484        // `membro_serde_keys_match_lifted_membro_key_consts` (that test
30485        // fails on the mismatch between const and derive). Peer with
30486        // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
30487        // on the sibling `SupervisorSpec` top-level axis.
30488        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
30489            assert!(
30490                !key.is_empty(),
30491                "MEMBRO_KEY_* must be non-empty (got {key:?})"
30492            );
30493            let first = key.chars().next().unwrap();
30494            assert!(
30495                first.is_ascii_lowercase(),
30496                "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
30497                 (got {key:?}, leads with {first:?})",
30498            );
30499            assert!(
30500                key.chars().all(|c| c.is_ascii_alphanumeric()),
30501                "MEMBRO_KEY_* must be ASCII-alphanumeric only \
30502                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
30503            );
30504        }
30505    }
30506
30507    // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
30508
30509    #[test]
30510    fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
30511        // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
30512        // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
30513        // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
30514        // keys the `#[serde(rename_all = "camelCase")]` attribute on
30515        // [`WitContract`] emits for the required-triad. The three
30516        // sibling payload-arm keys already pin under
30517        // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
30518        // `STORE_FIELD_NAME` — pin all six alongside so a future
30519        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
30520        // verbatim-field-name flip at the derive attribute (any of which
30521        // would silently break every downstream JSON consumer that
30522        // reaches for one of the six via `Value::get(...)`) surfaces
30523        // here as a build-time test failure at `aplicacao.rs`, not as an
30524        // apply-time `.get(<stale-canonical-const>)` returning `None`
30525        // far from the derive-attr drift's commit. Peer with the sibling
30526        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
30527        // pin on the M3 `:membros` per-entry axis — same discipline the
30528        // `Membro` per-entry lift established, extended here to the
30529        // sibling M3 `WitContract` per-`:contratos` entry axis, the last
30530        // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
30531        // axis on the Aplicacao surface without a lifted serde-key peer.
30532        let c = WitContract {
30533            de: "cart".into(),
30534            para: "catalog".into(),
30535            wit: "wasi:http/proxy".into(),
30536            endpoint: Some("/lookup".into()),
30537            subject: None,
30538            slot: None,
30539        };
30540        let json = serde_json::to_string(&c).unwrap();
30541        for key in [
30542            crate::CONTRATO_KEY_DE,
30543            crate::CONTRATO_KEY_PARA,
30544            crate::CONTRATO_KEY_WIT,
30545            WitTarget::HTTP_FIELD_NAME,
30546        ] {
30547            let quoted = format!("\"{key}\"");
30548            assert!(
30549                json.contains(&quoted),
30550                "serialized WitContract must carry the lifted \
30551                 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
30552                 {quoted} verbatim in the JSON emission (got: {json})",
30553            );
30554        }
30555
30556        // Pin the two remaining payload-arm keys by round-tripping a
30557        // `WitContract` under each payload-shape (pub-sub, store) — the
30558        // required-triad appears on every emission but the payload arms
30559        // only surface when their `Option<String>` field is `Some`.
30560        let pubsub = WitContract {
30561            de: "cart".into(),
30562            para: "events".into(),
30563            wit: "nats:pub-sub".into(),
30564            endpoint: None,
30565            subject: Some("orders.placed".into()),
30566            slot: None,
30567        };
30568        let pubsub_json = serde_json::to_string(&pubsub).unwrap();
30569        let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
30570        assert!(
30571            pubsub_json.contains(&pubsub_quoted),
30572            "serialized pub-sub WitContract must carry the lifted \
30573             WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
30574             verbatim in the JSON emission (got: {pubsub_json})",
30575        );
30576        let store = WitContract {
30577            de: "cart".into(),
30578            para: "sessions".into(),
30579            wit: "wasi:keyvalue/store".into(),
30580            endpoint: None,
30581            subject: None,
30582            slot: Some("cart/$id".into()),
30583        };
30584        let store_json = serde_json::to_string(&store).unwrap();
30585        let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
30586        assert!(
30587            store_json.contains(&store_quoted),
30588            "serialized store WitContract must carry the lifted \
30589             WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
30590             verbatim in the JSON emission (got: {store_json})",
30591        );
30592    }
30593
30594    #[test]
30595    fn contrato_key_consts_are_pairwise_distinct() {
30596        // Cross-axis drift-detection pin: a future collapse of the six
30597        // canonical [`WitContract`] per-entry byte-strings onto the same
30598        // value (e.g. an accidental copy-paste flip of
30599        // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
30600        // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
30601        // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
30602        // every downstream probe on one axis onto the sibling axis's
30603        // overlay entry and pass every propagation-probe test that
30604        // expected only the stale axis's value. Peer of the sibling
30605        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
30606        // widened here to the six-way axis the `WitContract`
30607        // required-triad + `WitTarget` payload-triad jointly cover.
30608        let all = [
30609            crate::CONTRATO_KEY_DE,
30610            crate::CONTRATO_KEY_PARA,
30611            crate::CONTRATO_KEY_WIT,
30612            WitTarget::HTTP_FIELD_NAME,
30613            WitTarget::PUBSUB_FIELD_NAME,
30614            WitTarget::STORE_FIELD_NAME,
30615        ];
30616        for (i, a) in all.iter().enumerate() {
30617            for b in all.iter().skip(i + 1) {
30618                assert_ne!(
30619                    a, b,
30620                    "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
30621                     must be pairwise-distinct canonical byte-sequences \
30622                     — got `{a}` == `{b}`",
30623                );
30624            }
30625        }
30626    }
30627
30628    #[test]
30629    fn contrato_key_consts_are_lower_camel_case_shape() {
30630        // Shape-pin: every `CONTRATO_KEY_*` (and every peer
30631        // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
30632        // byte-sequence (no `snake_case` underscores, no `kebab-case`
30633        // hyphens, no leading colon, no `PascalCase` leading capital, no
30634        // whitespace / dots) — the canonical shape the
30635        // `#[serde(rename_all = "camelCase")]` derive produces on
30636        // [`WitContract`]. A future flip to a non-camelCase attribute at
30637        // the derive surfaces both here (this test fails on the
30638        // stale-constant shape) and at
30639        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
30640        // (that test fails on the mismatch between const and derive).
30641        // Peer with `membro_key_consts_are_lower_camel_case_shape`
30642        // (ce80ca0) on the sibling `Membro` per-entry axis.
30643        for key in [
30644            crate::CONTRATO_KEY_DE,
30645            crate::CONTRATO_KEY_PARA,
30646            crate::CONTRATO_KEY_WIT,
30647            WitTarget::HTTP_FIELD_NAME,
30648            WitTarget::PUBSUB_FIELD_NAME,
30649            WitTarget::STORE_FIELD_NAME,
30650        ] {
30651            assert!(
30652                !key.is_empty(),
30653                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
30654                 non-empty (got {key:?})"
30655            );
30656            let first = key.chars().next().unwrap();
30657            assert!(
30658                first.is_ascii_lowercase(),
30659                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
30660                 with an ASCII-lowercase byte (got {key:?}, leads with \
30661                 {first:?})",
30662            );
30663            assert!(
30664                key.chars().all(|c| c.is_ascii_alphanumeric()),
30665                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
30666                 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
30667                 whitespace (got {key:?})",
30668            );
30669        }
30670    }
30671
30672    // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
30673
30674    #[test]
30675    fn entrada_serde_keys_match_lifted_entrada_key_consts() {
30676        // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
30677        // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
30678        // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
30679        // name the exact camelCase JSON keys the
30680        // `#[serde(rename_all = "camelCase")]` attribute on
30681        // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
30682        // pin that each canonical byte-sequence appears verbatim in the
30683        // JSON — a future accidental `rename_all = "snake_case"` /
30684        // `"kebab-case"` / verbatim-field-name flip at the derive
30685        // attribute (any of which would silently break every downstream
30686        // JSON consumer that reaches for one of the four consts via
30687        // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
30688        // emitter's per-Aplicacao hostname/paths/port projection, the
30689        // future `app-operator` reconciler's per-Aplicacao ingress
30690        // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
30691        // materializer's admission-time cross-check) surfaces here as
30692        // a build-time test failure at `aplicacao.rs`, not as an
30693        // apply-time `.get(<stale-canonical-const>)` returning `None`
30694        // far from the derive-attr drift's commit. Peer with the
30695        // sibling
30696        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
30697        // (ca463a4) and
30698        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
30699        // pins on the M3 collection-slot atom axes — same discipline
30700        // both collection-slot lifts established, extended here to the
30701        // singleton `:entrada` mesh-slot atom axis, the last M3
30702        // typed-struct top-level `#[serde(rename_all = "camelCase")]`
30703        // axis on the Aplicacao surface without a lifted serde-key
30704        // peer.
30705        let e = Entrada {
30706            host: "checkout.quero.cloud".into(),
30707            para: "cart".into(),
30708            paths: vec!["/cart".into()],
30709            port: 8080,
30710        };
30711        let json = serde_json::to_string(&e).unwrap();
30712        for key in [
30713            crate::ENTRADA_KEY_HOST,
30714            crate::ENTRADA_KEY_PARA,
30715            crate::ENTRADA_KEY_PATHS,
30716            crate::ENTRADA_KEY_PORT,
30717        ] {
30718            let quoted = format!("\"{key}\"");
30719            assert!(
30720                json.contains(&quoted),
30721                "serialized Entrada must carry the lifted ENTRADA_KEY_* \
30722                 byte-sequence {quoted} verbatim in the JSON emission \
30723                 (got: {json})",
30724            );
30725        }
30726    }
30727
30728    #[test]
30729    fn entrada_key_consts_are_pairwise_distinct() {
30730        // Cross-axis drift-detection pin: a future collapse of the four
30731        // canonical [`Entrada`] singleton byte-strings onto the same
30732        // value (e.g. an accidental copy-paste flip of
30733        // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
30734        // silently reroute every downstream probe on one axis onto the
30735        // sibling axis's overlay entry and pass every propagation-probe
30736        // test that expected only the stale axis's value — the
30737        // Gateway/HTTPRoute emitter would read the hostname string
30738        // where the destination-Servico name was expected (or vice
30739        // versa), the admission-webhook cross-check would compare the
30740        // wrong pair of values, and the resulting Gateway resource
30741        // would either be admitted with garbage or rejected at the
30742        // controller far from the rebrand commit's source. Peer of the
30743        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
30744        // tetrad (40cc4e5), the two-way distinct pin on the
30745        // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
30746        // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
30747        // triad (ca463a4).
30748        let all = [
30749            crate::ENTRADA_KEY_HOST,
30750            crate::ENTRADA_KEY_PARA,
30751            crate::ENTRADA_KEY_PATHS,
30752            crate::ENTRADA_KEY_PORT,
30753        ];
30754        for (i, a) in all.iter().enumerate() {
30755            for b in all.iter().skip(i + 1) {
30756                assert_ne!(
30757                    a, b,
30758                    "ENTRADA_KEY_* consts must be pairwise-distinct \
30759                     canonical byte-sequences — got `{a}` == `{b}`",
30760                );
30761            }
30762        }
30763    }
30764
30765    #[test]
30766    fn entrada_key_consts_are_lower_camel_case_shape() {
30767        // Shape-pin: every `ENTRADA_KEY_*` const must be a
30768        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
30769        // `kebab-case` hyphens, no leading colon, no `PascalCase`
30770        // leading capital, no whitespace / dots) — the canonical shape
30771        // the `#[serde(rename_all = "camelCase")]` derive produces on
30772        // [`Entrada`]. A future flip to a non-camelCase attribute at
30773        // the derive surfaces both here (this test fails on the
30774        // stale-constant shape) and at
30775        // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
30776        // test fails on the mismatch between const and derive). Peer
30777        // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
30778        // and `contrato_key_consts_are_lower_camel_case_shape`
30779        // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
30780        // entry axes.
30781        for key in [
30782            crate::ENTRADA_KEY_HOST,
30783            crate::ENTRADA_KEY_PARA,
30784            crate::ENTRADA_KEY_PATHS,
30785            crate::ENTRADA_KEY_PORT,
30786        ] {
30787            assert!(
30788                !key.is_empty(),
30789                "ENTRADA_KEY_* must be non-empty (got {key:?})"
30790            );
30791            let first = key.chars().next().unwrap();
30792            assert!(
30793                first.is_ascii_lowercase(),
30794                "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
30795                 (got {key:?}, leads with {first:?})",
30796            );
30797            assert!(
30798                key.chars().all(|c| c.is_ascii_alphanumeric()),
30799                "ENTRADA_KEY_* must be ASCII-alphanumeric only \
30800                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
30801            );
30802        }
30803    }
30804
30805    // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
30806
30807    #[test]
30808    fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
30809        // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
30810        // ([`crate::POLITICAS_KEY_TIMEOUT`] /
30811        // [`crate::POLITICAS_KEY_RETRIES`] /
30812        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
30813        // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
30814        // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
30815        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
30816        // on [`MeshPolicy`] emits. Three of the five axes
30817        // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
30818        // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
30819        // camelCase transforms — the derive-attribute is load-bearing
30820        // on those, unlike the sibling `Entrada` / `Membro` /
30821        // `WitContract` structs whose fields are all lowercase-single-
30822        // word and where the derive is a no-op on every axis.
30823        // Serialize a fully-populated [`MeshPolicy`] (every axis
30824        // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
30825        // on none of the five slots) and pin that each canonical
30826        // byte-sequence appears verbatim in the JSON — a future
30827        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
30828        // verbatim-field-name flip at the derive attribute (any of
30829        // which would silently break every downstream JSON consumer
30830        // that reaches for one of the five consts via
30831        // `Value::get(...)` — the future M4 per-edge `:politicas`
30832        // overlay projection onto Cilium `L7Rules` and Gateway API
30833        // `HTTPRoute` backend timeouts, the future
30834        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
30835        // admission-time mesh-policy cross-check, the future
30836        // `feira lint` per-`:politicas` bound-check gate) surfaces here
30837        // as a build-time test failure at `aplicacao.rs`, not as an
30838        // apply-time `.get(<stale-canonical-const>)` returning `None`
30839        // far from the derive-attr drift's commit. Peer with the
30840        // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
30841        // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
30842        // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
30843        // (ce80ca0) pins on the M3 collection-slot / singleton-slot
30844        // atom axes — same discipline every M3 sibling lift
30845        // established, extended here to the singleton `:politicas`
30846        // mesh-slot atom axis, closing the last M3 typed-struct
30847        // top-level `#[serde(rename_all = "camelCase")]` axis on the
30848        // Aplicacao surface without a lifted serde-key peer.
30849        let p = MeshPolicy {
30850            timeout: Some(Duration::from_secs(30)),
30851            retries: Some(3),
30852            circuit_breaker: Some(CircuitBreaker {
30853                max_failures: 5,
30854                window: Duration::from_secs(60),
30855            }),
30856            mtls_required: Some(true),
30857            rate_limit: Some(RateLimit {
30858                rate: 100,
30859                window: Duration::from_secs(1),
30860            }),
30861        };
30862        let json = serde_json::to_string(&p).unwrap();
30863        for key in [
30864            crate::POLITICAS_KEY_TIMEOUT,
30865            crate::POLITICAS_KEY_RETRIES,
30866            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
30867            crate::POLITICAS_KEY_MTLS_REQUIRED,
30868            crate::POLITICAS_KEY_RATE_LIMIT,
30869        ] {
30870            let quoted = format!("\"{key}\"");
30871            assert!(
30872                json.contains(&quoted),
30873                "serialized MeshPolicy must carry the lifted \
30874                 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
30875                 JSON emission (got: {json})",
30876            );
30877        }
30878    }
30879
30880    #[test]
30881    fn politicas_key_consts_are_pairwise_distinct() {
30882        // Cross-axis drift-detection pin: a future collapse of the five
30883        // canonical [`MeshPolicy`] singleton byte-strings onto the same
30884        // value (e.g. an accidental copy-paste flip of
30885        // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
30886        // would silently reroute every downstream probe on one axis
30887        // onto the sibling axis's overlay entry and pass every
30888        // propagation-probe test that expected only the stale axis's
30889        // value — the M4 per-edge `:politicas` overlay projection would
30890        // read the retry-count string where the timeout duration was
30891        // expected (or vice versa), the CR materializer's admission
30892        // cross-check would compare the wrong pair of values, and the
30893        // resulting mesh reconciler would either bind the wrong axis
30894        // or reject the resource at reconcile far from the rebrand
30895        // commit's source. Peer of the sibling four-way distinct pin
30896        // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
30897        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
30898        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
30899        // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
30900        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
30901        let all = [
30902            crate::POLITICAS_KEY_TIMEOUT,
30903            crate::POLITICAS_KEY_RETRIES,
30904            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
30905            crate::POLITICAS_KEY_MTLS_REQUIRED,
30906            crate::POLITICAS_KEY_RATE_LIMIT,
30907        ];
30908        for (i, a) in all.iter().enumerate() {
30909            for b in all.iter().skip(i + 1) {
30910                assert_ne!(
30911                    a, b,
30912                    "POLITICAS_KEY_* consts must be pairwise-distinct \
30913                     canonical byte-sequences — got `{a}` == `{b}`",
30914                );
30915            }
30916        }
30917    }
30918
30919    #[test]
30920    fn politicas_key_consts_are_lower_camel_case_shape() {
30921        // Shape-pin: every `POLITICAS_KEY_*` const must be a
30922        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
30923        // `kebab-case` hyphens, no leading colon, no `PascalCase`
30924        // leading capital, no whitespace / dots) — the canonical shape
30925        // the `#[serde(rename_all = "camelCase")]` derive produces on
30926        // [`MeshPolicy`]. A future flip to a non-camelCase attribute
30927        // at the derive surfaces both here (this test fails on the
30928        // stale-constant shape) and at
30929        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
30930        // (that test fails on the mismatch between const and derive).
30931        // Peer with `entrada_key_consts_are_lower_camel_case_shape`
30932        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
30933        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
30934        // (ca463a4) on the sibling M3 typed-struct axes.
30935        for key in [
30936            crate::POLITICAS_KEY_TIMEOUT,
30937            crate::POLITICAS_KEY_RETRIES,
30938            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
30939            crate::POLITICAS_KEY_MTLS_REQUIRED,
30940            crate::POLITICAS_KEY_RATE_LIMIT,
30941        ] {
30942            assert!(
30943                !key.is_empty(),
30944                "POLITICAS_KEY_* must be non-empty (got {key:?})"
30945            );
30946            let first = key.chars().next().unwrap();
30947            assert!(
30948                first.is_ascii_lowercase(),
30949                "POLITICAS_KEY_* must lead with an ASCII-lowercase \
30950                 byte (got {key:?}, leads with {first:?})",
30951            );
30952            assert!(
30953                key.chars().all(|c| c.is_ascii_alphanumeric()),
30954                "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
30955                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
30956            );
30957        }
30958    }
30959
30960    // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
30961
30962    #[test]
30963    fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
30964        // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
30965        // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
30966        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
30967        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
30968        // [`CircuitBreaker`] emits inside the
30969        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
30970        // two axes (`max_failures` → `maxFailures`) is a non-trivial
30971        // camelCase transform — the derive-attribute is load-bearing on
30972        // that axis, unlike the sibling `window` field where the derive
30973        // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
30974        // pin that each canonical byte-sequence appears verbatim in the
30975        // JSON — a future accidental `rename_all = "snake_case"` /
30976        // `"kebab-case"` / verbatim-field-name flip at the derive
30977        // attribute (any of which would silently break every downstream
30978        // JSON consumer that reaches for one of the two consts via
30979        // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
30980        // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
30981        // per-edge `:politicas` overlay projection onto the mesh's
30982        // per-backend consecutive-failure-counter tripping threshold, the
30983        // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
30984        // admission-time breaker cross-check, the future `feira lint`
30985        // per-`:politicas :circuit-breaker` bound-check gate) surfaces
30986        // here as a build-time test failure at `aplicacao.rs`, not as an
30987        // apply-time `.get(<stale-canonical-const>)` returning `None`
30988        // far from the derive-attr drift's commit. Peer with the sibling
30989        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
30990        // (b55cca7) parent-axis pin — that test pins the outer
30991        // sub-block key the derive on [`MeshPolicy`] emits, this test
30992        // pins the inner keys the derive on the payload type emits, so
30993        // the two together lock the whole [`MeshPolicy`] breaker-tuning
30994        // shape end-to-end at build time.
30995        let cb = CircuitBreaker {
30996            max_failures: 5,
30997            window: Duration::from_secs(60),
30998        };
30999        let json = serde_json::to_string(&cb).unwrap();
31000        for key in [
31001            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
31002            crate::CIRCUIT_BREAKER_KEY_WINDOW,
31003        ] {
31004            let quoted = format!("\"{key}\"");
31005            assert!(
31006                json.contains(&quoted),
31007                "serialized CircuitBreaker must carry the lifted \
31008                 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
31009                 in the JSON emission (got: {json})",
31010            );
31011        }
31012    }
31013
31014    #[test]
31015    fn circuit_breaker_key_consts_are_pairwise_distinct() {
31016        // Cross-axis drift-detection pin: a future collapse of the two
31017        // canonical [`CircuitBreaker`] sub-block byte-strings onto the
31018        // same value (e.g. an accidental copy-paste flip of
31019        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
31020        // `"maxFailures"`) would silently reroute every downstream
31021        // probe on one axis onto the sibling axis's overlay entry and
31022        // pass every propagation-probe test that expected only the
31023        // stale axis's value — the M4 per-edge `:politicas` overlay
31024        // projection would read the failure-count where the window
31025        // duration was expected (or vice versa), the CR materializer's
31026        // admission cross-check would compare the wrong pair of values,
31027        // and the resulting mesh reconciler would either bind the wrong
31028        // axis or reject the resource at reconcile far from the rebrand
31029        // commit's source. Peer of the sibling five-way distinct pin on
31030        // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
31031        // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
31032        // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
31033        // six-way distinct pin on the `CONTRATO_KEY_*` triad +
31034        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
31035        let all = [
31036            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
31037            crate::CIRCUIT_BREAKER_KEY_WINDOW,
31038        ];
31039        for (i, a) in all.iter().enumerate() {
31040            for b in all.iter().skip(i + 1) {
31041                assert_ne!(
31042                    a, b,
31043                    "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
31044                     canonical byte-sequences — got `{a}` == `{b}`",
31045                );
31046            }
31047        }
31048    }
31049
31050    #[test]
31051    fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
31052        // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
31053        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
31054        // `kebab-case` hyphens, no leading colon, no `PascalCase`
31055        // leading capital, no whitespace / dots) — the canonical shape
31056        // the `#[serde(rename_all = "camelCase")]` derive produces on
31057        // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
31058        // at the derive surfaces both here (this test fails on the
31059        // stale-constant shape) and at
31060        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
31061        // (that test fails on the mismatch between const and derive).
31062        // Peer with `politicas_key_consts_are_lower_camel_case_shape`
31063        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
31064        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
31065        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
31066        // (ca463a4) on the sibling M3 typed-struct axes.
31067        for key in [
31068            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
31069            crate::CIRCUIT_BREAKER_KEY_WINDOW,
31070        ] {
31071            assert!(
31072                !key.is_empty(),
31073                "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
31074            );
31075            let first = key.chars().next().unwrap();
31076            assert!(
31077                first.is_ascii_lowercase(),
31078                "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
31079                 byte (got {key:?}, leads with {first:?})",
31080            );
31081            assert!(
31082                key.chars().all(|c| c.is_ascii_alphanumeric()),
31083                "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
31084                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
31085            );
31086        }
31087    }
31088
31089    // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
31090
31091    #[test]
31092    fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
31093        // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
31094        // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
31095        // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
31096        // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
31097        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
31098        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
31099        // [`Placement`] emits. One of the four axes (`shard_key` →
31100        // `shardKey`) is a non-trivial camelCase transform — the
31101        // derive-attribute is load-bearing on that axis, unlike the
31102        // sibling `estrategia` / `clusters` / `affinity` axes whose
31103        // source-side field names carry no `_` and where the derive is a
31104        // no-op. Serialize a fully-populated [`Placement`] (both
31105        // `Option`-carrying axes `Some(_)` so
31106        // `skip_serializing_if = "Option::is_none"` fires on neither of
31107        // the two optional slots) and pin that each canonical
31108        // byte-sequence appears verbatim in the JSON — a future
31109        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
31110        // verbatim-field-name flip at the derive attribute (any of which
31111        // would silently break every downstream consumer that reaches
31112        // for one of the four consts via
31113        // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
31114        // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
31115        // aggregator's per-cluster fanout filter keying off
31116        // `placement.clusters`, the M3 shard-pool dispatch materializer
31117        // keying off `placement.shardKey`, the M3 Adaptive compression
31118        // pass weighting off `placement.affinity`, every downstream
31119        // dispatcher branching on `placement.estrategia`, the future
31120        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
31121        // admission-time placement cross-check, the future `feira lint`
31122        // per-`:placement` bound-check gate) surfaces here as a
31123        // build-time test failure at `aplicacao.rs`, not as an
31124        // apply-time `.get(<stale-canonical-const>)` returning `None`
31125        // far from the derive-attr drift's commit. Peer with the sibling
31126        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
31127        // (b55cca7),
31128        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
31129        // (468e959),
31130        // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
31131        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
31132        // (ca463a4), and
31133        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
31134        // pins on the M3 collection-slot / singleton-slot atom axes —
31135        // closes the last M3 typed-struct top-level
31136        // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
31137        // surface without a drift-detection pin.
31138        let p = Placement {
31139            estrategia: PlacementStrategy::Sharded,
31140            clusters: vec!["rio".into(), "mar".into()],
31141            affinity: Some("data-locality".into()),
31142            shard_key: Some("$tenantId".into()),
31143        };
31144        let json = serde_json::to_string(&p).unwrap();
31145        for key in [
31146            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
31147            crate::M3_PLACEMENT_KEY_CLUSTERS,
31148            crate::M3_PLACEMENT_KEY_AFFINITY,
31149            crate::M3_PLACEMENT_KEY_SHARD_KEY,
31150        ] {
31151            let quoted = format!("\"{key}\"");
31152            assert!(
31153                json.contains(&quoted),
31154                "serialized Placement must carry the lifted \
31155                 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
31156                 the JSON emission (got: {json})",
31157            );
31158        }
31159    }
31160
31161    #[test]
31162    fn m3_placement_key_consts_are_pairwise_distinct() {
31163        // Cross-axis drift-detection pin: a future collapse of the four
31164        // canonical [`Placement`] sub-block byte-strings onto the same
31165        // value (e.g. an accidental copy-paste flip of
31166        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
31167        // `"affinity"`) would silently reroute every downstream probe on
31168        // one axis onto the sibling axis's overlay entry and pass every
31169        // propagation-probe test that expected only the stale axis's
31170        // value — the M3 shard-pool dispatch materializer would read the
31171        // affinity placement-hint where the shard-selection template was
31172        // expected (or vice versa), the M3 Adaptive compression pass's
31173        // cross-check would compare the wrong pair of values, and the
31174        // resulting placement engine would either bind the wrong axis or
31175        // reject the resource at reconcile far from the rebrand commit's
31176        // source. Peer of the sibling two-way distinct pin on the
31177        // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
31178        // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
31179        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
31180        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
31181        // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
31182        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
31183        let all = [
31184            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
31185            crate::M3_PLACEMENT_KEY_CLUSTERS,
31186            crate::M3_PLACEMENT_KEY_AFFINITY,
31187            crate::M3_PLACEMENT_KEY_SHARD_KEY,
31188        ];
31189        for (i, a) in all.iter().enumerate() {
31190            for b in all.iter().skip(i + 1) {
31191                assert_ne!(
31192                    a, b,
31193                    "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
31194                     canonical byte-sequences — got `{a}` == `{b}`",
31195                );
31196            }
31197        }
31198    }
31199
31200    #[test]
31201    fn m3_placement_key_consts_are_lower_camel_case_shape() {
31202        // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
31203        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
31204        // `kebab-case` hyphens, no leading colon, no `PascalCase`
31205        // leading capital, no whitespace / dots) — the canonical shape
31206        // the `#[serde(rename_all = "camelCase")]` derive produces on
31207        // [`Placement`]. A future flip to a non-camelCase attribute at
31208        // the derive surfaces both here (this test fails on the stale-
31209        // constant shape) and at
31210        // `placement_serde_keys_match_lifted_m3_placement_key_consts`
31211        // (that test fails on the mismatch between const and derive).
31212        // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
31213        // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
31214        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
31215        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
31216        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
31217        // (ca463a4) on the sibling M3 typed-struct axes.
31218        for key in [
31219            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
31220            crate::M3_PLACEMENT_KEY_CLUSTERS,
31221            crate::M3_PLACEMENT_KEY_AFFINITY,
31222            crate::M3_PLACEMENT_KEY_SHARD_KEY,
31223        ] {
31224            assert!(
31225                !key.is_empty(),
31226                "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
31227            );
31228            let first = key.chars().next().unwrap();
31229            assert!(
31230                first.is_ascii_lowercase(),
31231                "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
31232                 byte (got {key:?}, leads with {first:?})",
31233            );
31234            assert!(
31235                key.chars().all(|c| c.is_ascii_alphanumeric()),
31236                "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
31237                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
31238            );
31239        }
31240    }
31241
31242    // ── AplicacaoSpec::port_for_destination — the substrate-canonical
31243    //    destination-facing L4 port resolver every per-Aplicacao renderer
31244    //    reaching for a per-destination Servico TCP port axis routes
31245    //    through. The four pin tests below fix the four-way accept-set
31246    //    the resolver must always honor: (:entrada-para-matches,
31247    //    :entrada-para-mismatches, :entrada-none-so-fallback,
31248    //    :entrada-port-non-default-honored) — drift on any arm surfaces
31249    //    at caixa-core build time rather than at cluster-apply time.
31250
31251    #[test]
31252    fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
31253        // The typed `:entrada` block's `:para "cart"` matches the
31254        // queried destination, so the resolver returns the author-
31255        // declared `:port` scalar verbatim — the canonical "the
31256        // destination Servico IS the ingress apex, honor the typed
31257        // listener port" arm of the port-resolution dispatch.
31258        let mut spec = three_member_spec();
31259        if let Some(e) = spec.entrada.as_mut() {
31260            e.para = "cart".into();
31261            e.port = 9090;
31262        }
31263        assert_eq!(
31264            spec.port_for_destination("cart"),
31265            9090,
31266            "port_for_destination(entrada.para) must return entrada.port \
31267             verbatim, not the DEFAULT_SERVICO_PORT fallback"
31268        );
31269    }
31270
31271    #[test]
31272    fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
31273        // The typed `:entrada` block names `:para "cart"`, but the
31274        // queried destination is `"payment"` — a Servico that
31275        // participates in the mesh graph but is not the ingress apex.
31276        // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
31277        // canonical port floor, closing the "non-apex destination reads
31278        // the substrate default" arm. Same fixture the peer
31279        // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
31280        // pin at caixa-mesh exercises through the CNP emit-side path;
31281        // this pin exercises the shared underlying resolver directly.
31282        let spec = three_member_spec();
31283        assert_eq!(
31284            spec.port_for_destination("payment"),
31285            DEFAULT_SERVICO_PORT,
31286            "port_for_destination(non-apex-destination) must route \
31287             through the lifted DEFAULT_SERVICO_PORT canonical port floor"
31288        );
31289    }
31290
31291    #[test]
31292    fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
31293        // Internal-only Aplicacao — no `:entrada` block declared. Every
31294        // per-destination port query falls back to the lifted
31295        // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
31296        // the Aplicacao surface admits `:entrada None` (internal mesh
31297        // with no external gateway); every downstream renderer's per-
31298        // destination port axis must still resolve to a well-defined
31299        // scalar even without an ingress apex.
31300        let mut spec = three_member_spec();
31301        spec.entrada = None;
31302        assert_eq!(
31303            spec.port_for_destination("cart"),
31304            DEFAULT_SERVICO_PORT,
31305            "port_for_destination on an internal-only Aplicacao must \
31306             fall back to the lifted DEFAULT_SERVICO_PORT floor for \
31307             every destination"
31308        );
31309        assert_eq!(
31310            spec.port_for_destination("payment"),
31311            DEFAULT_SERVICO_PORT,
31312            "port_for_destination on an internal-only Aplicacao must \
31313             fall back uniformly across every destination — the fallback \
31314             is not entrada-shape-conditional"
31315        );
31316    }
31317
31318    #[test]
31319    fn port_for_destination_honors_non_default_entrada_port_verbatim() {
31320        // Structural pin against a hypothetical future refactor that
31321        // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
31322        // the resolver (a "normalize to the default when the author's
31323        // port matches the substrate default" collapse) — that would
31324        // break renderer sites that carry meaning on the emitted port
31325        // value beyond bare equality (a future per-cluster listener-
31326        // audit that keys off the author-declared port, not the
31327        // resolved-with-fallback port). Pin that a non-default
31328        // entrada.port is returned verbatim so drift here surfaces at
31329        // caixa-core build time.
31330        let mut spec = three_member_spec();
31331        if let Some(e) = spec.entrada.as_mut() {
31332            e.para = "cart".into();
31333            e.port = 8443;
31334        }
31335        assert_ne!(
31336            8443, DEFAULT_SERVICO_PORT,
31337            "test fixture must probe a port distinct from \
31338             DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
31339        );
31340        assert_eq!(
31341            spec.port_for_destination("cart"),
31342            8443,
31343            "port_for_destination(entrada.para) must return entrada.port \
31344             verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
31345        );
31346    }
31347
31348    #[test]
31349    fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
31350        // Apex-identity pair-invariant pin composing both substrate-
31351        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
31352        // and [`Entrada::destination`] — at the emit-side call shape
31353        // every per-Aplicacao renderer's ingress-apex L4 port reader
31354        // now takes. The invariant:
31355        //
31356        //   spec.port_for_destination(entrada.destination()) == entrada.port
31357        //
31358        // holds by construction under today's single-destination
31359        // `:entrada` slot (`destination()` returns `entrada.para`, and
31360        // the resolver's apex arm matches `para == destination` and
31361        // returns `entrada.port`), and every downstream consumer that
31362        // composes the two accessors at the ingress apex — the
31363        // `caixa_mesh::gateway_routes` HTTPRoute per-rule
31364        // `backendRefs[0].port` emit-site path, the peer future M4 CR
31365        // materializer's admission-webhook that promotes the scalar to
31366        // a per-CR override overlay, every future per-Aplicacao snapshot
31367        // renderer's apex-facing L4 port reader — reaches through the
31368        // same composition. Pin the identity across four permutations
31369        // (`:para` × `:port` including a non-default port to exercise
31370        // the honor-verbatim arm and a non-cart `:para` to exercise
31371        // destination-agnostic identity) so a future refactor that
31372        // silently split either accessor's apex behavior surfaces at
31373        // caixa-core build time — a subtle `destination()` renaming
31374        // that returned `entrada.host.as_str()` instead of
31375        // `entrada.para.as_str()` would blow this pin loudly, closing
31376        // the last quiet failure mode the two lifts admit in composition.
31377        //
31378        // Peer discipline with the sibling caixa-mesh cross-crate pin
31379        // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
31380        // on the two-renderer pair-invariant axis; this pin encodes the
31381        // same two-consumer coherence rule at the substrate-primitive
31382        // level so the invariant survives even if every renderer is
31383        // deleted.
31384        for (para, port) in [
31385            ("cart", DEFAULT_SERVICO_PORT),
31386            ("cart", 8443u16),
31387            ("payment", 9090u16),
31388            ("catalog", 443u16),
31389        ] {
31390            let mut spec = three_member_spec();
31391            if let Some(e) = spec.entrada.as_mut() {
31392                e.para = para.into();
31393                e.port = port;
31394            }
31395            let expected_port = spec
31396                .entrada()
31397                .expect("three_member_spec carries a typed `:entrada` block")
31398                .port();
31399            let composed_port = {
31400                let entrada = spec.entrada().expect("entrada present");
31401                spec.port_for_destination(entrada.destination())
31402            };
31403            assert_eq!(
31404                composed_port, expected_port,
31405                "`spec.port_for_destination(entrada.destination())` must \
31406                 equal `entrada.port` under today's single-destination \
31407                 `:entrada` slot — this is the apex-identity contract \
31408                 every downstream ingress-apex L4 port reader relies on. \
31409                 Input :entrada :para: {para:?}, :entrada :port: {port}"
31410            );
31411        }
31412    }
31413
31414    #[test]
31415    fn port_for_destination_apex_arm_routes_through_destination_accessor() {
31416        // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
31417        // per-`:entrada` apex-arm membership probe must key off
31418        // [`Entrada::destination`], not the raw `.para` field access.
31419        // Structurally: setting ONLY the `:entrada :para` field to a
31420        // fresh non-cart destination on an otherwise-well-formed
31421        // Aplicacao must (1) leave `e.destination()` byte-equal to
31422        // `e.para.as_str()` (the accessor is byte-projective by
31423        // definition), and (2) cause the resolver's apex arm to fire
31424        // and return `entrada.port` at exactly that new destination
31425        // while every other destination string falls through to
31426        // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
31427        // membership check. Pins against a future silent detour that
31428        // (a) re-derived the apex-arm membership probe off
31429        // `e.para == destination` in `port_for_destination` instead of
31430        // `e.destination() == destination`, silently disagreeing with
31431        // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
31432        // consumers (`entrada.destination()` at
31433        // caixa-mesh/src/lib.rs:3173, `c.destination()` at
31434        // caixa-mesh/src/lib.rs:2739) that already reach through the
31435        // accessor, (b) accessor-side introduced a per-tenant alias
31436        // arm the caller was unaware of, silently rewriting an
31437        // author-declared `:para "cart"` value to a canary-aliased
31438        // form — the raw-field-access resolver would fall through to
31439        // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
31440        // while the peer emit-site consumers landed on the aliased
31441        // destination, splitting the ingress-apex L4 port at
31442        // cluster-apply time.
31443        //
31444        // Peer of the sibling
31445        // [`validate_membros_empty_gate_routes_through_nome_accessor`]
31446        // (d0de220) composition pin on the per-`:membros` refusal-arm
31447        // axis — same "the shape-gate predicate must route through the
31448        // substrate-primitive typed dispatch" discipline extended onto
31449        // the per-`:entrada` apex-arm membership-probe axis. Closes
31450        // the last unlifted `.para` production-code read site on
31451        // `Entrada` in `caixa-core` — after this converge every
31452        // `caixa-core` `.para` field access outside the accessor's own
31453        // body and outside the `WitContract` per-`:contratos` sibling
31454        // axis is either a test-side field-setter or a doc-comment
31455        // reference.
31456        for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
31457            let mut spec = three_member_spec();
31458            if let Some(e) = spec.entrada.as_mut() {
31459                e.para = para.into();
31460                e.port = port;
31461            }
31462            let e = spec
31463                .entrada
31464                .as_ref()
31465                .expect("three_member_spec carries a typed `:entrada` block");
31466            assert_eq!(
31467                e.destination(),
31468                e.para.as_str(),
31469                "Entrada::destination must byte-equal the .para field \
31470                 access — an accessor-side detour that no longer \
31471                 projects the raw field would silently split this \
31472                 drift-detection test from the port_for_destination \
31473                 apex-arm membership probe",
31474            );
31475            assert_eq!(
31476                spec.port_for_destination(para),
31477                port,
31478                "port_for_destination must key off the accessor-projected \
31479                 destination and return `entrada.port` on the apex arm — \
31480                 input :entrada :para: {para:?}, :entrada :port: {port}",
31481            );
31482            assert_eq!(
31483                spec.port_for_destination("ghost-destination-never-a-member"),
31484                DEFAULT_SERVICO_PORT,
31485                "port_for_destination must fall through to \
31486                 DEFAULT_SERVICO_PORT on a non-matching destination \
31487                 under the accessor-projected membership check — input \
31488                 :entrada :para: {para:?}, :entrada :port: {port}",
31489            );
31490        }
31491    }
31492
31493    #[test]
31494    fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
31495        // The canonical per-`:politicas :rate-limit` `:rate`
31496        // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
31497        // [`RateLimit::rate`] must return the `:politicas :rate-limit`
31498        // typed `u32` verbatim, byte-equal to the raw field access
31499        // across every representative value in the accept-set — `1` (the
31500        // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
31501        // the surrounding [`AplicacaoSpec::validate_politicas`] gate
31502        // carves out on the sibling `PolicyRateLimitZero` refusal),
31503        // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
31504        // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
31505        // `0` (a past-the-guard sentinel that pins the accessor doesn't
31506        // perform a silent bounds-collapse into `1` on the zero arm —
31507        // validate rejects zero but the accessor must ship the raw slot
31508        // verbatim so a validate-time gate regression surfaces at the
31509        // emit boundary rather than being silently absorbed), `u32::MAX`
31510        // (a past-the-guard sentinel that pins the accessor doesn't
31511        // perform a silent bounds-collapse through
31512        // `POLICY_RATE_LIMIT_MAX` at the return path).
31513        //
31514        // First sub-struct required-scalar accessor pin on the
31515        // `RateLimit` axis — sibling in shape to the peer
31516        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
31517        // required-`u32` accessor pin on the peer per-sub-struct
31518        // required-axis. Pins against a future silent detour that
31519        // re-derived the token capacity from a peer axis (an accidental
31520        // `self.window.as_secs() as u32` collapse that read the
31521        // rate-limit window duration as a token count), a `0 → 1`
31522        // cluster-default projection (which would silently absorb the
31523        // `PolicyRateLimitZero` refusal case at the accessor boundary),
31524        // or a bounds-collapsing accessor that clamped the return
31525        // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
31526        // gate owns the bounds; the accessor must ship the raw slot
31527        // verbatim).
31528        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
31529            let rl = RateLimit {
31530                rate,
31531                window: Duration::from_secs(1),
31532            };
31533            assert_eq!(
31534                rl.rate(),
31535                rate,
31536                "RateLimit::rate must return :politicas :rate-limit :rate \
31537                 verbatim (got {}, expected {rate})",
31538                rl.rate(),
31539            );
31540            assert_eq!(
31541                rl.rate(),
31542                rl.rate,
31543                "RateLimit::rate must byte-equal the raw .rate field \
31544                 access across every value in the u32 accept-set",
31545            );
31546        }
31547    }
31548
31549    #[test]
31550    fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
31551        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
31552        // `:rate-limit :rate` zero-floor arm must key off
31553        // [`RateLimit::rate`], not the raw `.rate` field access.
31554        // Structurally: a `RateLimit { rate: 0, window:
31555        // Duration::from_secs(1) }` embedded in a `:politicas
31556        // :rate-limit` slot must surface the `PolicyRateLimitZero`
31557        // refusal exactly, and a `RateLimit { rate: 1, window:
31558        // Duration::from_secs(1) }` (the lower boundary of the
31559        // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
31560        // The pair jointly pins the accessor + validate-gate composition:
31561        // any future silent detour that had the accessor return a fresh
31562        // `1` on the zero arm (a `.rate().max(1)` collapse) would
31563        // silently absorb the `PolicyRateLimitZero` refusal at the
31564        // accessor boundary and the validate gate would accept a
31565        // struct-literal `RateLimit { rate: 0, .. }` — the composition
31566        // pin catches that at caixa-core build time.
31567        //
31568        // Peer of the sibling per-`CircuitBreaker`
31569        // [`CircuitBreaker::max_failures`] (3a74062) /
31570        // [`CircuitBreaker::window`] (373957f) accessor-composition
31571        // pins on the peer required-scalar axes — same "the validate /
31572        // shape-gate predicate must route through the substrate-primitive
31573        // typed dispatch" discipline extended onto the peer
31574        // per-`RateLimit` required-`u32` composition axis.
31575        let mut spec = three_member_spec();
31576        spec.politicas = MeshPolicy {
31577            rate_limit: Some(RateLimit {
31578                rate: 0,
31579                window: Duration::from_secs(1),
31580            }),
31581            ..MeshPolicy::default()
31582        };
31583        assert!(
31584            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
31585            "validate_politicas must reject rate == 0 with \
31586             PolicyRateLimitZero — the accessor and the validate gate \
31587             must route through the same substrate-primitive typed \
31588             dispatch on the :rate zero-floor arm",
31589        );
31590        spec.politicas = MeshPolicy {
31591            rate_limit: Some(RateLimit {
31592                rate: 1,
31593                window: Duration::from_secs(1),
31594            }),
31595            ..MeshPolicy::default()
31596        };
31597        assert!(
31598            spec.validate().is_ok(),
31599            "validate_politicas must accept rate == 1 (the lower \
31600             boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
31601        );
31602    }
31603
31604    #[test]
31605    fn rate_limit_rate_projects_u32_by_copy() {
31606        // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
31607        // `u32` is `Copy` and the accessor must return by value, not by
31608        // reference. Peer of the sibling per-`CircuitBreaker`
31609        // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
31610        // peer required-scalar `:max-failures` axis, extended onto the
31611        // peer per-`RateLimit` required-`u32` copy-invariant shape —
31612        // the accessor's returned `u32` must outlive `&self` (multiple
31613        // calls must return equal values from a dropped-`&self` copy,
31614        // since the returned scalar carries no borrow), and calling the
31615        // accessor twice on the same RateLimit must yield the same
31616        // `u32` verbatim (idempotent, no side effects on `&self`).
31617        //
31618        // Pins against a future silent detour that returned `&u32`
31619        // (which would type-check but silently break every downstream
31620        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
31621        // first parameter is `u32`, and `&u32` would fold to a detached
31622        // copy at the call site with a `*` deref the sibling accessors
31623        // don't need), an accidental `.rate.wrapping_add(0)` detour that
31624        // returned a fresh copy through an arithmetic no-op (breaking a
31625        // future `const fn` regression), or a one-arm-only accessor
31626        // that returned a saturating value on some sentinel input
31627        // (breaking the pass-through invariant the sibling required-
31628        // scalar accessors carry).
31629        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
31630            let rl = RateLimit {
31631                rate,
31632                window: Duration::from_secs(1),
31633            };
31634            let first = rl.rate();
31635            let second = rl.rate();
31636            assert_eq!(
31637                first, second,
31638                "RateLimit::rate must be idempotent — two successive \
31639                 calls on the same &self must return the same u32",
31640            );
31641            assert_eq!(
31642                first, rate,
31643                "RateLimit::rate must return :politicas :rate-limit :rate \
31644                 verbatim by copy — got {first}, expected {rate}",
31645            );
31646        }
31647    }
31648
31649    #[test]
31650    fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
31651        // The canonical per-`:politicas :rate-limit` `:window`
31652        // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
31653        // pin: [`RateLimit::window`] must return the
31654        // `:politicas :rate-limit :window` typed `Duration` verbatim,
31655        // byte-equal to the raw field access across every
31656        // representative value in the accept-set — `Duration::from_secs(1)`
31657        // (the `"s"` canonical window, the lower row of
31658        // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
31659        // [`AplicacaoSpec::validate_politicas`] gate accepts via
31660        // [`is_canonical_rate_limit_window`]),
31661        // `Duration::from_secs(60)` (the `"m"` canonical window, the
31662        // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
31663        // window, the upper row), `Duration::ZERO` (a past-the-guard
31664        // sentinel that pins the accessor doesn't perform a silent
31665        // bounds-collapse into `Duration::from_secs(1)` on the zero
31666        // arm — validate rejects an off-set window through
31667        // `PolicyRateLimitWindowNotCanonical` but the accessor must
31668        // ship the raw slot verbatim so a validate-time gate
31669        // regression surfaces at the emit boundary rather than being
31670        // silently absorbed), `Duration::from_millis(500)` (a
31671        // sub-canonical past-the-guard sentinel that pins the accessor
31672        // doesn't silently normalize a non-canonical fractional
31673        // magnitude onto the nearest canonical row).
31674        //
31675        // Second sub-struct required-scalar accessor pin on the
31676        // `RateLimit` axis — sibling in shape to the just-landed
31677        // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
31678        // accessor pin on the peer per-sub-struct required-axis,
31679        // extended onto the per-`RateLimit` required-`Duration` axis.
31680        // Pins against a future silent detour that re-derived the
31681        // refill period from a peer axis (an accidental
31682        // `Duration::from_secs(self.rate as u64)` collapse that read
31683        // the rate-limit token capacity as a refill-interval
31684        // duration), a `Duration::ZERO → Duration::from_secs(1)`
31685        // canonical-default projection (which would silently absorb
31686        // the `PolicyRateLimitWindowNotCanonical` refusal case at the
31687        // accessor boundary), or a canonical-set-collapsing accessor
31688        // that clamped the return through [`rate_limit_window_unit`]
31689        // (the `AplicacaoSpec::validate` gate owns the canonical-set
31690        // membership; the accessor must ship the raw slot verbatim).
31691        for window in [
31692            Duration::from_secs(1),
31693            Duration::from_secs(60),
31694            Duration::from_secs(3600),
31695            Duration::ZERO,
31696            Duration::from_millis(500),
31697        ] {
31698            let rl = RateLimit { rate: 100, window };
31699            assert_eq!(
31700                rl.window(),
31701                window,
31702                "RateLimit::window must return :politicas :rate-limit :window \
31703                 verbatim (got {:?}, expected {window:?})",
31704                rl.window(),
31705            );
31706            assert_eq!(
31707                rl.window(),
31708                rl.window,
31709                "RateLimit::window must byte-equal the raw .window field \
31710                 access across every value in the Duration accept-set",
31711            );
31712        }
31713    }
31714
31715    #[test]
31716    fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
31717        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
31718        // `:rate-limit :window` canonical-set arm must key off
31719        // [`RateLimit::window`], not the raw `.window` field access.
31720        // Structurally: a `RateLimit { window: Duration::from_millis(500),
31721        // .. }` embedded in a `:politicas :rate-limit` slot must
31722        // surface the `PolicyRateLimitWindowNotCanonical` refusal
31723        // exactly (with the sub-canonical `Duration::from_millis(500)`
31724        // magnitude carried through verbatim), and a `RateLimit
31725        // { window: Duration::from_secs(1), .. }` (the lower row of
31726        // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
31727        // The pair jointly pins the accessor + validate-gate
31728        // composition: any future silent detour that had the accessor
31729        // normalize the off-set window to the nearest canonical row
31730        // (a `.window().max(Duration::from_secs(1))` collapse, or a
31731        // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
31732        // collapse) would silently absorb the
31733        // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
31734        // boundary — including a drift in the error's `window` payload
31735        // (the emit-side diagnostic reader keys off the offending
31736        // magnitude verbatim, so a normalization at the accessor
31737        // boundary would silently pin the wrong magnitude in the
31738        // refusal). The composition pin catches that at caixa-core
31739        // build time.
31740        //
31741        // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
31742        // (7f81a60) accessor-composition pin on the peer required-
31743        // scalar `:rate` axis — same "the validate / shape-gate
31744        // predicate must route through the substrate-primitive typed
31745        // dispatch, and the error payload must project through the
31746        // same accessor" discipline extended onto the peer
31747        // per-`RateLimit` required-`Duration` composition axis.
31748        let mut spec = three_member_spec();
31749        spec.politicas = MeshPolicy {
31750            rate_limit: Some(RateLimit {
31751                rate: 100,
31752                window: Duration::from_millis(500),
31753            }),
31754            ..MeshPolicy::default()
31755        };
31756        match spec.validate() {
31757            Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
31758                assert_eq!(
31759                    window,
31760                    Duration::from_millis(500),
31761                    "PolicyRateLimitWindowNotCanonical must carry the \
31762                     offending :window magnitude verbatim through the \
31763                     accessor — got {window:?}, expected 500ms",
31764                );
31765            }
31766            other => panic!(
31767                "validate_politicas must reject non-canonical :window \
31768                 with PolicyRateLimitWindowNotCanonical — the accessor \
31769                 and the validate gate must route through the same \
31770                 substrate-primitive typed dispatch on the :window \
31771                 canonical-set arm; got {other:?}",
31772            ),
31773        }
31774        spec.politicas = MeshPolicy {
31775            rate_limit: Some(RateLimit {
31776                rate: 100,
31777                window: Duration::from_secs(1),
31778            }),
31779            ..MeshPolicy::default()
31780        };
31781        assert!(
31782            spec.validate().is_ok(),
31783            "validate_politicas must accept window == Duration::from_secs(1) \
31784             (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
31785        );
31786    }
31787
31788    #[test]
31789    fn rate_limit_window_projects_duration_by_copy() {
31790        // The by-copy pin: [`RateLimit::window`] returns `Duration`
31791        // by copy — `Duration` is `Copy` and the accessor must return
31792        // by value, not by reference. Peer of the sibling per-`RateLimit`
31793        // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
31794        // required-scalar `:rate` axis, extended onto the peer
31795        // per-`RateLimit` required-`Duration` copy-invariant shape —
31796        // the accessor's returned `Duration` must outlive `&self`
31797        // (multiple calls must return equal values from a
31798        // dropped-`&self` copy, since the returned scalar carries no
31799        // borrow), and calling the accessor twice on the same
31800        // RateLimit must yield the same `Duration` verbatim
31801        // (idempotent, no side effects on `&self`).
31802        //
31803        // Pins against a future silent detour that returned
31804        // `&Duration` (which would type-check but silently break every
31805        // downstream `Duration`-by-value consumer —
31806        // [`is_canonical_rate_limit_window`]'s first parameter is
31807        // `Duration`, and `&Duration` would fold to a detached copy at
31808        // the call site with a `*` deref the sibling accessors don't
31809        // need), an accidental `.window + Duration::ZERO` detour that
31810        // returned a fresh copy through an arithmetic no-op (breaking
31811        // a future `const fn` regression), or a one-arm-only accessor
31812        // that returned a canonical fallback on some sentinel input
31813        // (breaking the pass-through invariant the sibling required-
31814        // scalar accessors carry).
31815        for window in [
31816            Duration::from_secs(1),
31817            Duration::from_secs(60),
31818            Duration::from_secs(3600),
31819            Duration::ZERO,
31820            Duration::from_millis(500),
31821        ] {
31822            let rl = RateLimit { rate: 100, window };
31823            let first = rl.window();
31824            let second = rl.window();
31825            assert_eq!(
31826                first, second,
31827                "RateLimit::window must be idempotent — two successive \
31828                 calls on the same &self must return the same Duration",
31829            );
31830            assert_eq!(
31831                first, window,
31832                "RateLimit::window must return :politicas :rate-limit :window \
31833                 verbatim by copy — got {first:?}, expected {window:?}",
31834            );
31835        }
31836    }
31837
31838    #[test]
31839    fn placement_estrategia_default_pins_m3_canonical_value() {
31840        // Pin [`PLACEMENT_ESTRATEGIA_DEFAULT`] at
31841        // [`PlacementStrategy::Replicated`] — MESH-COMPOSITION §II.2's
31842        // active-active-across-every-named-cluster arm, the closest
31843        // canonical M3 production reference the substrate carries and
31844        // the arm the caixa-mesh `programs.yaml` fan-out already keys off
31845        // for every un-`:placement`-declared Aplicacao. Pinning the arm
31846        // here surfaces a future rebrand of the M3-canonical
31847        // distribution default (a widening to `Sharded` once the
31848        // substrate discovers hash-keyed distribution as the more
31849        // common production shape, a tightening to `SingleNode` for
31850        // stateful Erlang/OTP distributed-app-takeover semantics
31851        // MESH-COMPOSITION §II.1 names, a per-cluster overlay the
31852        // operator pins through a future `:placement-overrides` slot)
31853        // as a deliberate test edit, not a silent contract migration.
31854        // Peer of the sibling M2 per-supervisor value pins
31855        // [`crate::supervisor::tests::supervisor_estrategia_default_pins_otp_canonical_value`]
31856        // /
31857        // [`crate::supervisor::tests::supervisor_child_restart_default_pins_otp_canonical_value`]
31858        // extended onto the M3 mesh-primitive-defining `:placement
31859        // :estrategia` axis.
31860        assert_eq!(PLACEMENT_ESTRATEGIA_DEFAULT, PlacementStrategy::Replicated);
31861    }
31862
31863    #[test]
31864    fn placement_strategy_default_routes_through_lifted_default() {
31865        // Composition pin: the [`Default for PlacementStrategy`] impl's
31866        // return arm must route through the substrate-canonical
31867        // [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
31868        // a raw `Self::Replicated` arm. Prior to the lift the impl
31869        // carried an inline `Self::Replicated` arm with no compile-time
31870        // link back to the shared M3-canonical `Replicated` arm the
31871        // paired [`Default for Placement`] impl's struct-literal
31872        // `estrategia` field, the serde-side `#[serde(default)]` on
31873        // [`Placement::estrategia`] that resolves an author-omitted
31874        // wire-form `:placement :estrategia` scalar through the impl,
31875        // and the [`crate::manifest::Caixa::aplicacao_view`] fold's
31876        // `.unwrap_or_default()` `Option<Placement>` collapse arm (which
31877        // routes through [`Placement::default`] which routes through the
31878        // strategy default) all key off — so a future rebrand of the
31879        // M3-canonical distribution default would have had to be threaded
31880        // through the `Default` impl and the three peer routes in
31881        // lockstep or the four consumers would silently split. Byte-
31882        // parity against the lifted constant closes the split. Peer of
31883        // the sibling
31884        // [`crate::supervisor::tests::restart_strategy_default_routes_through_lifted_default`]
31885        // /
31886        // [`crate::supervisor::tests::restart_policy_default_routes_through_lifted_default`]
31887        // composition pins on the M2 per-supervisor axes.
31888        assert_eq!(PlacementStrategy::default(), PLACEMENT_ESTRATEGIA_DEFAULT);
31889    }
31890
31891    #[test]
31892    fn placement_default_estrategia_routes_through_lifted_default() {
31893        // Composition pin: the [`Default for Placement`] impl's
31894        // struct-literal `estrategia` field must route through the
31895        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
31896        // `pub const` (either directly, or via the [`PlacementStrategy::default`]
31897        // impl that the sibling
31898        // `placement_strategy_default_routes_through_lifted_default` pin
31899        // already routes onto the constant). Structurally: every
31900        // `Placement::default()` call must yield an `estrategia` field
31901        // byte-equal to the lifted constant so the two paired defaults —
31902        // the [`Default for PlacementStrategy`] impl arm and the
31903        // struct-literal default arm here — cannot silently split on any
31904        // future M3-canonical distribution-default rebrand. Peer of the
31905        // sibling M2
31906        // [`crate::supervisor::tests::supervisor_spec_default_estrategia_routes_through_lifted_default`]
31907        // byte-parity pin on the [`Default for SupervisorSpec`]
31908        // struct-literal `estrategia` field extended onto the M3
31909        // mesh-primitive-defining slot family.
31910        assert_eq!(
31911            Placement::default().estrategia,
31912            PLACEMENT_ESTRATEGIA_DEFAULT,
31913        );
31914    }
31915
31916    #[test]
31917    fn placement_serde_default_estrategia_routes_through_lifted_default() {
31918        // Composition pin: the serde-side `#[serde(default)]` on
31919        // [`Placement::estrategia`] — the wire-format author-omitted
31920        // `:placement :estrategia` arm — must resolve onto the substrate-
31921        // canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const`
31922        // (via the [`Default for PlacementStrategy`] impl the sibling
31923        // `placement_strategy_default_routes_through_lifted_default` pin
31924        // already routes onto the constant). Structurally: a `Placement`
31925        // deserialized from a payload that omits the `estrategia` key
31926        // must yield an `estrategia` field byte-equal to the lifted
31927        // constant, so the wire-format author-omitted arm and the
31928        // [`PlacementStrategy::default`] impl arm cannot silently split
31929        // on any future M3-canonical distribution-default rebrand. Peer
31930        // of the sibling M2
31931        // [`crate::supervisor::tests::child_spec_serde_default_restart_routes_through_lifted_default`]
31932        // byte-parity pin on the wire-format author-omitted `:children
31933        // :restart` scalar extended onto the M3 mesh-primitive-defining
31934        // slot family.
31935        let omitted: Placement = serde_json::from_str("{}")
31936            .expect("Placement must deserialize with the estrategia key omitted");
31937        assert_eq!(
31938            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
31939            "an author-omitted :placement :estrategia slot must degrade onto \
31940             the PLACEMENT_ESTRATEGIA_DEFAULT typed pub const (got \
31941             {:?}, expected {:?})",
31942            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
31943        );
31944    }
31945
31946    // ── contrato_target_ctors! fold pins ────────────────────────────────
31947    //
31948    // Fixture edge triple + payload-field-name label pair for every
31949    // `contrato_target_ctors!`-generated ctor pin below. Kept as
31950    // non-default `("cart", "catalog", "wasi:http/proxy")` +
31951    // `WitTarget::HTTP_FIELD_NAME` so a byte-equality mistake against
31952    // the fixture default doesn't silently pass. Peer of the sibling
31953    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
31954    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
31955    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
31956    // `missing_entry_ctor_matches_struct_literal_wrap` /
31957    // `<slot>_ctor_matches_tuple_literal_wrap` equivalence pins on the
31958    // four `LayoutError` constructor families each closed on their
31959    // sibling envelopes.
31960    fn contrato_target_ctor_fixture() -> (String, String, String, &'static str) {
31961        (
31962            "cart".to_string(),
31963            "catalog".to_string(),
31964            "wasi:http/proxy".to_string(),
31965            WitTarget::HTTP_FIELD_NAME,
31966        )
31967    }
31968
31969    #[test]
31970    fn contrato_wrong_target_ctor_matches_struct_literal_wrap() {
31971        // Equivalence pin: the ctor produces byte-equal
31972        // `AplicacaoError::ContratoWrongTarget` to the pre-lift open-
31973        // coded struct-literal on the same edge fixture, so the fold
31974        // cannot silently drift on any future field-addition /
31975        // reordering / string-conversion tweak on the variant. Peer of
31976        // the sibling `entrada_host_invalid_ctor_matches_struct_literal_wrap`
31977        // (17dd504) / the four `LayoutError` family equivalence pins.
31978        let (de, para, wit, expected) = contrato_target_ctor_fixture();
31979        let lifted = AplicacaoError::contrato_wrong_target(
31980            (de.clone(), para.clone(), wit.clone()),
31981            expected,
31982        );
31983        let struct_literal = AplicacaoError::ContratoWrongTarget {
31984            de,
31985            para,
31986            wit,
31987            expected,
31988        };
31989        assert_eq!(lifted, struct_literal);
31990    }
31991
31992    #[test]
31993    fn contrato_missing_target_ctor_matches_struct_literal_wrap() {
31994        // Equivalence pin peer of the sibling
31995        // `contrato_wrong_target_ctor_matches_struct_literal_wrap` above
31996        // on the paired `ContratoMissingTarget` variant of the same
31997        // four-slot envelope shape the `contrato_target_ctors!` macro
31998        // closes.
31999        let (de, para, wit, expected) = contrato_target_ctor_fixture();
32000        let lifted = AplicacaoError::contrato_missing_target(
32001            (de.clone(), para.clone(), wit.clone()),
32002            expected,
32003        );
32004        let struct_literal = AplicacaoError::ContratoMissingTarget {
32005            de,
32006            para,
32007            wit,
32008            expected,
32009        };
32010        assert_eq!(lifted, struct_literal);
32011    }
32012
32013    #[test]
32014    fn contrato_target_ctors_route_edge_triple_through_verbatim() {
32015        // Routing pin: the `(de, para, wit)` triple threads verbatim
32016        // onto same-named fields on both generated ctors, no wrapper-
32017        // side lowercase / trim / re-order. Sweeps a non-default triple
32018        // (`"cart-svc" → "catalog-v2"`, `"nats:pub-sub"`) so any
32019        // wrapper-side transformation surfaces here rather than at a
32020        // downstream diagnostic-shape drift. Sibling of
32021        // `entrada_host_invalid_ctor_routes_host_through_to_string`
32022        // (17dd504) on the paired triple-carrying envelope.
32023        let edge = (
32024            "cart-svc".to_string(),
32025            "catalog-v2".to_string(),
32026            "nats:pub-sub".to_string(),
32027        );
32028        let wrong =
32029            AplicacaoError::contrato_wrong_target(edge.clone(), WitTarget::PUBSUB_FIELD_NAME);
32030        let missing = AplicacaoError::contrato_missing_target(edge, WitTarget::PUBSUB_FIELD_NAME);
32031        let AplicacaoError::ContratoWrongTarget {
32032            de: wde,
32033            para: wpara,
32034            wit: wwit,
32035            ..
32036        } = wrong
32037        else {
32038            panic!("contrato_wrong_target must construct the ContratoWrongTarget variant");
32039        };
32040        let AplicacaoError::ContratoMissingTarget {
32041            de: mde,
32042            para: mpara,
32043            wit: mwit,
32044            ..
32045        } = missing
32046        else {
32047            panic!("contrato_missing_target must construct the ContratoMissingTarget variant");
32048        };
32049        assert_eq!(wde, "cart-svc");
32050        assert_eq!(wpara, "catalog-v2");
32051        assert_eq!(wwit, "nats:pub-sub");
32052        assert_eq!(mde, "cart-svc");
32053        assert_eq!(mpara, "catalog-v2");
32054        assert_eq!(mwit, "nats:pub-sub");
32055    }
32056
32057    #[test]
32058    fn contrato_target_ctors_route_expected_through_verbatim() {
32059        // Routing pin: the `expected: &'static str` label threads
32060        // verbatim (identity, not copy-and-transform) onto the
32061        // `expected` field of both variants, so the four canonical
32062        // labels [`WitTarget::HTTP_FIELD_NAME`] /
32063        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
32064        // / [`WitTarget::CAPABILITY_EXPECTED`] survive the fold as
32065        // pointer-equal (not merely value-equal) references — a wrapper-
32066        // side `.to_string()` / `Cow::Owned` promotion would break the
32067        // `&'static str` contract downstream consumers depend on.
32068        for label in [
32069            WitTarget::HTTP_FIELD_NAME,
32070            WitTarget::PUBSUB_FIELD_NAME,
32071            WitTarget::STORE_FIELD_NAME,
32072            WitTarget::CAPABILITY_EXPECTED,
32073        ] {
32074            let (de, para, wit, _) = contrato_target_ctor_fixture();
32075            let wrong = AplicacaoError::contrato_wrong_target(
32076                (de.clone(), para.clone(), wit.clone()),
32077                label,
32078            );
32079            let missing = AplicacaoError::contrato_missing_target((de, para, wit), label);
32080            match wrong {
32081                AplicacaoError::ContratoWrongTarget { expected, .. } => {
32082                    assert!(
32083                        std::ptr::eq(expected.as_ptr(), label.as_ptr())
32084                            && expected.len() == label.len(),
32085                        "contrato_wrong_target must thread the &'static str \
32086                         label pointer-equal onto the `expected` field \
32087                         (label = {label:?})",
32088                    );
32089                }
32090                other => panic!("expected ContratoWrongTarget, got {other:?}"),
32091            }
32092            match missing {
32093                AplicacaoError::ContratoMissingTarget { expected, .. } => {
32094                    assert!(
32095                        std::ptr::eq(expected.as_ptr(), label.as_ptr())
32096                            && expected.len() == label.len(),
32097                        "contrato_missing_target must thread the &'static \
32098                         str label pointer-equal onto the `expected` field \
32099                         (label = {label:?})",
32100                    );
32101                }
32102                other => panic!("expected ContratoMissingTarget, got {other:?}"),
32103            }
32104        }
32105    }
32106
32107    // ── contrato_empty_pair_ctors! fold pins ────────────────────────────
32108    //
32109    // Fixture edge pair for every `contrato_empty_pair_ctors!`-generated
32110    // ctor pin below. Kept as non-default `("cart", "catalog")` so a
32111    // byte-equality mistake against the fixture default doesn't silently
32112    // pass. Peer of the sibling `contrato_target_ctor_fixture` (14b81d5,
32113    // triple + expected-label envelope on
32114    // `contrato_target_ctors!`) / `entrada_host_invalid_ctor_matches_
32115    // struct_literal_wrap` (17dd504, host + reason envelope on
32116    // `entrada_host_invalid`) / the four `LayoutError` family
32117    // equivalence pins.
32118    fn contrato_empty_pair_ctor_fixture() -> (String, String) {
32119        ("cart".to_string(), "catalog".to_string())
32120    }
32121
32122    #[test]
32123    fn empty_wit_ctor_matches_struct_literal_wrap() {
32124        // Equivalence pin: the ctor produces byte-equal
32125        // `AplicacaoError::EmptyWit` to the pre-lift open-coded
32126        // struct-literal on the same edge pair, so the fold cannot
32127        // silently drift on any future field-addition / reordering /
32128        // string-conversion tweak on the variant. Peer of the sibling
32129        // `contrato_wrong_target_ctor_matches_struct_literal_wrap`
32130        // (14b81d5) / `entrada_host_invalid_ctor_matches_struct_literal_wrap`
32131        // (17dd504) / the four `LayoutError` family equivalence pins.
32132        let (de, para) = contrato_empty_pair_ctor_fixture();
32133        let lifted = AplicacaoError::empty_wit((de.clone(), para.clone()));
32134        let struct_literal = AplicacaoError::EmptyWit { de, para };
32135        assert_eq!(lifted, struct_literal);
32136    }
32137
32138    #[test]
32139    fn contrato_endpoint_empty_ctor_matches_struct_literal_wrap() {
32140        // Equivalence pin peer of the sibling
32141        // `empty_wit_ctor_matches_struct_literal_wrap` above on the
32142        // paired `ContratoEndpointEmpty` variant of the same two-slot
32143        // envelope shape the `contrato_empty_pair_ctors!` macro closes.
32144        let (de, para) = contrato_empty_pair_ctor_fixture();
32145        let lifted = AplicacaoError::contrato_endpoint_empty((de.clone(), para.clone()));
32146        let struct_literal = AplicacaoError::ContratoEndpointEmpty { de, para };
32147        assert_eq!(lifted, struct_literal);
32148    }
32149
32150    #[test]
32151    fn contrato_subject_empty_ctor_matches_struct_literal_wrap() {
32152        // Equivalence pin peer of the sibling
32153        // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
32154        // above on the paired `ContratoSubjectEmpty` variant of the
32155        // same two-slot envelope shape.
32156        let (de, para) = contrato_empty_pair_ctor_fixture();
32157        let lifted = AplicacaoError::contrato_subject_empty((de.clone(), para.clone()));
32158        let struct_literal = AplicacaoError::ContratoSubjectEmpty { de, para };
32159        assert_eq!(lifted, struct_literal);
32160    }
32161
32162    #[test]
32163    fn contrato_slot_empty_ctor_matches_struct_literal_wrap() {
32164        // Equivalence pin peer of the sibling
32165        // `contrato_subject_empty_ctor_matches_struct_literal_wrap`
32166        // above on the paired `ContratoSlotEmpty` variant of the same
32167        // two-slot envelope shape.
32168        let (de, para) = contrato_empty_pair_ctor_fixture();
32169        let lifted = AplicacaoError::contrato_slot_empty((de.clone(), para.clone()));
32170        let struct_literal = AplicacaoError::ContratoSlotEmpty { de, para };
32171        assert_eq!(lifted, struct_literal);
32172    }
32173
32174    #[test]
32175    fn contrato_empty_pair_ctors_route_edge_pair_through_verbatim() {
32176        // Routing pin: the `(de, para)` pair threads verbatim onto
32177        // same-named fields on all four generated ctors, no wrapper-
32178        // side lowercase / trim / re-order. Sweeps a non-default pair
32179        // (`"cart-svc" → "catalog-v2"`) so any wrapper-side
32180        // transformation surfaces here rather than at a downstream
32181        // diagnostic-shape drift. Sibling of
32182        // `contrato_target_ctors_route_edge_triple_through_verbatim`
32183        // (14b81d5) on the paired triple-carrying envelope and of
32184        // `entrada_host_invalid_ctor_routes_host_through_to_string`
32185        // (17dd504) on the sibling `{ host, reason }` envelope.
32186        let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
32187        let variants: [(AplicacaoError, &'static str); 4] = [
32188            (AplicacaoError::empty_wit(edge.clone()), "EmptyWit"),
32189            (
32190                AplicacaoError::contrato_endpoint_empty(edge.clone()),
32191                "ContratoEndpointEmpty",
32192            ),
32193            (
32194                AplicacaoError::contrato_subject_empty(edge.clone()),
32195                "ContratoSubjectEmpty",
32196            ),
32197            (
32198                AplicacaoError::contrato_slot_empty(edge.clone()),
32199                "ContratoSlotEmpty",
32200            ),
32201        ];
32202        for (built, label) in variants {
32203            let (de, para) = match built {
32204                AplicacaoError::EmptyWit { de, para }
32205                | AplicacaoError::ContratoEndpointEmpty { de, para }
32206                | AplicacaoError::ContratoSubjectEmpty { de, para }
32207                | AplicacaoError::ContratoSlotEmpty { de, para } => (de, para),
32208                other => panic!("expected {label} pair variant, got {other:?}"),
32209            };
32210            assert_eq!(de, "cart-svc", "de field on {label} must thread verbatim");
32211            assert_eq!(
32212                para, "catalog-v2",
32213                "para field on {label} must thread verbatim",
32214            );
32215        }
32216    }
32217
32218    // ── contrato_pair_value_reason_ctors! fold pins ─────────────────────
32219    //
32220    // Fixture edge pair + value + reason for every
32221    // `contrato_pair_value_reason_ctors!`-generated ctor pin below. Kept
32222    // as non-default `("cart", "catalog")` on the `(de, para)` pair and
32223    // fixed per-axis `<val>` / reason so a byte-equality mistake against
32224    // the fixture default doesn't silently pass. Peer of the sibling
32225    // `contrato_empty_pair_ctor_fixture` (8580068, pair-only envelope on
32226    // `contrato_empty_pair_ctors!`) / `contrato_target_ctor_fixture`
32227    // (14b81d5, triple + expected-label envelope on
32228    // `contrato_target_ctors!`) / `entrada_host_invalid_ctor_matches_
32229    // struct_literal_wrap` (17dd504, host + reason envelope on
32230    // `entrada_host_invalid`).
32231    fn contrato_pair_value_reason_ctor_fixture() -> (String, String) {
32232        ("cart".to_string(), "catalog".to_string())
32233    }
32234
32235    #[test]
32236    fn contrato_endpoint_invalid_ctor_matches_struct_literal_wrap() {
32237        // Equivalence pin: the ctor produces byte-equal
32238        // `AplicacaoError::ContratoEndpointInvalid` to the pre-lift
32239        // open-coded struct-literal on the same
32240        // `(edge_pair, endpoint, reason)` triple, so the fold cannot
32241        // silently drift on any future field-addition / reordering /
32242        // string-conversion tweak on the variant. Peer of the sibling
32243        // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
32244        // (8580068) on the paired two-slot envelope of the same
32245        // `{ de, para, ... }` prefix, and of
32246        // `entrada_host_invalid_ctor_matches_struct_literal_wrap`
32247        // (17dd504) on the sibling `{ <field>: String, reason: String }`
32248        // two-slot envelope.
32249        let (de, para) = contrato_pair_value_reason_ctor_fixture();
32250        let endpoint = "/charge";
32251        let reason = "sample reason text";
32252        let lifted =
32253            AplicacaoError::contrato_endpoint_invalid((de.clone(), para.clone()), endpoint, reason);
32254        let struct_literal = AplicacaoError::ContratoEndpointInvalid {
32255            de,
32256            para,
32257            endpoint: endpoint.to_string(),
32258            reason: reason.to_string(),
32259        };
32260        assert_eq!(lifted, struct_literal);
32261    }
32262
32263    #[test]
32264    fn contrato_subject_invalid_ctor_matches_struct_literal_wrap() {
32265        // Equivalence pin peer of the sibling
32266        // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap`
32267        // above on the paired `ContratoSubjectInvalid` variant of the
32268        // same four-slot envelope shape the
32269        // `contrato_pair_value_reason_ctors!` macro closes.
32270        let (de, para) = contrato_pair_value_reason_ctor_fixture();
32271        let subject = "checkout.events.charge.failed";
32272        let reason = "sample reason text";
32273        let lifted =
32274            AplicacaoError::contrato_subject_invalid((de.clone(), para.clone()), subject, reason);
32275        let struct_literal = AplicacaoError::ContratoSubjectInvalid {
32276            de,
32277            para,
32278            subject: subject.to_string(),
32279            reason: reason.to_string(),
32280        };
32281        assert_eq!(lifted, struct_literal);
32282    }
32283
32284    #[test]
32285    fn contrato_slot_invalid_ctor_matches_struct_literal_wrap() {
32286        // Equivalence pin peer of the sibling
32287        // `contrato_subject_invalid_ctor_matches_struct_literal_wrap`
32288        // above on the paired `ContratoSlotInvalid` variant of the same
32289        // four-slot envelope shape.
32290        let (de, para) = contrato_pair_value_reason_ctor_fixture();
32291        let slot = "checkout/$orderId";
32292        let reason = "sample reason text";
32293        let lifted =
32294            AplicacaoError::contrato_slot_invalid((de.clone(), para.clone()), slot, reason);
32295        let struct_literal = AplicacaoError::ContratoSlotInvalid {
32296            de,
32297            para,
32298            slot: slot.to_string(),
32299            reason: reason.to_string(),
32300        };
32301        assert_eq!(lifted, struct_literal);
32302    }
32303
32304    #[test]
32305    fn contrato_pair_value_reason_ctors_route_edge_pair_through_verbatim() {
32306        // Routing pin: the `(de, para)` pair threads verbatim onto
32307        // same-named fields on all three generated ctors, no wrapper-
32308        // side lowercase / trim / re-order. Sweeps a non-default pair
32309        // (`"cart-svc" → "catalog-v2"`) so any wrapper-side
32310        // transformation surfaces here rather than at a downstream
32311        // diagnostic-shape drift. Sibling of
32312        // `contrato_empty_pair_ctors_route_edge_pair_through_verbatim`
32313        // (8580068) on the paired two-slot envelope and of
32314        // `contrato_target_ctors_route_edge_triple_through_verbatim`
32315        // (14b81d5) on the paired triple-carrying envelope.
32316        let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
32317        let variants: [(AplicacaoError, &'static str); 3] = [
32318            (
32319                AplicacaoError::contrato_endpoint_invalid(edge.clone(), "/x", "r"),
32320                "ContratoEndpointInvalid",
32321            ),
32322            (
32323                AplicacaoError::contrato_subject_invalid(edge.clone(), "x.y", "r"),
32324                "ContratoSubjectInvalid",
32325            ),
32326            (
32327                AplicacaoError::contrato_slot_invalid(edge.clone(), "x/y", "r"),
32328                "ContratoSlotInvalid",
32329            ),
32330        ];
32331        for (built, label) in variants {
32332            let (de, para) = match built {
32333                AplicacaoError::ContratoEndpointInvalid { de, para, .. }
32334                | AplicacaoError::ContratoSubjectInvalid { de, para, .. }
32335                | AplicacaoError::ContratoSlotInvalid { de, para, .. } => (de, para),
32336                other => panic!("expected {label} pair variant, got {other:?}"),
32337            };
32338            assert_eq!(de, "cart-svc", "de field on {label} must thread verbatim");
32339            assert_eq!(
32340                para, "catalog-v2",
32341                "para field on {label} must thread verbatim",
32342            );
32343        }
32344    }
32345
32346    #[test]
32347    fn contrato_pair_value_reason_ctors_route_reason_through_into_uniformly() {
32348        // Cross-arm invariance pin — the three ctors all route
32349        // `reason: impl Into<String>` verbatim onto their respective
32350        // typed variants through the shared
32351        // [`contrato_pair_value_reason_ctors!`] macro. Sweeps a fixture
32352        // pair (`&str` literal, `format!` output) against every ctor to
32353        // pin that no per-arm wrapper transformation drifted in against
32354        // the uniform macro-generated body. Peer of
32355        // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
32356        // (981060b) on the sibling two-slot envelope's cross-arm sweep.
32357        let edge = || ("cart".to_string(), "catalog".to_string());
32358        let via_literal = "literal reason text";
32359        let via_format = format!("{} reason text", "literal");
32360        assert_eq!(
32361            AplicacaoError::contrato_endpoint_invalid(edge(), "/e", via_literal),
32362            AplicacaoError::contrato_endpoint_invalid(edge(), "/e", via_format.clone()),
32363        );
32364        assert_eq!(
32365            AplicacaoError::contrato_subject_invalid(edge(), "s.t", via_literal),
32366            AplicacaoError::contrato_subject_invalid(edge(), "s.t", via_format.clone()),
32367        );
32368        assert_eq!(
32369            AplicacaoError::contrato_slot_invalid(edge(), "k/v", via_literal),
32370            AplicacaoError::contrato_slot_invalid(edge(), "k/v", via_format),
32371        );
32372    }
32373}