Skip to main content

caixa_core/
aplicacao.rs

1//! Typed Aplicacao — the fourth caixa kind that turns a graph of
2//! Servicos into a single declarative application (mesh).
3//!
4//! See `theory/MESH-COMPOSITION.md` for the design frame: an
5//! Aplicacao composes [`crate::CaixaKind::Servico`] caixas via WIT-typed
6//! `:contratos` (inter-Servico edges), declares mesh-level
7//! `:politicas` (timeouts, retries, breakers, mTLS), pins
8//! `:placement` strategy (single-node / replicated / sharded), and
9//! exposes `:entrada` (gateway).
10//!
11//! ```lisp
12//! (defcaixa
13//!   :nome      "checkout"
14//!   :versao    "0.1.0"
15//!   :kind      Aplicacao
16//!   :membros   ((:caixa "catalog"     :versao "^0.1")
17//!               (:caixa "cart"        :versao "^0.1")
18//!               (:caixa "payment"     :versao "^0.2"))
19//!   :contratos ((:de "cart" :para "catalog"
20//!                :wit "wasi:http/proxy" :endpoint "/products/:id")
21//!               (:de "cart" :para "payment"
22//!                :wit "wasi:http/proxy" :endpoint "/charge"))
23//!   :politicas ((:timeout "30s")
24//!               (:retries 3)
25//!               (:circuit-breaker (:max-failures 5 :window "60s"))
26//!               (:mtls-required t))
27//!   :placement (:estrategia replicated
28//!               :clusters   ("rio" "mar" "plo"))
29//!   :entrada   (:host  "checkout.quero.cloud"
30//!               :para  "cart"
31//!               :paths ("/api/cart" "/api/products")))
32//! ```
33//!
34//! All the typed slots compose with the M2 primitives the Servicos
35//! they reference already declare (`:limits`, `:behavior`,
36//! `:upgrade-from`). The Aplicacao adds the *graph-level*
37//! standardization on top.
38
39use std::time::Duration;
40
41use serde::{Deserialize, Serialize};
42use thiserror::Error;
43
44use crate::supervisor; // we reuse the duration-string codec at module scope
45
46// ── inter-Servico contracts ──────────────────────────────────────────
47
48/// One typed edge in the Aplicacao graph. The build refuses any
49/// contract whose `:de` or `:para` doesn't appear in `:membros`, and
50/// (M3+) cross-checks the `:wit` shape against both Servicos'
51/// declared imports/exports.
52#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
53#[serde(rename_all = "camelCase")]
54pub struct WitContract {
55    /// Caller Servico — must reference an entry in the Aplicacao's
56    /// `:membros`. The Servico's caixa.lisp must declare a matching
57    /// `:capabilities` import for the `:wit` world.
58    pub de: String,
59
60    /// Callee Servico — must reference an entry in `:membros`. The
61    /// Servico must declare a matching `:capabilities` export.
62    pub para: String,
63
64    /// WIT world reference — e.g. `"wasi:http/proxy"`,
65    /// `"wasi:keyvalue/store"`, `"nats:pub-sub"`. Strings for V0;
66    /// M4 promotes these to a typed enum once the WIT registry
67    /// stabilizes in tatara-lisp.
68    pub wit: String,
69
70    /// HTTP endpoint path, present when `:wit` is HTTP-shaped.
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub endpoint: Option<String>,
73
74    /// NATS / event-stream subject, present when `:wit` is pub-sub-shaped.
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub subject: Option<String>,
77
78    /// Key/value or queue slot, present when `:wit` is store-shaped.
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub slot: Option<String>,
81}
82
83/// Canonical lowercase byte-prefix set the substrate's WIT-shape
84/// dispatch routes `wasi:http/*` / `http:*` values through as the
85/// HTTP-shaped arm. The single source of truth every consumer that
86/// classifies a `:wit` value as HTTP-shaped consults —
87/// [`WitContract::is_http`] on the typed contract, the
88/// `AplicacaoSpec::validate` positive-sweep test's payload-dispatch
89/// helper, and every future renderer that routes an L7 emission off a
90/// bare `&str` (the M4 per-edge WIT registry resolver, the future
91/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer). Spelled
92/// exactly as the [`is_wit_world_ref`][iwr] predicate documents the
93/// canonical lowercase prefixes ("`wasi:http/`, `nats:`,
94/// `wasi:keyvalue/`, `kafka:`, `kv:`, `http:`") so drift between the
95/// substrate's accept-set and this crate's dispatch-set is a
96/// build-time compile error (unused-import), not a per-renderer
97/// silent L7-→-L4 demotion at apply time.
98///
99/// [iwr]: crate::render::is_wit_world_ref
100pub const WIT_HTTP_SHAPE_PREFIXES: &[&str] = &["wasi:http/", "http:"];
101
102/// Canonical lowercase byte-prefix set the substrate's WIT-shape
103/// dispatch routes `nats:*` / `kafka:*` values through as the
104/// pub-sub-shaped arm. Peer of [`WIT_HTTP_SHAPE_PREFIXES`] /
105/// [`WIT_STORE_SHAPE_PREFIXES`] on the shape-dispatch axis; see the
106/// HTTP constant's docstring for the full lift rationale.
107pub const WIT_PUBSUB_SHAPE_PREFIXES: &[&str] = &["nats:", "kafka:"];
108
109/// Canonical lowercase byte-prefix set the substrate's WIT-shape
110/// dispatch routes `wasi:keyvalue/*` / `kv:*` values through as the
111/// key/value-store-shaped arm. Peer of [`WIT_HTTP_SHAPE_PREFIXES`] /
112/// [`WIT_PUBSUB_SHAPE_PREFIXES`] on the shape-dispatch axis; see the
113/// HTTP constant's docstring for the full lift rationale.
114pub const WIT_STORE_SHAPE_PREFIXES: &[&str] = &["wasi:keyvalue/", "kv:"];
115
116/// True when `wit` — a raw `:contratos :wit` value — starts with any
117/// entry in the `prefixes` accept-set. The single canonical
118/// prefix-driven WIT-shape classification combinator every peer
119/// per-shape predicate ([`wit_shape_is_http`], [`wit_shape_is_pubsub`],
120/// [`wit_shape_is_store`]) routes through, closing the 3-site
121/// duplication of the `PREFIXES.iter().any(|p| wit.starts_with(p))`
122/// combinator the prior open-coded implementations each carried.
123///
124/// A future 4th WIT-shape dispatch arm (a hypothetical `wasi:sockets/*`
125/// / `tcp:*` transport-layer shape, an `oci:*` capability-import
126/// carrier) becomes exactly one new [`WIT_*_SHAPE_PREFIXES`] const +
127/// one new `wit_shape_is_<name>` one-liner routing through this
128/// combinator, not a fourth copy of the `iter().any(starts_with)`
129/// combinator paired to its own prefix-set. Same "one canonical
130/// combinator, thin per-arm projections" discipline the peer
131/// [`WitTarget::payload_pair`] (6788ed6) already established for the
132/// downstream per-arm `(field, payload)` dispatch, extended to the
133/// upstream per-arm `PREFIXES → bool` dispatch.
134///
135/// Declared `pub const fn` — the four peer classifiers
136/// ([`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
137/// [`wit_shape_is_store`] / [`wit_shape_is_capability`]) route through
138/// this combinator in `const`-eval context, so the raw `&str → bool`
139/// WIT-shape dispatch reaches every substrate-side `const`-context
140/// consumer (the module-scope `const _: () = assert!(…)` canonical-
141/// accept-set + partition-witness pins immediately below the four
142/// peer classifiers, any future M4
143/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
144/// webhook `const fn` per-`:contratos :wit` shape-arm resolver over a
145/// raw &str, any future `const fn` per-`:contratos`-edge WIT-registry
146/// prefix-set overlay resolver over the substrate primitive that fans
147/// on the shape arm at compile time) through the same typed dispatch
148/// on the substrate primitive at const-eval time as at runtime. The
149/// prior `prefixes.iter().any(|p| wit.starts_with(p))` body carried
150/// non-`const` bounds on stable Rust 1.94 (`.iter()` / `.any()` /
151/// `str::starts_with(&str)` via the non-`const` `Pattern` trait); the
152/// new body routes the per-prefix probe through a manual byte-level
153/// `starts_with` loop over the paired `str::as_bytes` (`pub const fn`)
154/// slice projections, dispatching through primitive-`u8` `!=` and
155/// `usize` comparison + `pub const fn` `<[u8]>::len` and const-stable
156/// slice indexing (since Rust 1.79) — every operation `const`-eval-
157/// callable on stable, no iterator methods, no `Pattern` trait.
158#[must_use]
159pub const fn wit_shape_matches(wit: &str, prefixes: &[&str]) -> bool {
160    let bytes = wit.as_bytes();
161    let mut i = 0;
162    while i < prefixes.len() {
163        let prefix = prefixes[i].as_bytes();
164        if prefix.len() <= bytes.len() {
165            let mut j = 0;
166            let mut matches = true;
167            while j < prefix.len() {
168                if bytes[j] != prefix[j] {
169                    matches = false;
170                    break;
171                }
172                j += 1;
173            }
174            if matches {
175                return true;
176            }
177        }
178        i += 1;
179    }
180    false
181}
182
183/// True when `wit` — a raw `:contratos :wit` value — targets an
184/// HTTP-shaped WIT world (starts with any prefix in
185/// [`WIT_HTTP_SHAPE_PREFIXES`]). The single dispatch predicate every
186/// consumer routes L7-HTTP emission through, whether they carry a
187/// full [`WitContract`] on hand ([`WitContract::is_http`] delegates
188/// here) or only the raw `wit` string (the positive-sweep test's
189/// payload-dispatch helper, future renderers that classify off a
190/// bare `&str`). Lifting to a free function makes the shape-dispatch
191/// arm reachable without materializing a scratch [`WitContract`] at
192/// every classification point, and pins the six-prefix accept-set at
193/// one place so future additions (e.g. an `"https:"` peer of
194/// `"http:"`) reach every consumer by construction. Routes through
195/// the lifted [`wit_shape_matches`] combinator so the
196/// `PREFIXES.iter().any(|p| wit.starts_with(p))` scan lives at one
197/// canonical primitive, not one open-coded copy per peer arm.
198///
199/// Declared `pub const fn` — routes through the peer `pub const fn`
200/// [`wit_shape_matches`] combinator so every substrate-side
201/// `const`-context WIT-shape-arm-classifier consumer (the module-scope
202/// `const _: () = assert!(…)` canonical-accept-set + partition-witness
203/// pins immediately below, any future M4 admission-webhook
204/// `const fn` per-`:contratos :wit` HTTP-arm resolver over a raw &str)
205/// reaches through the same typed dispatch on the substrate primitive
206/// at const-eval time as at runtime.
207#[must_use]
208pub const fn wit_shape_is_http(wit: &str) -> bool {
209    wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES)
210}
211
212/// True when `wit` — a raw `:contratos :wit` value — targets a
213/// pub-sub-shaped WIT world (starts with any prefix in
214/// [`WIT_PUBSUB_SHAPE_PREFIXES`]). Peer of [`wit_shape_is_http`] /
215/// [`wit_shape_is_store`] on the shape-dispatch axis; see
216/// [`wit_shape_is_http`] for the lift rationale. Routes through the
217/// lifted [`wit_shape_matches`] combinator.
218///
219/// Declared `pub const fn` — sibling in `const`-eval posture to the
220/// peer [`wit_shape_is_http`] classifier; see that function's `const`
221/// posture-block for the full rationale.
222#[must_use]
223pub const fn wit_shape_is_pubsub(wit: &str) -> bool {
224    wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES)
225}
226
227/// True when `wit` — a raw `:contratos :wit` value — targets a
228/// key/value-store-shaped WIT world (starts with any prefix in
229/// [`WIT_STORE_SHAPE_PREFIXES`]). Peer of [`wit_shape_is_http`] /
230/// [`wit_shape_is_pubsub`] on the shape-dispatch axis; see
231/// [`wit_shape_is_http`] for the lift rationale. Routes through the
232/// lifted [`wit_shape_matches`] combinator.
233///
234/// Declared `pub const fn` — sibling in `const`-eval posture to the
235/// peer [`wit_shape_is_http`] / [`wit_shape_is_pubsub`] classifiers;
236/// see [`wit_shape_is_http`]'s `const` posture-block for the full
237/// rationale.
238#[must_use]
239pub const fn wit_shape_is_store(wit: &str) -> bool {
240    wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES)
241}
242
243/// True when `wit` — a raw `:contratos :wit` value — targets *none* of
244/// the three known payload-shape WIT worlds; the payload-less
245/// capability arm of the 4-way WIT-shape partition on the raw
246/// `:contratos :wit` axis. Peer of [`wit_shape_is_http`] /
247/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] on the shape-
248/// dispatch axis — closes the free-function classifier family the
249/// three payload-arm predicates opened onto the exact-inverse
250/// disjunction of the trio, so any downstream consumer that must
251/// classify a raw `:wit` `&str` onto the payload-less capability arm
252/// (a future substrate-side capability-shape-only emitter — the M4
253/// per-Aplicacao WIT-registry capability-import materializer, the
254/// future `feira app graph --capability` filter, the future per-
255/// cluster capability-scope reconciler that skips L4/L7 emission for
256/// payload-less edges, the future `mesh.pleme.io/v1alpha1/Aplicacao`
257/// CR admission webhook's per-shape histogram) reaches for exactly
258/// one typed dispatch at the substrate primitive rather than an
259/// open-coded per-consumer `!wit_shape_is_http(wit) &&
260/// !wit_shape_is_pubsub(wit) && !wit_shape_is_store(wit)` triplet
261/// negation — each of which would silently misclassify a future 4th
262/// payload-arm addition (a hypothetical `wasi:sockets/*` transport-
263/// layer shape, an `oci:*` capability-import carrier per the sibling
264/// [`wit_shape_matches`] docstring's trajectory bullet) as
265/// capability without a compile-time signal at the consumer site.
266///
267/// Fourth arm on the free-function WIT-shape-predicate family — closes
268/// the {[`wit_shape_is_http`], [`wit_shape_is_pubsub`],
269/// [`wit_shape_is_store`]} trio into a 4-way partition witness on the
270/// raw `:contratos :wit` `&str` axis, mirroring the paired sibling
271/// [`WitContract`]-surface [`WitContract::is_capability`] predicate and
272/// the post-projection [`WitTarget`]-side
273/// `gen_platform::IsVariant`-derived [`WitTarget::is_capability`]
274/// (7f6aa98 `IsVariant` derive lift on the peer arm-set). Every
275/// [`WitTarget`] variant now carries a matched peer predicate on both
276/// the raw `&str` axis (this function + [`wit_shape_is_http`] /
277/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`]) and the
278/// [`WitContract`] surface (the sibling 4-arm predicate family
279/// [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
280/// [`WitContract::is_store`] / [`WitContract::is_capability`]),
281/// pinned in load-bearing by the sibling
282/// [`tests::wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis`]
283/// partition-witness pin and the peer
284/// [`tests::wit_contract_shape_methods_delegate_to_free_functions`]
285/// delegation pin.
286///
287/// Prior to this lift the "not one of the three known payload shapes"
288/// classification only reached the raw `&str` axis by materializing a
289/// scratch [`WitContract`] and delegating through
290/// [`WitContract::is_capability`] — a five-field constructor at every
291/// classification point for a pure `&str → bool` question, and a
292/// dependency on the payload-carrier scalar layout the classifier
293/// does not read. Same "one canonical combinator, thin per-arm
294/// projections" discipline the peer [`wit_shape_is_http`] /
295/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] trio already
296/// established, extended to close the 4-arm partition on the raw
297/// `&str` axis.
298///
299/// Note: purely syntactic classification on the negated `:wit` prefix-
300/// set — unlike [`WitContract::target`], which additionally rejects
301/// value-shape-invalid `:wit` strings (uppercase, hyphen-for-colon
302/// typo, empty package) via [`crate::render::is_wit_world_ref`] and
303/// payload-shape mismatches. An empty or structurally malformed `wit`
304/// string returns `true` here (the prefix set matches nothing), and
305/// the surrounding validate-side gate cascade is where the
306/// [`AplicacaoError::EmptyWit`] / [`AplicacaoError::ContratoWitInvalid`]
307/// diagnostic surfaces — this function is the classifier, not the
308/// validator.
309///
310/// Declared `pub const fn` — closes the 4-arm classifier family's
311/// `const`-eval-surface pass on the payload-less capability arm,
312/// peer of the sibling `pub const fn` [`wit_shape_is_http`] /
313/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] classifiers, so
314/// the raw `&str → bool` WIT-shape partition on the capability arm
315/// reaches every substrate-side `const`-context consumer through one
316/// typed dispatch. See [`wit_shape_is_http`]'s `const` posture-block
317/// for the full rationale.
318#[must_use]
319pub const fn wit_shape_is_capability(wit: &str) -> bool {
320    !wit_shape_is_http(wit) && !wit_shape_is_pubsub(wit) && !wit_shape_is_store(wit)
321}
322
323// Compile-time pins on the 4-arm WIT-shape classifier family — the
324// module-scope const-eval assertions below trip at caixa-core build
325// time (not test time) if a future edit rewires any of the four
326// classifier's arm-set away from the accept-set MESH-COMPOSITION §II.3
327// pins. Anchor the `const`-eval-surface posture of the four peer
328// classifiers on canonical accept-set samples (one per WIT_*_SHAPE_PREFIXES
329// prefix) plus pairwise-exclusion samples asserting the trio partitions
330// the payload-carrying arm-set and the capability arm carries the
331// complementary payload-less remainder. Any future accidental downgrade
332// of one classifier to non-`const` fails these items at caixa-core build
333// time; any future prefix-set edit that overlaps two arms (e.g. a `kv:`
334// prefix accidentally re-emitted under `WIT_HTTP_SHAPE_PREFIXES`) trips
335// the corresponding partition-witness item. Peer of the sibling M3
336// [`PlacementStrategy::requires_shard_key`] partition pins at
337// aplicacao.rs:5121-5123 on the sibling closed-set typed-enum
338// discriminator axis.
339const _: () = assert!(wit_shape_is_http("wasi:http/proxy"));
340const _: () = assert!(wit_shape_is_http("http:incoming"));
341const _: () = assert!(wit_shape_is_pubsub("nats:events"));
342const _: () = assert!(wit_shape_is_pubsub("kafka:topic"));
343const _: () = assert!(wit_shape_is_store("wasi:keyvalue/store"));
344const _: () = assert!(wit_shape_is_store("kv:cache"));
345const _: () = assert!(wit_shape_is_capability("wasi:filesystem/preopens"));
346const _: () = assert!(wit_shape_is_capability(""));
347// Pairwise-exclusion pins — the three payload-carrying arms are
348// pairwise disjoint on the canonical accept-set samples, and the
349// capability arm is the exact-inverse disjunction of the trio
350// (the free-function classifier family's 4-way partition witness).
351const _: () = assert!(!wit_shape_is_http("nats:events"));
352const _: () = assert!(!wit_shape_is_http("kv:cache"));
353const _: () = assert!(!wit_shape_is_pubsub("wasi:http/proxy"));
354const _: () = assert!(!wit_shape_is_pubsub("wasi:keyvalue/store"));
355const _: () = assert!(!wit_shape_is_store("wasi:http/proxy"));
356const _: () = assert!(!wit_shape_is_store("nats:events"));
357const _: () = assert!(!wit_shape_is_capability("wasi:http/proxy"));
358const _: () = assert!(!wit_shape_is_capability("nats:events"));
359const _: () = assert!(!wit_shape_is_capability("wasi:keyvalue/store"));
360
361impl WitContract {
362    /// Substrate-canonical per-`:contratos` caller-Servico scalar
363    /// accessor every consumer that reads the edge's source endpoint
364    /// keys off — returns the author-declared `:contratos :de`
365    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
366    /// own [`String`] storage.
367    ///
368    /// The `:contratos :de` slot names the caller-side member Servico
369    /// on a typed inter-Servico edge (validated by
370    /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
371    /// Aplicacao declares — a stray `:de` that doesn't name a member is
372    /// [`AplicacaoError::ContratoMemberMissing`], not a silent
373    /// caller-attachment miss at cluster-apply time). Peer of the
374    /// sibling [`WitContract::destination`] accessor on the same
375    /// per-`:contratos` entry — the pair `( source(), destination() )`
376    /// jointly names the typed edge every renderer that fans on the
377    /// caller-callee identity keys off (the
378    /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)`
379    /// grouping, the [`AplicacaoSpec::detect_sync_cycles`] adjacency
380    /// map, the per-edge dedup key, the per-edge membership-lookup
381    /// diagnostic).
382    ///
383    /// Prior to this lift the `.de` byte-string was accessed inline at
384    /// four caixa-core sites (the two validate-side membership lookups
385    /// at `!names.contains(c.de.as_str())`, the per-edge dedup-key
386    /// tuple's caller-arm at
387    /// `(c.de.as_str(), c.para.as_str(), c.wit.as_str(), ...)`, the
388    /// `detect_sync_cycles` adjacency `adj.entry(c.de.as_str())`) and
389    /// one caixa-mesh site (the per-`(:de, :para)` CNP grouping's
390    /// caller-arm at `groups.entry((c.de.as_str(), c.para.as_str()))`)
391    /// — five open-coded `.de.as_str()` field-accesses that expressed
392    /// no compile-time link back to the typed slot. A future extension
393    /// of the `:contratos :de` axis to a richer author surface (a
394    /// multi-caller weighted-fan-in overlay per MESH-COMPOSITION §III.2
395    /// canary flow, a per-cluster caller-alias table the operator pins
396    /// through a future `:placement`-scoped slot, the M4
397    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
398    /// admission-webhook that promotes the scalar to a caller-set
399    /// projection) would have had to be threaded through every
400    /// open-coded copy in lockstep or one consumer would silently
401    /// disagree with the peers on which caller Servico a given edge
402    /// resolves to. Lifting the resolution rule to a typed method on
403    /// the substrate primitive means every downstream caller-facing
404    /// consumer reaches for one typed dispatch — the resolver's
405    /// accept-set migrates as a unit on any future axis addition.
406    ///
407    /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
408    /// (6db982c) accessor on the analogous per-ingress-Servico scalar
409    /// axis — same "one typed dispatch on the substrate primitive,
410    /// thin projections at each consumer" discipline extended onto the
411    /// per-`:contratos` caller-Servico byte-string axis.
412    ///
413    /// Declared `pub const fn` — the body composes exclusively through
414    /// the `pub const fn` [`String::as_str`] projection (const-stable
415    /// since Rust 1.87, well within the workspace MSRV), so every
416    /// downstream `const`-context consumer of the per-`:contratos`
417    /// caller-Servico byte-string reaches through the same substrate-
418    /// primitive dispatch at const-eval time as at runtime. Peer of
419    /// the sibling `pub const fn` [`Self::destination`] /
420    /// [`Self::world_ref`] scalar accessors on the same
421    /// per-`:contratos` byte-string trio (the family closure the
422    /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
423    /// locks load-bearing), and mirror on the method-surface of the
424    /// sibling free-function [`wit_shape_matches`] +
425    /// [`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
426    /// [`wit_shape_is_store`] / [`wit_shape_is_capability`] `const`-
427    /// eval-surface pass (d46420c) on the raw `&str → bool` WIT-shape
428    /// dispatch family.
429    #[must_use]
430    pub const fn source(&self) -> &str {
431        self.de.as_str()
432    }
433
434    /// Substrate-canonical per-`:contratos` callee-Servico scalar
435    /// accessor every consumer that reads the edge's destination
436    /// endpoint keys off — returns the author-declared
437    /// `:contratos :para` byte-string verbatim as a `&str`, borrowed
438    /// from the typed slot's own [`String`] storage.
439    ///
440    /// The `:contratos :para` slot names the callee-side member Servico
441    /// on a typed inter-Servico edge (validated by
442    /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
443    /// Aplicacao declares — a stray `:para` that doesn't name a member
444    /// is [`AplicacaoError::ContratoMemberMissing`], not a silent
445    /// callee-attachment miss at cluster-apply time). Callee-side twin
446    /// of the sibling [`WitContract::source`] accessor — the pair
447    /// jointly names the typed edge every renderer that fans on the
448    /// caller-callee identity keys off, and this accessor is also the
449    /// per-`(:de, :para)` L4 port resolver's canonical destination arg:
450    /// under today's typed surface [`AplicacaoSpec::port_for_destination`]
451    /// composes with `destination()` at every emit site that projects a
452    /// per-edge destination Servico's L4 listener port.
453    ///
454    /// Prior to this lift the `.para` byte-string was accessed inline
455    /// at five sites — four caixa-core (the validate-side membership
456    /// lookup at `!names.contains(c.para.as_str())`, the per-edge
457    /// dedup-key tuple's callee-arm, the `detect_sync_cycles`
458    /// adjacency `.insert(c.para.as_str())`, the CNP grouping's
459    /// callee-arm) and one caixa-mesh (the per-`(:de, :para)` CNP L4
460    /// port resolver's destination arg `spec.port_for_destination(&c.para)`)
461    /// — with no compile-time link back to the typed slot. A future
462    /// extension of the `:contratos :para` axis to a richer author
463    /// surface (a multi-callee weighted-fan-out overlay for canary /
464    /// blue-green routing on typed edges, a per-cluster callee-alias
465    /// table the operator pins through a future `:placement`-scoped
466    /// slot, the M4 CR materializer's per-CR admission-webhook that
467    /// promotes the scalar to a callee-set projection) would have had
468    /// to be threaded through every open-coded copy in lockstep or one
469    /// consumer would silently disagree on which callee Servico a given
470    /// edge resolves to (a per-CNP `endpointSelector` that names a
471    /// different destination than its L4 port resolver reads for, a
472    /// dedup-key that treats `(cart, catalog-v2)` and `(cart, catalog)`
473    /// as distinct while the adjacency map collapses them, or vice
474    /// versa). Lifting to a typed method on the substrate primitive
475    /// means every downstream callee-facing consumer reaches for one
476    /// typed dispatch.
477    ///
478    /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
479    /// (6db982c) accessor — both name the "destination-Servico
480    /// byte-string" concept on their respective mesh-slot atoms (per-
481    /// ingress apex vs. per-typed-edge callee), and both extend the
482    /// substrate-primitive-owns-the-resolver discipline onto the
483    /// per-slot destination-Servico scalar axis. Composes with
484    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) at every
485    /// emit-side per-edge L4 port reader — the composition
486    /// `spec.port_for_destination(c.destination())` pins the CNP per-
487    /// `(:de, :para)` L4 port axis to the same typed dispatch the peer
488    /// `HTTPRoute` `backendRefs[0].port` axis reaches through with
489    /// `spec.port_for_destination(entrada.destination())`.
490    ///
491    /// Declared `pub const fn` — sibling in `const`-eval posture to the
492    /// peer `pub const fn` [`Self::source`] / [`Self::world_ref`]
493    /// per-`:contratos` byte-string scalar accessors, all three
494    /// projecting through the `pub const fn` [`String::as_str`]
495    /// (const-stable since Rust 1.87). See [`Self::source`] for the
496    /// family-closure rationale.
497    #[must_use]
498    pub const fn destination(&self) -> &str {
499        self.para.as_str()
500    }
501
502    /// Substrate-canonical per-`:contratos` WIT-world-reference scalar
503    /// accessor every consumer that reads the edge's WIT world
504    /// discriminator keys off — returns the author-declared
505    /// `:contratos :wit` byte-string verbatim as a `&str`, borrowed from
506    /// the typed slot's own [`String`] storage.
507    ///
508    /// The `:contratos :wit` slot names the WIT world the typed edge
509    /// carries (e.g. `"wasi:http/proxy"`, `"nats:pub-sub"`,
510    /// `"wasi:keyvalue/store"`); validated by [`WitContract::target`] to
511    /// be a well-shaped WIT world reference via
512    /// [`crate::render::is_wit_world_ref`] and by
513    /// [`AplicacaoSpec::validate`] to be non-empty via the narrower
514    /// [`AplicacaoError::EmptyWit`] variant. Peer of the sibling
515    /// [`WitContract::source`] / [`WitContract::destination`] accessors
516    /// on the same per-`:contratos` entry — the triple
517    /// `( source(), destination(), world_ref() )` jointly names the
518    /// typed edge every renderer that fans on the caller-callee-shape
519    /// identity keys off (the per-edge dedup key at
520    /// [`AplicacaoSpec::validate`]'s duplicate-`:contratos` gate, the
521    /// per-`(:de, :para)` CNP grouping's shape-arm classifier at
522    /// [`caixa_mesh::cilium_network_policies`], the
523    /// [`WitContract::is_http`] / [`is_pubsub`][WitContract::is_pubsub]
524    /// / [`is_store`][WitContract::is_store] shape-dispatch predicates,
525    /// the [`feira app graph`][fag] per-edge printer's WIT-shape label).
526    ///
527    /// Prior to this lift the `.wit` byte-string was accessed inline at
528    /// five sites — three caixa-core (the `WitContract::is_*` shape-
529    /// dispatch predicates' `&self.wit` arg, the validate-side empty
530    /// check at `if c.wit.is_empty()`, the per-edge dedup-key tuple's
531    /// shape arm at `c.wit.as_str()`) and one caixa-feira (the app-graph
532    /// printer's `{}` format-slot at `c.wit`) — five open-coded
533    /// `.wit` field-accesses that expressed no compile-time link back to
534    /// the typed slot. A future extension of the `:contratos :wit` axis
535    /// to a richer author surface (an M4 promotion from `String` to a
536    /// typed WIT-world enum once the WIT registry stabilizes in tatara-
537    /// lisp per this struct's own `:wit` field docstring, a per-cluster
538    /// WIT-alias table the operator pins through a future
539    /// `:placement`-scoped slot, a canonicalization pass that lowercases
540    /// `wasi:*` prefixes) would have had to be threaded through every
541    /// open-coded copy in lockstep or one consumer would silently
542    /// disagree with the peers on which WIT shape a given edge resolves
543    /// to (a per-CNP L7 emission that read `wasi:http/proxy` while the
544    /// dedup key read the pre-canonicalized `WASI:HTTP/proxy`, an
545    /// empty-check that missed a whitespace-only string a peer accessor
546    /// stripped, or vice versa). Lifting to a typed method on the
547    /// substrate primitive means every downstream WIT-shape-facing
548    /// consumer reaches for one typed dispatch — the resolver's
549    /// accept-set migrates as a unit on any future axis addition.
550    ///
551    /// Sibling of the peer per-`:contratos` [`WitContract::source`] /
552    /// [`WitContract::destination`] (7f0fd43), per-`:entrada`
553    /// [`Entrada::hostname`] / [`Entrada::destination`] (11f3dfe /
554    /// 6db982c), per-`:membros` [`Membro::nome`] /
555    /// [`Membro::versao_requirement`] (4a32abf / a40b0e3) accessors on
556    /// the mesh-slot-atom scalar-value axes — same "one typed dispatch
557    /// on the substrate primitive, thin projections at each consumer"
558    /// discipline extended onto the last unlifted per-`:contratos`
559    /// scalar (the WIT-world-reference arm).
560    ///
561    /// [fag]: caixa-feira/src/cmd/app.rs
562    ///
563    /// Declared `pub const fn` — sibling in `const`-eval posture to the
564    /// peer `pub const fn` [`Self::source`] / [`Self::destination`]
565    /// per-`:contratos` byte-string scalar accessors on the trio, and
566    /// the load-bearing enabler for the paired `pub const fn`
567    /// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] /
568    /// [`Self::is_capability`] WIT-shape-predicate family (each
569    /// composes as `wit_shape_is_<arm>(self.world_ref())` and inherits
570    /// the `const`-eval posture by construction once this accessor
571    /// carries it). See [`Self::source`] for the family-closure
572    /// rationale and the paired
573    /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
574    /// for the load-bearing witness.
575    #[must_use]
576    pub const fn world_ref(&self) -> &str {
577        self.wit.as_str()
578    }
579
580    /// Substrate-canonical per-`:contratos` `:endpoint` HTTP-shaped
581    /// payload-target scalar accessor every consumer that reads the
582    /// edge's L7 HTTP request path payload keys off — returns the
583    /// author-declared `:contratos :endpoint` byte-string verbatim as
584    /// an `Option<&str>`, borrowed from the typed slot's own
585    /// `Option<String>` storage; `None` when the slot is absent (the
586    /// canonical shape of a non-HTTP-`:wit`-world edge — pub-sub
587    /// `nats:*`/`kafka:*` carries `:subject` instead, key/value
588    /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
589    /// [`WitTarget::Capability`] edge carries none of the three).
590    ///
591    /// The `:contratos :endpoint` slot carries the HTTP request path
592    /// payload (Cilium L7 `path:` + Gateway API v1 `PathPrefix` grammar
593    /// — same shape required of `:entrada :paths`, gated by the shared
594    /// [`crate::render::is_gateway_api_http_path`] predicate) that
595    /// [`WitContract::target`] projects onto the [`WitTarget::Http`]
596    /// arm's `endpoint: &'a str` payload when the edge's `:wit` world
597    /// matches the [`WIT_HTTP_SHAPE_PREFIXES`] accept-set. Every
598    /// downstream consumer that reads the payload keys off this scalar
599    /// (the [`WitContract::target`] Http-arm payload extraction that
600    /// materializes [`WitTarget::Http { endpoint }`] under the paired
601    /// [`WitTarget::HTTP_FIELD_NAME`] label, the
602    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
603    /// key's endpoint arm that pins the payload as part of the six-tuple
604    /// dedup key alongside the sibling `:subject`/`:slot` arms, the
605    /// future M4 per-edge WIT registry resolver's HTTP-arm materializer,
606    /// the future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
607    /// per-edge L7 admission webhook, the future caixa-mesh L7 CNP
608    /// emission path that lands the payload verbatim as a Cilium L7
609    /// `path:` rule).
610    ///
611    /// Prior to this lift the `.endpoint` field was accessed inline at
612    /// two production sites in `caixa-core/src/aplicacao.rs` — the
613    /// [`WitContract::target`] payload-shape dispatch's `let endpoint =
614    /// self.endpoint.as_deref();` binding at the top of the method, and
615    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
616    /// tuple's `c.endpoint.as_deref()` HTTP-arm slot — two open-coded
617    /// field-accesses that expressed no compile-time link back to the
618    /// typed slot. A future extension of the `:contratos :endpoint`
619    /// axis to a richer author surface (an M4 promotion from
620    /// `Option<String>` to a typed HTTP path-template enum once the
621    /// WIT registry stabilizes path-parameter shapes in tatara-lisp per
622    /// this struct's own `:wit` field docstring, a per-cluster endpoint-
623    /// alias table the operator pins through a future `:placement`-
624    /// scoped slot, a canonicalization pass that percent-encodes non-
625    /// ASCII path segments, a per-CR fully-qualified rewrite the M4 CR
626    /// materializer applies per-tenant) would have had to be threaded
627    /// through both open-coded copies in lockstep or the two consumers
628    /// would silently disagree on which HTTP path a given edge resolves
629    /// to — the [`WitContract::target`] payload-extraction reading
630    /// `"/lookup"` while the [`AplicacaoSpec::validate`] dedup key read
631    /// the operator-resolved `"/tenant-a/lookup"` would silently split
632    /// the [`WitTarget::Http`]-arm rendered payload from the actual
633    /// dedup-key uniqueness axis, a two-consumer split at the validator
634    /// far from the source `caixa.lisp` with no field naming the
635    /// payload-drift root cause. Lifting the resolution rule to a typed
636    /// method on the substrate primitive means every downstream
637    /// HTTP-payload-facing consumer of the Aplicacao's per-`:contratos`
638    /// L7-payload surface reaches for exactly one typed dispatch — the
639    /// resolver's accept-set migrates as a unit on any future axis
640    /// addition.
641    ///
642    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
643    /// (7cd2a28) / [`Placement::affinity`] (74ec2d3) `Option<&str>`
644    /// accessors on the M3 mesh-slot family — same "one typed dispatch
645    /// on the substrate primitive, thin projections at each consumer"
646    /// discipline extended onto the per-`:contratos` HTTP-shaped
647    /// payload-carrier `Option<String>` optional-scalar axis. First
648    /// `Option<&str>`-return accessor on the per-`:contratos` mesh-slot
649    /// atom — opens the "optional per-slot payload-carrier scalar"
650    /// projection pattern the sibling per-`:contratos` `:subject` /
651    /// `:slot` future lifts fold on, matching the closed
652    /// per-`:contratos` scalar-value accessor family
653    /// ([`WitContract::source`] / [`WitContract::destination`] /
654    /// [`WitContract::world_ref`]) already lifted onto the mandatory-
655    /// scalar `String` axes. Named `endpoint()` to match the storage
656    /// field's name and the paired [`WitTarget::HTTP_FIELD_NAME`]
657    /// author-facing label const; the accessor's identity name maps
658    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
659    /// docstring already carries.
660    #[must_use]
661    pub const fn endpoint(&self) -> Option<&str> {
662        match &self.endpoint {
663            Some(s) => Some(s.as_str()),
664            None => None,
665        }
666    }
667
668    /// Substrate-canonical per-`:contratos` `:subject` pub-sub-shaped
669    /// payload-target scalar accessor every consumer that reads the
670    /// edge's NATS / Kafka publish subject payload keys off — returns
671    /// the author-declared `:contratos :subject` byte-string verbatim
672    /// as an `Option<&str>`, borrowed from the typed slot's own
673    /// `Option<String>` storage; `None` when the slot is absent (the
674    /// canonical shape of a non-pub-sub-`:wit`-world edge — HTTP
675    /// `wasi:http/*`/`http:*` carries `:endpoint` instead, key/value
676    /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
677    /// [`WitTarget::Capability`] edge carries none of the three).
678    ///
679    /// The `:contratos :subject` slot carries the NATS / Kafka publish
680    /// subject payload (the [`WIT_PUBSUB_SHAPE_PREFIXES`] dispatch arm's
681    /// per-edge target selector — `orders.paid`, `events.>`, whatever
682    /// subject namespace the author names on the pub-sub edge) that
683    /// [`WitContract::target`] projects onto the [`WitTarget::PubSub`]
684    /// arm's `subject: &'a str` payload when the edge's `:wit` world
685    /// matches the [`WIT_PUBSUB_SHAPE_PREFIXES`] accept-set. Every
686    /// downstream consumer that reads the payload keys off this scalar
687    /// (the [`WitContract::target`] PubSub-arm payload extraction that
688    /// materializes [`WitTarget::PubSub { subject }`] under the paired
689    /// [`WitTarget::PUBSUB_FIELD_NAME`] label, the
690    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
691    /// key's subject arm that pins the payload as part of the six-tuple
692    /// dedup key alongside the sibling `:endpoint`/`:slot` arms, the
693    /// future M4 per-edge WIT registry resolver's pub-sub-arm
694    /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
695    /// materializer's per-edge NATS admission webhook, the future
696    /// caixa-mesh L4 CNP emission path that lands the payload verbatim
697    /// as a NATS subject the operator pins per-CR).
698    ///
699    /// Prior to this lift the `.subject` field was accessed inline at
700    /// two production sites in `caixa-core/src/aplicacao.rs` — the
701    /// [`WitContract::target`] payload-shape dispatch's `let subject =
702    /// self.subject.as_deref();` binding at the top of the method, and
703    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
704    /// tuple's `c.subject.as_deref()` pub-sub-arm slot — two open-coded
705    /// field-accesses that expressed no compile-time link back to the
706    /// typed slot. A future extension of the `:contratos :subject` axis
707    /// to a richer author surface (an M4 promotion from `Option<String>`
708    /// to a typed NATS-subject-template enum once the WIT registry
709    /// stabilizes wildcard / hierarchy shapes in tatara-lisp per this
710    /// struct's own `:wit` field docstring, a per-cluster subject-alias
711    /// table the operator pins through a future `:placement`-scoped
712    /// slot, a canonicalization pass that lowercases / dedupes wildcard
713    /// segments, a per-CR fully-qualified rewrite the M4 CR materializer
714    /// applies per-tenant) would have had to be threaded through both
715    /// open-coded copies in lockstep or the two consumers would silently
716    /// disagree on which NATS subject a given edge resolves to — the
717    /// [`WitContract::target`] payload-extraction reading `"orders.paid"`
718    /// while the [`AplicacaoSpec::validate`] dedup key read the operator-
719    /// resolved `"tenant-a.orders.paid"` would silently split the
720    /// [`WitTarget::PubSub`]-arm rendered payload from the actual dedup-
721    /// key uniqueness axis, a two-consumer split at the validator far
722    /// from the source `caixa.lisp` with no field naming the payload-
723    /// drift root cause. Lifting the resolution rule to a typed method
724    /// on the substrate primitive means every downstream pub-sub-payload-
725    /// facing consumer of the Aplicacao's per-`:contratos` L4-payload
726    /// surface reaches for exactly one typed dispatch — the resolver's
727    /// accept-set migrates as a unit on any future axis addition.
728    ///
729    /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
730    /// (7020470) `Option<&str>` accessor on the M3 mesh-slot payload-
731    /// carrier axis — second `Option<&str>`-return accessor on the
732    /// per-`:contratos` mesh-slot atom, extending the "optional per-slot
733    /// payload-carrier scalar" projection pattern the [`WitContract::endpoint`]
734    /// HTTP-arm lift opened onto the pub-sub arm; leaves the [`WitContract::slot`]
735    /// key/value-store arm as the last unlifted per-`:contratos`
736    /// `Option<String>` axis. Named `subject()` to match the storage
737    /// field's name and the paired [`WitTarget::PUBSUB_FIELD_NAME`]
738    /// author-facing label const; the accessor's identity name maps
739    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
740    /// docstring already carries.
741    #[must_use]
742    pub const fn subject(&self) -> Option<&str> {
743        match &self.subject {
744            Some(s) => Some(s.as_str()),
745            None => None,
746        }
747    }
748
749    /// Substrate-canonical per-`:contratos` `:slot` key/value-store-
750    /// shaped payload-target scalar accessor every consumer that reads
751    /// the edge's `wasi:keyvalue/*` / `kv:*` key-template payload keys
752    /// off — returns the author-declared `:contratos :slot` byte-string
753    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
754    /// own `Option<String>` storage; `None` when the slot is absent
755    /// (the canonical shape of a non-store-`:wit`-world edge — HTTP
756    /// `wasi:http/*`/`http:*` carries `:endpoint` instead, pub-sub
757    /// `nats:*`/`kafka:*` carries `:subject` instead, and a plain
758    /// [`WitTarget::Capability`] edge carries none of the three).
759    ///
760    /// The `:contratos :slot` slot carries the key/value store
761    /// key-template payload (the [`WIT_STORE_SHAPE_PREFIXES`] dispatch
762    /// arm's per-edge target selector — `carts/{cart_id}`,
763    /// `sessions/{tenant}/{sid}`, whatever key-template the author
764    /// names on the store edge) that [`WitContract::target`] projects
765    /// onto the [`WitTarget::Store`] arm's `slot: &'a str` payload when
766    /// the edge's `:wit` world matches the [`WIT_STORE_SHAPE_PREFIXES`]
767    /// accept-set. Every downstream consumer that reads the payload
768    /// keys off this scalar (the [`WitContract::target`] Store-arm
769    /// payload extraction that materializes [`WitTarget::Store { slot }`]
770    /// under the paired [`WitTarget::STORE_FIELD_NAME`] label, the
771    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
772    /// key's store arm that pins the payload as part of the six-tuple
773    /// dedup key alongside the sibling `:endpoint`/`:subject` arms,
774    /// the future M4 per-edge WIT registry resolver's store-arm
775    /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
776    /// materializer's per-edge key/value admission webhook, the future
777    /// caixa-mesh L4 CNP emission path that lands the payload verbatim
778    /// as a key-template the operator pins per-CR).
779    ///
780    /// Prior to this lift the `.slot` field was accessed inline at two
781    /// production sites in `caixa-core/src/aplicacao.rs` — the
782    /// [`WitContract::target`] payload-shape dispatch's `let slot =
783    /// self.slot.as_deref();` binding at the top of the method, and
784    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
785    /// tuple's `c.slot.as_deref()` store-arm slot — two open-coded
786    /// field-accesses that expressed no compile-time link back to the
787    /// typed slot. A future extension of the `:contratos :slot` axis
788    /// to a richer author surface (an M4 promotion from `Option<String>`
789    /// to a typed key-template enum once the WIT registry stabilizes
790    /// key-template parameter shapes in tatara-lisp per this struct's
791    /// own `:wit` field docstring, a per-cluster slot-alias table the
792    /// operator pins through a future `:placement`-scoped slot, a
793    /// canonicalization pass that lowercases the bucket prefix, a
794    /// per-CR fully-qualified rewrite the M4 CR materializer applies
795    /// per-tenant) would have had to be threaded through both
796    /// open-coded copies in lockstep or the two consumers would
797    /// silently disagree on which key-template a given edge resolves
798    /// to — the [`WitContract::target`] payload-extraction reading
799    /// `"carts/{cart_id}"` while the [`AplicacaoSpec::validate`] dedup
800    /// key read the operator-resolved `"tenant-a/carts/{cart_id}"`
801    /// would silently split the [`WitTarget::Store`]-arm rendered
802    /// payload from the actual dedup-key uniqueness axis, a
803    /// two-consumer split at the validator far from the source
804    /// `caixa.lisp` with no field naming the payload-drift root cause.
805    /// Lifting the resolution rule to a typed method on the substrate
806    /// primitive means every downstream store-payload-facing consumer
807    /// of the Aplicacao's per-`:contratos` payload surface reaches for
808    /// exactly one typed dispatch — the resolver's accept-set migrates
809    /// as a unit on any future axis addition.
810    ///
811    /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
812    /// (7020470) / [`WitContract::subject`] (90de675) `Option<&str>`
813    /// accessors on the M3 mesh-slot payload-carrier axis — third and
814    /// final `Option<&str>`-return accessor on the per-`:contratos`
815    /// mesh-slot atom, closes the last unlifted per-`:contratos`
816    /// `Option<String>` axis and completes the "optional per-slot
817    /// payload-carrier scalar" projection pattern the peer HTTP /
818    /// pub-sub arms established across the three payload-shape
819    /// dispatch arms. Named `slot()` to match the storage field's
820    /// name and the paired [`WitTarget::STORE_FIELD_NAME`]
821    /// author-facing label const; the accessor's identity name maps
822    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
823    /// docstring already carries.
824    #[must_use]
825    pub const fn slot(&self) -> Option<&str> {
826        match &self.slot {
827            Some(s) => Some(s.as_str()),
828            None => None,
829        }
830    }
831
832    /// Substrate-canonical per-`:contratos` `(caller, callee)` owned-form
833    /// caller-callee-pair accessor every consumer that constructs an
834    /// [`AplicacaoError`] variant carrying the per-edge `(de, para)`
835    /// caller-callee pair keys off — returns the author-declared
836    /// `:contratos :de` / `:contratos :para` byte-strings verbatim as an
837    /// owned `(String, String)` tuple, projected through the lifted
838    /// [`WitContract::source`] / [`WitContract::destination`] scalar
839    /// accessors so any future rebrand on the caller-arm / callee-arm
840    /// projection axis (an M4 per-cluster caller-alias table the
841    /// operator pins through a future `:placement`-scoped slot, a
842    /// namespace-qualified rewrite the M4 CR materializer applies per-CR,
843    /// a per-`:membros` alias overlay from the future `:membros
844    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
845    /// acknowledges) reaches every diagnostic-construction site by
846    /// construction.
847    ///
848    /// The `(de, para)` pair is the "typed-edge caller-callee identity in
849    /// owned form" primitive every per-`:contratos` diagnostic variant on
850    /// [`AplicacaoError`] carries alongside its payload-shape arm — the
851    /// nine variants [`AplicacaoError::EmptyWit`],
852    /// [`AplicacaoError::ContratoEndpointEmpty`],
853    /// [`AplicacaoError::ContratoEndpointNotAbsolute`],
854    /// [`AplicacaoError::ContratoEndpointInvalid`],
855    /// [`AplicacaoError::ContratoSubjectEmpty`],
856    /// [`AplicacaoError::ContratoSubjectInvalid`],
857    /// [`AplicacaoError::ContratoSlotEmpty`],
858    /// [`AplicacaoError::ContratoSlotInvalid`], and
859    /// [`AplicacaoError::ContratoDuplicate`] each carry a `de: String,
860    /// para: String` field pair the constructor site reads verbatim off
861    /// the [`WitContract`] the diagnostic points at, so a diagnostic
862    /// whose `de:` and `para:` labels silently drift off the source
863    /// caller/callee — a per-cluster caller-alias rewrite that landed on
864    /// one variant's inline `de: c.de.clone()` field access but not on
865    /// its sibling variant's, an accidental swap of the `de:` and `para:`
866    /// arms in a copy-paste of the constructor block — would emit a
867    /// build-time error whose "which caixa is at fault" question the
868    /// operator answers wrongly, far from the source `caixa.lisp`.
869    ///
870    /// Prior to this lift the `(self.de.clone(), self.para.clone())`
871    /// pair was inlined at seven [`WitContract::target`] error-
872    /// construction sites (the [`AplicacaoError::ContratoEndpointEmpty`]
873    /// / [`AplicacaoError::ContratoEndpointNotAbsolute`] /
874    /// [`AplicacaoError::ContratoEndpointInvalid`] HTTP-arm variants,
875    /// the [`AplicacaoError::ContratoSubjectEmpty`] /
876    /// [`AplicacaoError::ContratoSubjectInvalid`] pub-sub-arm variants,
877    /// the [`AplicacaoError::ContratoSlotEmpty`] /
878    /// [`AplicacaoError::ContratoSlotInvalid`] store-arm variants) and
879    /// two [`AplicacaoSpec::validate`] error-construction sites (the
880    /// [`AplicacaoError::EmptyWit`] empty-`:wit` gate, the
881    /// [`AplicacaoError::ContratoDuplicate`] duplicate-`:contratos`
882    /// insert-first-seen closure) — nine open-coded `.de.clone() +
883    /// .para.clone()` pairs that expressed no compile-time contract that
884    /// the caller-arm and callee-arm arms of the same diagnostic
885    /// construction reach for the same [`WitContract`] instance or that
886    /// the `de:` and `para:` label pair binds to the fields the author
887    /// declared. Any future rebrand on the axis — an M4 per-cluster
888    /// caller/callee-alias rewrite the operator pins through a future
889    /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
890    /// per-CR fully-qualified namespace prefix the M4
891    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
892    /// per-tenant, a canonicalization pass that lowercases the caller +
893    /// callee identifiers post-parse — would have had to be threaded
894    /// through every open-coded copy in lockstep or one variant's
895    /// diagnostic would silently name a different caller/callee pair
896    /// than its peer, silently degrading the "which caixa is at fault"
897    /// self-locating signal every operator-facing typed diagnostic
898    /// exists to carry. Lifting the pair to a typed method on the
899    /// substrate primitive means every downstream diagnostic-construction
900    /// site reaches for exactly one typed dispatch — the resolver's
901    /// projection migrates as a unit on any future axis addition.
902    ///
903    /// Peer of the sibling per-`:contratos` scalar accessor family
904    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43)
905    /// / [`WitContract::world_ref`] (6226bf4) on the mesh-slot-atom
906    /// scalar-value axes — first composite-projection accessor on the
907    /// per-`:contratos` mesh-slot atom, folds the two open-coded owned-
908    /// form `.clone()` field-accesses that pair the sibling
909    /// caller/callee accessors' `&str`-return borrowed-form outputs onto
910    /// one typed dispatch. Named `edge_pair()` to reflect the identity
911    /// name of the projected tuple (the typed-edge caller-callee pair,
912    /// distinct from the sibling triple-projection
913    /// [`WitContract::edge_triple`] accessor that folds the local `edge`
914    /// closure in [`WitContract::target`] + the paired
915    /// [`AplicacaoError::ContratoDuplicate`] diagnostic constructor
916    /// site's `(de, para, wit)` triple onto one typed dispatch).
917    #[must_use]
918    pub fn edge_pair(&self) -> (String, String) {
919        (self.source().to_string(), self.destination().to_string())
920    }
921
922    /// Owned form of the `(:contratos :de, :contratos :para, :contratos
923    /// :wit)` triple every per-edge diagnostic constructor that names
924    /// all three axes threads verbatim into its `de:` / `para:` /
925    /// `wit:` fields — the [`WitTarget::target`] dispatch's wrong-target
926    /// / missing-target / invalid-wit / capability-with-payload arms
927    /// (eight sites all shape `let (de, para, wit) = edge();
928    /// AplicacaoError::Contrato* { de, para, wit, .. }` before this
929    /// accessor landed) and the sibling
930    /// [`AplicacaoError::ContratoDuplicate`] duplicate-gate diagnostic
931    /// constructor (which paired `edge_pair()` for the `(de, para)`
932    /// prefix with a raw `c.wit.clone()` for the `wit:` tail — a mixed
933    /// typed-dispatch + raw-field-access shape the sibling accessor
934    /// family already flagged as a drift risk). Nine total call sites
935    /// collapse onto this helper.
936    ///
937    /// Lifted with the same one-source-of-truth discipline
938    /// [`WitContract::edge_pair`] carries on the paired
939    /// caller-callee-only axis: the returned tuple's `.0` / `.1` / `.2`
940    /// arms compose through the lifted [`WitContract::source`] /
941    /// [`WitContract::destination`] / [`WitContract::world_ref`]
942    /// scalar accessors byte-for-byte (pinned by the paired
943    /// [`tests::wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`]
944    /// composition-pin), so any future rebrand on the per-`:contratos`
945    /// caller / callee / world-ref axis (an M4 per-cluster
946    /// caller/callee-alias rewrite the operator pins through a future
947    /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
948    /// per-CR fully-qualified namespace prefix the M4
949    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
950    /// per-tenant, an M4-typed-caller-enum `Display` re-canonicalization
951    /// on `source()` / `destination()`, a per-CR canonicalization pass
952    /// that lowercases the WIT world ref post-parse) migrates as a
953    /// single caixa-core edit rather than a coordinated rewrite of
954    /// nine open-coded triple-constructors.
955    ///
956    /// Peer of the sibling per-`:contratos` composite-projection
957    /// [`WitContract::edge_pair`] accessor on the mesh-slot-atom
958    /// composite-value axes — closes the last unlifted owned-form
959    /// composite-tuple axis on the per-`:contratos` diagnostic-
960    /// construction surface. Named `edge_triple()` to reflect the
961    /// identity name of the projected tuple (the typed-edge
962    /// caller-callee-wit triple, sibling to the caller-callee-only
963    /// pair `edge_pair()` returns).
964    #[must_use]
965    pub fn edge_triple(&self) -> (String, String, String) {
966        (
967            self.source().to_string(),
968            self.destination().to_string(),
969            self.world_ref().to_string(),
970        )
971    }
972
973    /// Borrowed [`ContratoIdentity`] six-tuple every consumer that
974    /// dedups typed edges keys off — routes through the lifted
975    /// [`WitContract::source`] / [`WitContract::destination`] /
976    /// [`WitContract::world_ref`] / [`WitContract::endpoint`] /
977    /// [`WitContract::subject`] / [`WitContract::slot`] scalar
978    /// accessors so the tuple's six arms and the [`ContratoIdentity`]
979    /// type alias's six axes migrate as a unit on any future axis
980    /// addition (adding a seventh field to [`WitContract`] is one
981    /// [`ContratoIdentity`] alias edit + one accessor addition + one
982    /// arm here, not a coordinated rewrite of every open-coded
983    /// six-tuple builder that dedups on the identity axis).
984    ///
985    /// Sibling of [`WitContract::edge_pair`] /
986    /// [`WitContract::edge_triple`] on the composite-projection axis:
987    /// the pair projects the caller-callee axes, the triple extends it
988    /// with the world-ref, this method extends it with the three
989    /// payload-carrier axes. Every projection returns the same six
990    /// scalar accessors' outputs; the three methods differ only in
991    /// which arms they surface.
992    ///
993    /// Declared `pub const fn` — every callee is itself `pub const fn`
994    /// ([`Self::source`] / [`Self::destination`] / [`Self::world_ref`]
995    /// project through `pub const fn` [`String::as_str`], const-stable
996    /// since Rust 1.87; [`Self::endpoint`] / [`Self::subject`] /
997    /// [`Self::slot`] project through the same `String::as_str` under a
998    /// `match &self.<field> { Some(s) => Some(s.as_str()), None => None }`
999    /// arm — the sibling `Option<String> → Option<&str>` shape 0650f64
1000    /// closed the const-eval surface on) and tuple construction from
1001    /// borrowed-reference / `Option`-of-borrowed-reference arms is
1002    /// itself trivially const. The `ContratoIdentity<'_>` alias
1003    /// resolves to a `(&str, &str, &str, Option<&str>, Option<&str>,
1004    /// Option<&str>)` tuple whose every arm is `Copy` — no destructor,
1005    /// no heap allocation, no non-const call folded through the tuple's
1006    /// construction. Sibling in `const`-eval posture to the peer
1007    /// `pub const fn` [`WitContract::is_http`] / [`Self::is_pubsub`] /
1008    /// [`Self::is_store`] / [`Self::is_capability`] WIT-shape-predicate
1009    /// composite-projection family the sibling
1010    /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
1011    /// already anchors — this extends the same `const`-eval-surface
1012    /// posture onto the peer six-arm composite-projection axis where
1013    /// the projection surfaces the full identity tuple rather than a
1014    /// per-`(:de, :para, :wit)`-triple boolean shape probe. Pinned load-
1015    /// bearing by
1016    /// [`wit_contract_identity_projection_accessor_is_const_fn`] below
1017    /// (a future accidental downgrade fires E0015 at the wrapper at
1018    /// caixa-core build time).
1019    #[must_use]
1020    pub const fn identity(&self) -> ContratoIdentity<'_> {
1021        (
1022            self.source(),
1023            self.destination(),
1024            self.world_ref(),
1025            self.endpoint(),
1026            self.subject(),
1027            self.slot(),
1028        )
1029    }
1030
1031    /// True when this contract targets an HTTP-shaped WIT world.
1032    ///
1033    /// Declared `pub const fn` — routes through the paired `pub const
1034    /// fn` [`Self::world_ref`] scalar accessor and the substrate's
1035    /// `pub const fn` free-function classifier [`wit_shape_is_http`]
1036    /// (d46420c). Sibling in `const`-eval posture to the peer
1037    /// `pub const fn` [`Self::is_pubsub`] / [`Self::is_store`] /
1038    /// [`Self::is_capability`] WIT-shape-predicate family; the closed
1039    /// 4-arm partition on the raw `:contratos :wit` axis now carries
1040    /// the same `const`-eval-surface posture as the free-function
1041    /// classifier family it composes through. Pinned load-bearing by
1042    /// the [`wit_contract_pre_projection_accessor_family_is_const_fn`]
1043    /// test (a future accidental downgrade to non-`const` fires E0015
1044    /// at the corresponding `<arm>_via_const_fn` wrapper at caixa-core
1045    /// build time).
1046    #[must_use]
1047    pub const fn is_http(&self) -> bool {
1048        wit_shape_is_http(self.world_ref())
1049    }
1050
1051    /// True when this contract targets a pub-sub-shaped WIT world.
1052    ///
1053    /// Declared `pub const fn` — sibling in `const`-eval posture to
1054    /// the peer `pub const fn` [`Self::is_http`] / [`Self::is_store`] /
1055    /// [`Self::is_capability`] WIT-shape-predicate family. See
1056    /// [`Self::is_http`] for the family-closure rationale.
1057    #[must_use]
1058    pub const fn is_pubsub(&self) -> bool {
1059        wit_shape_is_pubsub(self.world_ref())
1060    }
1061
1062    /// True when this contract targets a key/value-shaped WIT world.
1063    ///
1064    /// Declared `pub const fn` — sibling in `const`-eval posture to
1065    /// the peer `pub const fn` [`Self::is_http`] / [`Self::is_pubsub`] /
1066    /// [`Self::is_capability`] WIT-shape-predicate family. See
1067    /// [`Self::is_http`] for the family-closure rationale.
1068    #[must_use]
1069    pub const fn is_store(&self) -> bool {
1070        wit_shape_is_store(self.world_ref())
1071    }
1072
1073    /// True when this contract targets *none* of the three known payload-
1074    /// shape WIT worlds — the fourth (payload-less) arm of the WIT-shape
1075    /// partition [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
1076    /// open on the [`WitContract`] surface. Returns the exact-inverse
1077    /// disjunction of the peer trio — `true` when none of the three
1078    /// prefix-set predicates matches the raw `:contratos :wit` value; the
1079    /// author-declared WIT world is a pure typed capability edge with no
1080    /// payload selector (the shape [`WitContract::target`] projects onto
1081    /// the payload-less [`WitTarget::Capability`] arm, MESH-COMPOSITION
1082    /// §II.3 — the fourth typed [`WitTarget`] arm the substrate admits).
1083    ///
1084    /// The `:contratos :wit` shape-space is closed at four arms
1085    /// ([`WIT_HTTP_SHAPE_PREFIXES`] / [`WIT_PUBSUB_SHAPE_PREFIXES`] /
1086    /// [`WIT_STORE_SHAPE_PREFIXES`] on the payload-carrying arms;
1087    /// everything else on the payload-less capability arm), and every
1088    /// downstream consumer that must filter contratos by shape-class
1089    /// keys off the four sibling predicates (the [`WitContract::target`]
1090    /// dispatch's implicit `else` after the three payload-shape arm
1091    /// checks at aplicacao.rs:959–1129 that admits [`WitTarget::Capability`],
1092    /// every future substrate-side capability-shape-only emitter — the
1093    /// M4 per-Aplicacao WIT-registry capability-import materializer, the
1094    /// future `feira app graph --capability` per-Aplicacao capability-
1095    /// column filter, the future per-cluster capability-scope reconciler
1096    /// that skips L4/L7 emission for payload-less edges since Cilium
1097    /// can't introspect WASI capability calls, the future
1098    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission webhook's per-
1099    /// shape shape-count histogram). Every such consumer reaches for one
1100    /// typed dispatch on the substrate primitive so the "which arm
1101    /// carries the capability-only shape?" answer lives at one caixa-core
1102    /// edit rather than open-coded across per-consumer
1103    /// `!c.is_http() && !c.is_pubsub() && !c.is_store()` triplet
1104    /// negations, each of which would silently drop a future fourth
1105    /// payload-arm addition without a compile-time signal at the
1106    /// consumer site.
1107    ///
1108    /// Prior to this lift the "not one of the three known payload
1109    /// shapes" classification sat inline at [`WitContract::target`]'s
1110    /// implicit `else`-branch (aplicacao.rs:1131 — the payload-less
1111    /// [`WitTarget::Capability`] admission arm after the three `if
1112    /// self.is_http() { … } if self.is_pubsub() { … } if self.is_store()
1113    /// { … }` guards) with no named accessor for downstream consumers
1114    /// to reach through. A future substrate-side capability-only
1115    /// filter or a future capability-scope reconciler would have had to
1116    /// re-inline the same triplet negation at every emit site with no
1117    /// compile-time link back to the sibling trio, and a future arm
1118    /// addition (a hypothetical fourth payload-shape prefix set — a
1119    /// `wasi:sockets/*` transport-layer shape or an `oci:*` capability-
1120    /// import carrier per the sibling [`wit_shape_matches`] docstring's
1121    /// trajectory bullet) would land the new predicate on the payload-
1122    /// carrying trio and silently misclassify the new shape as
1123    /// capability at every triplet-negation consumer site, propagating
1124    /// the drift far from the caixa-core prefix-set commit.
1125    ///
1126    /// Fourth arm on the [`WitContract`] WIT-shape-predicate family —
1127    /// closes the {[`Self::is_http`], [`Self::is_pubsub`], [`Self::is_store`]}
1128    /// trio into a 4-way partition witness on the raw `:contratos :wit`
1129    /// axis, mirroring the paired post-projection [`WitTarget`]
1130    /// `gen_platform::IsVariant`-derived 4-way predicate set
1131    /// ([`WitTarget::is_http`] / [`WitTarget::is_pubsub`] /
1132    /// [`WitTarget::is_store`] / [`WitTarget::is_capability`]) on the
1133    /// typed-view surface (7f6aa98 `IsVariant` derive lift on the peer
1134    /// arm-set). The two typed axes — pre-projection on the raw
1135    /// `:contratos :wit` string, post-projection on the validated typed
1136    /// view — now carry a matched 4-arm predicate discipline: every
1137    /// arm on the closed [`WitTarget`] set has a peer pre-projection
1138    /// predicate on the [`WitContract`] surface, and any future
1139    /// [`WitTarget`] variant addition (an M4 `Rest` / `Grpc` split of
1140    /// [`WitTarget::Http`] once the WIT registry stabilizes gRPC-shaped
1141    /// worlds per [`WitTarget`]'s own docstring at aplicacao.rs:1341-1343,
1142    /// a `Queue`-shaped peer of [`WitTarget::Store`]) reaches this
1143    /// pre-projection axis through a matching peer prefix-set + peer
1144    /// predicate lift by construction — the compile-time exhaustiveness
1145    /// on [`WitTarget::payload_pair`]'s single dispatch already enforces
1146    /// the post-projection accessor family stays in sync, and the sibling
1147    /// [`tests::wit_contract_is_capability_partitions_the_wit_shape_space`]
1148    /// partition-witness pin locks the pre-projection classification in
1149    /// load-bearing so a peer prefix-set addition that widened one arm's
1150    /// accept-set without shrinking the [`Self::is_capability`] accept-set
1151    /// surfaces as a test failure at caixa-core build time rather than a
1152    /// silent per-consumer split at renderer emit time.
1153    ///
1154    /// Composes byte-for-byte through the lifted peer trio
1155    /// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] so
1156    /// any future rebrand of any prefix-set const flows through this
1157    /// method by construction without a coordinated per-consumer rewrite
1158    /// (pinned by the sibling
1159    /// [`tests::wit_contract_is_capability_composes_through_shape_predicate_negation`]
1160    /// composition-witness).
1161    ///
1162    /// Note: purely syntactic classification on the `:wit` prefix-set —
1163    /// unlike [`Self::target`], which additionally rejects value-shape-
1164    /// invalid `:wit` strings (uppercase, hyphen-for-colon typo, empty
1165    /// package) via [`crate::render::is_wit_world_ref`] and payload-
1166    /// shape mismatches. A [`WitContract`] whose `:wit` is empty or
1167    /// structurally malformed returns `true` from `is_capability()` (the
1168    /// prefix set matches nothing), and the surrounding
1169    /// [`AplicacaoSpec::validate`] / [`WitContract::target`] gate cascade
1170    /// is where the [`AplicacaoError::EmptyWit`] /
1171    /// [`AplicacaoError::ContratoWitInvalid`] diagnostic surfaces — this
1172    /// predicate is the classifier, not the validator.
1173    ///
1174    /// Declared `pub const fn` — closes the WIT-shape-predicate
1175    /// family's `const`-eval-surface pass at the fourth (payload-less)
1176    /// arm; peer of the sibling `pub const fn` [`Self::is_http`] /
1177    /// [`Self::is_pubsub`] / [`Self::is_store`] payload-arm predicates.
1178    /// See [`Self::is_http`] for the family-closure rationale.
1179    #[must_use]
1180    pub const fn is_capability(&self) -> bool {
1181        wit_shape_is_capability(self.world_ref())
1182    }
1183
1184    /// True when this contract's caller equals its callee — a
1185    /// structurally degenerate typed edge that no `:contratos` entry can
1186    /// legitimately carry (MESH-COMPOSITION §III.1 — "Servico A calls
1187    /// Servico B" is an *inter*-Servico contract between two distinct
1188    /// graph nodes). A Servico contracting with itself resolves to an
1189    /// in-process call the wasm-engine never routes through the mesh at
1190    /// all, so no rendered `CiliumNetworkPolicy` / `HTTPRoute` /
1191    /// per-edge policy can express the intended shape — the pub-sub
1192    /// path silently rendered a self-allow rule that is a no-op (intra-
1193    /// pod traffic bypasses the mesh entirely), and the synchronous
1194    /// paths surfaced as a misleading `ContratoCycle` whose path was
1195    /// `["cart", "cart"]` — framing a self-edge as a multi-node
1196    /// deadlock. Every downstream consumer that must reject the shape
1197    /// (the [`AplicacaoSpec::validate`] per-`:contratos` self-loop
1198    /// gate at caixa-core/src/aplicacao.rs:5559, every future
1199    /// per-`:contratos`-edge policy resolver on the M4 CR materializer
1200    /// axis, every future adjacency-graph builder that must skip self-
1201    /// edges rather than fold them into an incidental cycle) now keys
1202    /// off exactly one typed dispatch on the substrate primitive, so
1203    /// any future rebrand on the axis (an M4-typed-caller enum whose
1204    /// identity comparison rule the accessor could route through, an
1205    /// operator-side per-cluster caller/callee-alias table the
1206    /// materializer resolves per-CR before the equality probe, a
1207    /// promotion of the pointwise `==` to a set-membership check once
1208    /// SimpleOneForOne-shaped dynamic replicas come into typed scope
1209    /// so a per-replica self-edge is rejected under the same predicate)
1210    /// migrates as a single caixa-core edit rather than a coordinated
1211    /// rewrite of every downstream self-edge consumer. Composes
1212    /// byte-for-byte through the lifted [`Self::source`] /
1213    /// [`Self::destination`] scalar accessors — the accessor pair every
1214    /// per-`:contratos` scalar-value axis already routes through — so
1215    /// any future rebrand of the underlying `:de` / `:para` storage
1216    /// (a lift from `String` to a typed `ServicoName(String)` newtype,
1217    /// a per-Aplicacao interning arena the M4 CR materializer authors,
1218    /// a `smol_str::SmolStr` inline-buffer swap) flows through the
1219    /// same one body without a coordinated per-consumer rewrite.
1220    ///
1221    /// Sibling in shape to the peer per-`:contratos` shape-predicate
1222    /// family [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
1223    /// on the `:wit` world-ref axis — extended onto the per-edge
1224    /// endpoint-equality axis: `is_http` / `is_pubsub` / `is_store`
1225    /// partition the WIT-shape-space; `is_self_loop` partitions the
1226    /// caller-callee identity-space. Named `is_self_loop()` to reflect
1227    /// the graph-theoretic identity of the shape (a loop from a graph
1228    /// node to itself, distinct from the sibling multi-node
1229    /// `ContratoCycle` shape [`Self::detect_sync_cycles`] rejects) and
1230    /// to match the [`AplicacaoError::ContratoSelfLoop`] diagnostic
1231    /// variant already carrying the term.
1232    ///
1233    /// Declared `pub const fn` — closes the last unlifted per-`:contratos`
1234    /// shape-predicate on the substrate's `const`-eval surface. The peer
1235    /// per-`:contratos` shape-predicate family [`Self::is_http`] /
1236    /// [`Self::is_pubsub`] / [`Self::is_store`] / [`Self::is_capability`]
1237    /// (d46420c / 84c2325 / 279823b) already carries the `pub const fn`
1238    /// posture on the WIT-world-ref classifier axis; this lift extends it
1239    /// onto the peer caller-callee identity-space predicate. The body
1240    /// projects the `:de` / `:para` `String` storage through the sibling
1241    /// `pub const fn` [`Self::source`] / [`Self::destination`] scalar
1242    /// accessors, then compares the resulting `&str` byte-slices under a
1243    /// manual `while`-loop through `str::as_bytes` (`pub const fn`,
1244    /// const-stable since Rust 1.39), primitive-`usize` `!=` on
1245    /// [`<[u8]>::len`], and const-stable slice indexing (since Rust 1.79)
1246    /// — every operation `const`-eval-callable on stable Rust, no
1247    /// iterator methods, no `PartialEq for str` trait dispatch (which
1248    /// remains non-`const` on stable). Mirrors the peer `pub const fn`
1249    /// [`wit_shape_matches`] combinator's manual byte-level `starts_with`
1250    /// loop verbatim on the paired-slice-equality shape. Every downstream
1251    /// substrate-side `const`-context consumer of the per-`:contratos`
1252    /// self-edge partition (a future `const _: () = assert!(…)` module-
1253    /// scope invariant pin over a per-fixture typed [`WitContract`] once
1254    /// the type's carriers admit `const`-context construction, a future
1255    /// M4 admission-webhook `const fn` self-edge resolver, any `const fn`
1256    /// composer that fans on the identity-space partition at compile
1257    /// time) reaches through the same typed dispatch on the substrate
1258    /// primitive at const-eval time as at runtime. Pinned by
1259    /// [`tests::wit_contract_is_self_loop_predicate_is_const_fn`] which
1260    /// witnesses the `const`-eval posture via a `const fn` wrapper so any
1261    /// future accidental downgrade to non-`const` trips at caixa-core
1262    /// build time with E0015 (`cannot call non-const method`), strictly
1263    /// stronger than a runtime `assert!`.
1264    #[must_use]
1265    pub const fn is_self_loop(&self) -> bool {
1266        // Compose through the paired `pub const fn` [`Self::source`] /
1267        // [`Self::destination`] scalar accessors so any future rebrand of
1268        // the underlying `:de` / `:para` storage (a lift from `String` to
1269        // a typed `ServicoName(String)` newtype, a per-Aplicacao interning
1270        // arena the M4 CR materializer authors, a `smol_str::SmolStr`
1271        // inline-buffer swap) flows through the same one body without a
1272        // coordinated per-consumer rewrite. Peer of the sibling
1273        // [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] /
1274        // [`Self::is_capability`] shape-predicate family — each of which
1275        // composes through the paired [`Self::world_ref`] scalar accessor
1276        // onto the peer `pub const fn` [`wit_shape_is_http`] /
1277        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
1278        // [`wit_shape_is_capability`] free-function classifier — the same
1279        // "typed dispatch composes with typed dispatch, not raw field
1280        // access" discipline extended onto the caller-callee identity-
1281        // space partition. Pinned by
1282        // [`tests::wit_contract_is_self_loop_routes_through_source_destination_accessors`]
1283        // above.
1284        let a = self.source().as_bytes();
1285        let b = self.destination().as_bytes();
1286        if a.len() != b.len() {
1287            return false;
1288        }
1289        // Manual byte-level equality loop — mirrors the peer
1290        // [`wit_shape_matches`] combinator's manual `starts_with` loop
1291        // verbatim on the paired-slice-equality shape. `PartialEq for
1292        // str` remains non-`const` on stable Rust 1.94 (the `Pattern`
1293        // trait dispatch it routes through is not `const`), so a naive
1294        // `self.source() == self.destination()` body would trip on
1295        // `const`-eval-callability; the byte-slice loop dispatches
1296        // through primitive-`u8` `!=`, primitive-`usize` comparison, and
1297        // const-stable slice indexing (since Rust 1.79) — every
1298        // operation `const`-eval-callable on stable.
1299        let mut i = 0;
1300        while i < a.len() {
1301            if a[i] != b[i] {
1302                return false;
1303            }
1304            i += 1;
1305        }
1306        true
1307    }
1308
1309    /// Reject a `:contratos` entry whose `:de` or `:para` names a
1310    /// caixa the `:membros` graph does not contain — the substrate-
1311    /// primitive per-edge graph-membership gate every consumer of the
1312    /// typed inter-Servico edge's endpoint-resolution axis reaches
1313    /// through one dispatch.
1314    ///
1315    /// A `:contratos` entry is a typed directed edge between two
1316    /// declared members (MESH-COMPOSITION §III.1 — "the typed edges
1317    /// address graph nodes, so a reference to a node the graph does
1318    /// not contain is a build error"). Both endpoints must resolve
1319    /// against the same [`AplicacaoSpec::membro_names`] oracle: the
1320    /// paired [`AplicacaoError::ContratoMemberMissing`] diagnostic
1321    /// framing does not distinguish `:de` from `:para` (both arms
1322    /// carry the offending `caixa` name verbatim without a
1323    /// slot-discriminator field, unlike the sibling per-arm shape
1324    /// gate [`validate_contrato_caixa`] whose paired
1325    /// [`AplicacaoError::ContratoCaixaEmpty`] / `ContratoCaixaInvalid`
1326    /// variants each carry a `slot: &'static str` tag). So the two
1327    /// arms are byte-identical modulo the accessor projection they
1328    /// key off, and folding them into one per-edge dispatch preserves
1329    /// every existing diagnostic-fired output byte-for-byte while
1330    /// closing the last inline duplication the substrate-primitive
1331    /// per-edge gate family carried inside
1332    /// [`AplicacaoSpec::validate_contratos`].
1333    ///
1334    /// Routes through the paired [`Self::source`] / [`Self::destination`]
1335    /// scalar accessors so every future rebrand of the underlying
1336    /// `:de` / `:para` storage (a lift from `String` to a typed
1337    /// `ServicoName(String)` newtype, a per-Aplicacao interning arena
1338    /// the M4 CR materializer authors, a per-cluster caller-alias
1339    /// table the operator pins through a future `:placement`-scoped
1340    /// slot, an M4 promotion from `String` to a typed edge-endpoint
1341    /// enum) flows through the same body without a coordinated
1342    /// per-consumer rewrite. Peer of the sibling per-edge substrate
1343    /// primitives already lifted on the same `impl WitContract`
1344    /// surface ([`Self::is_self_loop`] on the identity-space arm,
1345    /// [`Self::target`] on the payload-shape ↔ target-consistency
1346    /// arm, [`Self::identity`] on the dedup-key arm) — this run
1347    /// extends the shape to the last per-edge axis
1348    /// [`AplicacaoSpec::validate_contratos`] carried as an inline
1349    /// twin-arm cascade.
1350    ///
1351    /// Every future consumer that wants to re-check *one* edge's
1352    /// graph-membership reaches through one call: the M4
1353    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
1354    /// admission-webhook re-checking `:contratos` after a
1355    /// per-`(:de, :para)` edge patch without re-walking the whole
1356    /// `:contratos` list, the per-`:contratos`-edge `:politicas`
1357    /// override MESH-COMPOSITION §III.2 #3 acknowledges — which
1358    /// resolves an effective per-edge [`MeshPolicy`] and must
1359    /// re-check the edge's endpoints against the same membership
1360    /// oracle before it can key a per-edge override off the endpoint
1361    /// tuple. Pre-lift each such consumer was structurally forced to
1362    /// either re-inline the twin `if !names.contains(...)` cascade
1363    /// (the duplication the PRIME DIRECTIVE names as a bug) or call
1364    /// [`AplicacaoSpec::validate_contratos`] and pay a whole-list
1365    /// walk to re-check one edge. Post-lift each reaches the axis
1366    /// through one dispatch on the substrate primitive.
1367    ///
1368    /// `:de` runs before `:para` per the canonical edge-direction
1369    /// order the sibling per-arm shape gate
1370    /// [`validate_contrato_caixa`] arm ordering, the self-loop
1371    /// diagnostic string, and every peer arm ordering in
1372    /// [`AplicacaoSpec::validate_contratos`] already use — a
1373    /// well-shaped-but-phantom `:de` fires before a well-shaped-but-
1374    /// phantom `:para`, preserving byte-equal ordering with the
1375    /// pre-lift inline cascade.
1376    fn require_endpoints_in(
1377        &self,
1378        names: &std::collections::HashSet<&str>,
1379    ) -> Result<(), AplicacaoError> {
1380        if !names.contains(self.source()) {
1381            return Err(AplicacaoError::contrato_member_missing(self.source()));
1382        }
1383        if !names.contains(self.destination()) {
1384            return Err(AplicacaoError::contrato_member_missing(self.destination()));
1385        }
1386        Ok(())
1387    }
1388
1389    /// Typed view of the contract's payload target. Enforces that the
1390    /// `:wit` shape and the carried `:endpoint`/`:subject`/`:slot`
1391    /// fields agree, and that each carried value is itself
1392    /// value-shape valid:
1393    ///
1394    ///   - HTTP world (`wasi:http/*`, `http:*`) ⇒ exactly `:endpoint`,
1395    ///     non-empty, leading-`/` (Cilium L7 `path` + Gateway API
1396    ///     `PathPrefix` invariant — same shape required of `:entrada
1397    ///     :paths`)
1398    ///   - `PubSub` world (`nats:*`, `kafka:*`) ⇒ exactly `:subject`,
1399    ///     non-empty (NATS / Kafka publish without a subject is a
1400    ///     no-op subscribe, never the author's intent)
1401    ///   - Store world (`wasi:keyvalue/*`, `kv:*`) ⇒ exactly `:slot`,
1402    ///     non-empty (an empty slot template addresses the bucket
1403    ///     root, defeating the per-key isolation the slot exists for)
1404    ///   - Anything else ⇒ none of the three; the contract is a pure
1405    ///     typed capability edge with no payload selector.
1406    ///
1407    /// Translates the Apollo Federation discipline ("conflicts are
1408    /// errors at compile time, not warnings at runtime";
1409    /// MESH-COMPOSITION §II.3) onto pleme-io's typed Aplicacao surface:
1410    /// a contract whose WIT shape disagrees with its target field, or
1411    /// whose target field carries a value-shape-invalid string, is a
1412    /// build error — not a silent renderer drop. The returned
1413    /// [`WitTarget`] view's `&str` payload is therefore guaranteed
1414    /// non-empty (and absolute, for `Http`); every downstream consumer
1415    /// (caixa-mesh's L7 emission, the M3 Gateway/HTTPRoute renderer,
1416    /// the M4 per-edge policy resolver) can rely on that without
1417    /// re-checking.
1418    pub fn target(&self) -> Result<WitTarget<'_>, AplicacaoError> {
1419        // Route the HTTP-shaped payload-target extraction through the
1420        // lifted [`WitContract::endpoint`] accessor rather than the raw
1421        // `self.endpoint.as_deref()` field access — the two production
1422        // consumers of the per-`:contratos :endpoint` HTTP-shaped
1423        // payload-carrier scalar (this method's Http-arm payload
1424        // extraction, the [`AplicacaoSpec::validate`] duplicate-
1425        // `:contratos` [`ContratoIdentity`] dedup-key HTTP arm) now key
1426        // off exactly one typed dispatch on the substrate primitive, so
1427        // any future rebrand on the axis (an M4 per-cluster endpoint-
1428        // alias rewrite, a per-CR fully-qualified path prefix the M4
1429        // materializer applies per-tenant, an M4 promotion from
1430        // `Option<String>` to a typed HTTP path-template enum) migrates
1431        // as a single caixa-core edit rather than a coordinated rewrite
1432        // of the two call sites — peer of the sibling M3 per-`:placement`
1433        // [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
1434        // (74ec2d3) `Option<&str>` typed-dispatch discipline extended
1435        // onto the per-`:contratos` HTTP-shaped payload-carrier axis.
1436        let endpoint = self.endpoint();
1437        let subject = self.subject();
1438        // Route the store-arm payload-carrier scalar through the
1439        // lifted [`WitContract::slot`] accessor rather than the raw
1440        // `self.slot.as_deref()` field access — the two production
1441        // consumers of the per-`:contratos :slot` key/value-store-
1442        // shaped payload-carrier scalar (this method's Store-arm
1443        // payload extraction, the [`AplicacaoSpec::validate`]
1444        // duplicate-`:contratos` [`ContratoIdentity`] dedup-key store
1445        // arm) now key off exactly one typed dispatch on the substrate
1446        // primitive. Closes the last unlifted per-`:contratos`
1447        // `Option<String>` axis, completing the payload-carrier
1448        // accessor family peer of the sibling per-`:contratos`
1449        // [`WitContract::endpoint`] (7020470) / [`WitContract::subject`]
1450        // (90de675) lifts across the HTTP / pub-sub arms.
1451        let slot = self.slot();
1452        // Route the local `(de, para, wit)` triple-projection closure
1453        // through the lifted [`WitContract::edge_triple`] typed accessor
1454        // rather than re-inlining `(self.de.clone(), self.para.clone(),
1455        // self.wit.clone())` — the eight [`AplicacaoError::Contrato*`]
1456        // triple-carrying diagnostic constructors below (wrong-target /
1457        // missing-target on all three payload arms + capability-with-
1458        // payload + invalid-wit) now key off exactly one typed dispatch
1459        // on the substrate-primitive composite projection, sibling to
1460        // the peer [`WitContract::edge_pair`]-routed
1461        // [`AplicacaoError::Empty*`]/`ContratoEndpointEmpty`/
1462        // `ContratoSubjectEmpty`/`ContratoSlotEmpty` pair-carrying
1463        // diagnostic constructors on the same per-`:contratos`
1464        // diagnostic-construction surface.
1465        let edge = || self.edge_triple();
1466
1467        // The `:wit` value drives every downstream dispatch — the
1468        // is_http/is_pubsub/is_store prefix matchers below, the
1469        // caixa-mesh L7-vs-L4 emission, the cycle-detector's pub-sub
1470        // exclusion. Until this gate landed `target()` accepted any
1471        // non-empty string and silently demoted unrecognized shapes to
1472        // a capability-only edge (`:wit "WASI:HTTP/proxy"` — uppercase
1473        // typo, `:wit "wasi-http/proxy"` — hyphen-instead-of-colon typo,
1474        // `:wit "wasi:http proxy"` — whitespace, `:wit "wasi:"` — empty
1475        // package, the paste-from-binary footgun a multi-line blob
1476        // accidentally landing in the slot, the un-percent-encoded
1477        // non-ASCII byte) — the canonical "I thought I had L7 HTTP
1478        // routing, got L4-only" footgun. Empty is still pre-checked at
1479        // the [`AplicacaoSpec::validate`] call site via the narrower
1480        // [`AplicacaoError::EmptyWit`] variant (and fires first at the
1481        // validate layer); the value-shape gate here picks up the
1482        // structurally-invalid non-empty cases the empty check misses,
1483        // and remains correct under direct `target()` calls outside
1484        // validate (the predicate's defensive empty arm returns a
1485        // parser-shaped reason rather than silently falling through to
1486        // the Capability arm). Same trajectory as c4213a4 (WitContract
1487        // endpoint/subject/slot value-shape gates lifted into
1488        // `target()`) on the peer payload axes.
1489        //
1490        // Routed through the lifted [`WitContract::world_ref`] accessor
1491        // rather than the raw `&self.wit` field access — the two
1492        // production consumers of the per-`:contratos :wit` world-ref
1493        // byte-string on the value-shape axis (this method's invalid-
1494        // wit gate, the [`AplicacaoSpec::validate`] duplicate-
1495        // `:contratos` [`ContratoIdentity`] dedup-key world-ref arm via
1496        // [`WitContract::identity`]) now key off exactly one typed
1497        // dispatch on the substrate primitive, so any future rebrand on
1498        // the axis (an M4 promotion from `String` to a typed WIT
1499        // world-ref enum once the WIT registry stabilizes in
1500        // tatara-lisp, a per-CR canonicalization pass that lowercases
1501        // the WIT world ref post-parse, a promoted `smol_str::SmolStr`
1502        // inline-buffer swap on the storage arm) migrates as a single
1503        // caixa-core edit rather than a coordinated rewrite of the two
1504        // call sites — sibling of the peer [`WitContract::endpoint`] /
1505        // [`WitContract::subject`] / [`WitContract::slot`] accessor-
1506        // routed payload-carrier extractions above on the same
1507        // [`WitContract::target`] body, completing the per-`:contratos`
1508        // scalar-accessor-routing pass at the last unlifted raw-field-
1509        // access site inside `impl WitContract`. Same "typed dispatch
1510        // composes with typed dispatch, not with raw field access"
1511        // discipline the sibling [`WitContract::edge_pair`] /
1512        // [`WitContract::edge_triple`] / [`WitContract::identity`]
1513        // composite-projection accessors and the
1514        // [`WitContract::is_self_loop`] identity-space predicate
1515        // already route through. Pinned by
1516        // [`tests::wit_contract_target_wit_shape_gate_routes_through_world_ref_accessor`].
1517        if let Err(reason) = crate::render::is_wit_world_ref(self.world_ref()) {
1518            return Err(AplicacaoError::contrato_wit_invalid(
1519                self.edge_pair(),
1520                self.world_ref(),
1521                reason,
1522            ));
1523        }
1524
1525        if self.is_http() {
1526            if subject.is_some() || slot.is_some() {
1527                return Err(AplicacaoError::contrato_wrong_target(
1528                    edge(),
1529                    WitTarget::HTTP_FIELD_NAME,
1530                ));
1531            }
1532            let ep = endpoint.ok_or_else(|| {
1533                AplicacaoError::contrato_missing_target(edge(), WitTarget::HTTP_FIELD_NAME)
1534            })?;
1535            if ep.is_empty() {
1536                return Err(AplicacaoError::contrato_endpoint_empty(self.edge_pair()));
1537            }
1538            if !ep.starts_with('/') {
1539                return Err(AplicacaoError::contrato_endpoint_not_absolute(
1540                    self.edge_pair(),
1541                    ep,
1542                ));
1543            }
1544            // The `:endpoint` lands verbatim as a Cilium L7 `path:` rule
1545            // (caixa-mesh/src/lib.rs:311) and shares the K8s Gateway
1546            // API v1 HTTPPathMatch.value admission grammar with the
1547            // sibling `:entrada :paths` axis. Until this gate landed
1548            // `target()` only refused the empty string + the missing-
1549            // leading-`/` form; a structurally invalid endpoint
1550            // (`"/charge?token=X"` — query in path slot, `"/foo bar"` —
1551            // un-percent-encoded whitespace, `"/api/café"` — non-ASCII,
1552            // `"/api//bar"` — consecutive slash, `"/api/../etc"` —
1553            // path-traversal segment, the >1024-byte slug) silently
1554            // passed validate and the failure surfaced at apply time
1555            // as a Cilium policy rejection / silent traffic drop, far
1556            // from the source caixa.lisp. Same Gateway API HTTPPathMatch
1557            // grammar `:entrada :paths` already gates (55410e4), now
1558            // shared with `:contratos :endpoint` through the lifted
1559            // `crate::render::is_gateway_api_http_path` predicate.
1560            if let Err(reason) = crate::render::is_gateway_api_http_path(ep) {
1561                return Err(AplicacaoError::contrato_endpoint_invalid(
1562                    self.edge_pair(),
1563                    ep,
1564                    reason,
1565                ));
1566            }
1567            return Ok(WitTarget::Http { endpoint: ep });
1568        }
1569        if self.is_pubsub() {
1570            if endpoint.is_some() || slot.is_some() {
1571                return Err(AplicacaoError::contrato_wrong_target(
1572                    edge(),
1573                    WitTarget::PUBSUB_FIELD_NAME,
1574                ));
1575            }
1576            let s = subject.ok_or_else(|| {
1577                AplicacaoError::contrato_missing_target(edge(), WitTarget::PUBSUB_FIELD_NAME)
1578            })?;
1579            if s.is_empty() {
1580                return Err(AplicacaoError::contrato_subject_empty(self.edge_pair()));
1581            }
1582            // The `:subject` lands at runtime as the NATS subject the
1583            // producer publishes to and the consumer subscribes from.
1584            // Until this gate landed `target()` only refused the
1585            // empty string; a structurally invalid subject
1586            // (`"foo..bar"` — empty token between separators,
1587            // `"foo.>.bar"` — non-trailing `>` wildcard the NATS
1588            // server's subject parser rejects, `"foo bar"` —
1589            // un-percent-encoded whitespace, `"foo.café"` —
1590            // un-percent-encoded non-ASCII, `".foo"` / `"foo."` —
1591            // empty leading/trailing tokens, the >256-byte
1592            // paste-from-binary slug) silently passed validate and
1593            // the failure surfaced at runtime as a NATS server-side
1594            // `-ERR 'Invalid Subject'` on publish / subscribe, or as
1595            // a silent message drop, far from the source caixa.lisp.
1596            // Same Gateway API HTTPPathMatch / WIT-IDL grammar
1597            // trajectory `:contratos :endpoint` (4f0390b) and
1598            // `:contratos :wit` (6226bf4) already gate, now shared
1599            // with `:contratos :subject` through the lifted
1600            // `crate::render::is_nats_subject` predicate.
1601            if let Err(reason) = crate::render::is_nats_subject(s) {
1602                return Err(AplicacaoError::contrato_subject_invalid(
1603                    self.edge_pair(),
1604                    s,
1605                    reason,
1606                ));
1607            }
1608            return Ok(WitTarget::PubSub { subject: s });
1609        }
1610        if self.is_store() {
1611            if endpoint.is_some() || subject.is_some() {
1612                return Err(AplicacaoError::contrato_wrong_target(
1613                    edge(),
1614                    WitTarget::STORE_FIELD_NAME,
1615                ));
1616            }
1617            let sl = slot.ok_or_else(|| {
1618                AplicacaoError::contrato_missing_target(edge(), WitTarget::STORE_FIELD_NAME)
1619            })?;
1620            if sl.is_empty() {
1621                return Err(AplicacaoError::contrato_slot_empty(self.edge_pair()));
1622            }
1623            // Value-shape gate on the third (and last) typed payload
1624            // axis the `WitContract::target` dispatch carries — the
1625            // peer of [`crate::render::is_gateway_api_http_path`] for
1626            // `:endpoint` (4f0390b) and [`crate::render::is_nats_subject`]
1627            // for `:subject` (63e18a0). Until this gate landed
1628            // `target()` only refused the empty string; a structurally
1629            // invalid slot (`"check out/$order"` — un-percent-encoded
1630            // whitespace whose runtime behavior varies unpredictably
1631            // across kv backends, `"checkout/\x01order"` — control
1632            // character that Redis admits but corrupts on next read
1633            // and DynamoDB rejects outright, `"chéckout/$order"` —
1634            // un-percent-encoded non-ASCII byte each backend re-encodes
1635            // differently, `"checkout\n/$order"` — embedded newline,
1636            // the 513-byte paste-from-binary slug) silently passed
1637            // validate and surfaced at runtime as a per-backend kv
1638            // write rejection (DynamoDB / etcd) or as a silent
1639            // next-read corruption (Redis-via-RESP3), far from the
1640            // source caixa.lisp with no field naming which `:contratos`
1641            // edge carried the typo. The lifted predicate makes the
1642            // kv-backend intersection-floor a substrate-level
1643            // invariant at validate time, not a runtime "this passed
1644            // validate but the kv backend rejected on first write"
1645            // surprise — closes the typed payload-axis value-shape
1646            // trajectory across all three legs of the four
1647            // [`WitTarget`] arms (HTTP / PubSub / Store / Capability)
1648            // that caixa-mesh + the future kv emitters land in.
1649            if let Err(reason) = crate::render::is_wasi_keyvalue_slot(sl) {
1650                return Err(AplicacaoError::contrato_slot_invalid(
1651                    self.edge_pair(),
1652                    sl,
1653                    reason,
1654                ));
1655            }
1656            return Ok(WitTarget::Store { slot: sl });
1657        }
1658
1659        // Unrecognized WIT world — must not carry any payload target.
1660        if endpoint.is_some() || subject.is_some() || slot.is_some() {
1661            return Err(AplicacaoError::contrato_wrong_target(
1662                edge(),
1663                WitTarget::CAPABILITY_EXPECTED,
1664            ));
1665        }
1666        Ok(WitTarget::Capability)
1667    }
1668
1669    /// Substrate-canonical post-validation projection of the typed
1670    /// [`WitTarget`] view — the panic-on-failure shorthand every renderer
1671    /// downstream of an [`AplicacaoSpec`] that has already crossed the
1672    /// [`AplicacaoSpec::validate`] gate (typically via a caixa-mesh
1673    /// [`typed_view`]-shaped entry point that composes `validate` into
1674    /// the projection) reaches through when it needs the typed
1675    /// [`WitTarget`] and knows the containing [`AplicacaoSpec::validate`]
1676    /// has already admitted the `(:wit, :endpoint/:subject/:slot)` shape
1677    /// coherence for every `:contratos` entry. The peer accessor to the
1678    /// [`Self::target`] `Result`-returning validator on the same
1679    /// per-`:contratos` typed-projection axis — [`Self::target`] is the
1680    /// pre-validation validator that computes the projection *and* raises
1681    /// the [`AplicacaoError::Contrato*`] diagnostic cascade on any
1682    /// (`:wit`, payload) mismatch; this method is the post-validation
1683    /// projection every downstream consumer reaches through once the
1684    /// pre-validation gate has succeeded.
1685    ///
1686    /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
1687    ///
1688    /// Prior to this lift the "call `.target()` then `.expect(…)` with
1689    /// the same message" pattern sat inline at two production sites with
1690    /// no compile-time link between them: the
1691    /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)` CNP
1692    /// L7 introspection branch at `caixa-mesh/src/lib.rs:2825`
1693    /// (`c.target().expect("validated by typed_view").http_endpoint()`)
1694    /// and the [`caixa_feira::cmd::app`] `feira app graph` per-`:contratos`
1695    /// payload-column printer at `caixa-feira/src/cmd/app.rs:110`
1696    /// (`c.target().expect("validated by typed_view").graph_label()`),
1697    /// each open-coding the same `.target().expect("validated by
1698    /// typed_view")` pair with the message spelled twice. A future
1699    /// vocabulary shift on the panic-message axis (a tightening from
1700    /// `"validated by typed_view"` to `"validated by AplicacaoSpec::
1701    /// validate"` as the substrate's validator entry-point vocabulary
1702    /// sharpens, a per-consumer disambiguation, an M4 promotion of the
1703    /// panic to a `debug_assert` under a `--release` build profile) would
1704    /// have had to be threaded through both open-coded call sites in
1705    /// lockstep or one consumer would silently disagree with the peer on
1706    /// which invariant the panic message names. Same "same shape written
1707    /// verbatim ≥ 2 times becomes a typed helper" duplication-budget
1708    /// discipline the sibling [`Self::edge_pair`] /
1709    /// [`Self::edge_triple`] / [`Self::identity`] composite-projection
1710    /// lifts already establish on the paired composite-projection axis;
1711    /// this lift extends it onto the post-validation typed-view axis.
1712    ///
1713    /// Every future downstream consumer of the projected typed view
1714    /// (the future M4 per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao`
1715    /// CR materializer's per-edge admission webhook, the future
1716    /// Envoy-side per-typed-arm `local_rate_limit.descriptor_entries`
1717    /// bucket-key resolver, the future per-`:contratos`-edge mTLS overlay
1718    /// resolver, the future `feira app graph --l7` / `--pubsub` /
1719    /// `--kv` per-shape column emitters) reaches through this one typed
1720    /// dispatch on the substrate primitive rather than an open-coded
1721    /// per-consumer `.target().expect(…)` pair with the message
1722    /// re-inlined. The invariant the accessor's panic path pins — "this
1723    /// call is only reachable after [`AplicacaoSpec::validate`] has
1724    /// succeeded on the containing spec" — is the substrate's answer to
1725    /// give exactly once, at the primitive, not once per consumer.
1726    ///
1727    /// # Panics
1728    ///
1729    /// Panics with [`Self::PROJECTED_INVARIANT_MSG`] if [`Self::target`]
1730    /// would return an `Err` — i.e. if this contract's
1731    /// (`:wit`, `:endpoint`/`:subject`/`:slot`) shape has not been
1732    /// crossed by the [`AplicacaoSpec::validate`] gate cascade. Call
1733    /// this accessor only from a code path that has already reached the
1734    /// containing [`AplicacaoSpec`] through a validating entry-point
1735    /// (caixa-mesh's [`typed_view`], caixa-feira's `feira app graph`'s
1736    /// [`typed_view`] compose, the future M4 CR admission webhook's
1737    /// per-CR validate). Use [`Self::target`] instead on any pre-
1738    /// validation code path.
1739    ///
1740    /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
1741    #[must_use]
1742    pub fn target_projected(&self) -> WitTarget<'_> {
1743        self.target().expect(Self::PROJECTED_INVARIANT_MSG)
1744    }
1745
1746    /// Canonical panic message the [`Self::target_projected`]
1747    /// post-validation projection accessor threads through when the
1748    /// caller has violated the "call only after [`AplicacaoSpec::validate`]
1749    /// has succeeded" precondition. Lifted as a `pub const` on the
1750    /// [`WitContract`] surface so the byte-string lives in one place
1751    /// across the substrate — the [`Self::target_projected`] method
1752    /// body, the two prior production call sites' comments now naming
1753    /// the const, and every future consumer that must format-match the
1754    /// panic-message shape (a future test suite that asserts the panic-
1755    /// message byte-string across a fuzzed invalid-contract corpus,
1756    /// a future custom-panic hook in `caixa-operator` that surfaces the
1757    /// message with per-`:contratos` telemetry, the future admission
1758    /// webhook's per-CR validate-error report) reaches through the same
1759    /// canonical `&'static str`. A future rebrand on the panic-message
1760    /// axis (a tightening from `"validated by typed_view"` to `"validated
1761    /// by AplicacaoSpec::validate"` as the substrate's validator
1762    /// entry-point vocabulary sharpens once caixa-core grows a
1763    /// `Caixa::validated_aplicacao_view` companion to caixa-mesh's
1764    /// [`typed_view`]) lands at one caixa-core edit rather than a
1765    /// coordinated per-consumer sweep — same "one canonical declaration
1766    /// per axis, next to the accessor that reads it" discipline the peer
1767    /// [`WitTarget::CAPABILITY_LABEL`] / [`WitTarget::CAPABILITY_EXPECTED`]
1768    /// / [`WitTarget::CAPABILITY_GRAPH_LABEL`] payload-less-arm scalar-
1769    /// const family already establishes on the paired per-consumer-axis
1770    /// diagnostic-scalar surface.
1771    pub const PROJECTED_INVARIANT_MSG: &'static str = "validated by typed_view";
1772}
1773
1774/// Borrowed identity key for the typed-graph duplicate-`:contratos`
1775/// gate (see [`AplicacaoSpec::validate`]): every field that
1776/// distinguishes one contract from another, in declaration order
1777/// (`(de, para, wit, endpoint, subject, slot)`). Two [`WitContract`]s
1778/// with equal [`ContratoIdentity`]s are the same typed edge declared
1779/// twice — the graph-edge analogue of duplicate `:membros` /
1780/// `:placement :clusters` / `:entrada :paths` entries. Lifted as a
1781/// type alias so the duplicate-gate's `HashSet<…>` type doesn't trip
1782/// clippy's `type_complexity` lint (and so a future axis added to
1783/// `WitContract` is one alias edit, not a coordinated rewrite of
1784/// every set instantiation).
1785pub type ContratoIdentity<'a> = (
1786    &'a str,
1787    &'a str,
1788    &'a str,
1789    Option<&'a str>,
1790    Option<&'a str>,
1791    Option<&'a str>,
1792);
1793
1794/// Typed view of a [`WitContract`]'s payload target. Each variant
1795/// carries the field its WIT shape requires; constructing a `Http`
1796/// view without an endpoint is impossible by the type system.
1797///
1798/// Renderers (caixa-mesh L7 rules, feira app graph) match on this
1799/// instead of probing `Option<String>` fields one by one — the
1800/// "which payload field is set?" question is answered once, at
1801/// validation time.
1802#[derive(Debug, Clone, Copy, PartialEq, Eq, gen_platform::IsVariant)]
1803pub enum WitTarget<'a> {
1804    /// HTTP-shaped WIT world. Carries the configured request path.
1805    Http { endpoint: &'a str },
1806    /// Pub-sub-shaped WIT world. Carries the event-stream subject.
1807    ///
1808    /// The `IsVariant` derive would auto-name the predicate `is_pub_sub`
1809    /// (`discriminant_to_snake("PubSub") == "pub_sub"`); the explicit
1810    /// `#[is_variant(name = "pubsub")]` override keeps the emitted
1811    /// method name byte-identical to the sibling
1812    /// [`WitContract::is_pubsub`] predicate (the paired shape-side
1813    /// arm-discriminator that routes through
1814    /// [`wit_shape_is_pubsub`] on the wit-world-ref scalar rather than
1815    /// through `matches!` on the variant), so the two arm-discriminator
1816    /// axes — target-side variant-arm and shape-side ref-prefix — reach
1817    /// every downstream consumer through the same `is_pubsub()` name.
1818    #[is_variant(name = "pubsub")]
1819    PubSub { subject: &'a str },
1820    /// Key-value-shaped WIT world. Carries the slot template.
1821    Store { slot: &'a str },
1822    /// A typed capability edge with no payload selector — the WIT
1823    /// world stands on its own (rare; reserved for plain capability
1824    /// imports or M4-and-later WIT worlds we haven't shaped yet).
1825    Capability,
1826}
1827
1828impl<'a> WitTarget<'a> {
1829    /// Canonical author-facing `:contratos` payload field name for the
1830    /// HTTP-shaped arm — the `expected: &'static str` scalar the
1831    /// [`AplicacaoError::ContratoMissingTarget`] /
1832    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1833    /// through, the `:endpoint "…"` keyword the [`WitTarget::label`]
1834    /// duplicate-edge diagnostic emits, and the `endpoint=…` prefix
1835    /// the `feira app graph` verb prints. Peer of
1836    /// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
1837    /// on the payload-field-name axis; declared as a peer const next
1838    /// to the [`WitTarget::Http`] variant so a future rename on the
1839    /// author-surface `(defcaixa … :contratos ((:de … :para … :wit …
1840    /// :endpoint …)))` field lands in exactly one place, not scattered
1841    /// across the [`WitContract::target`] gate's six `expected:`
1842    /// literals, the label template, and every downstream consumer
1843    /// that prints a per-arm prefix. Same trajectory as the peer
1844    /// [`WitTarget::label`] lift (174e96a): a single source of truth
1845    /// for the arm's shape, next to the variant declaration.
1846    pub const HTTP_FIELD_NAME: &'static str = "endpoint";
1847    /// Canonical author-facing `:contratos` payload field name for the
1848    /// pub-sub-shaped arm. Peer of [`WitTarget::HTTP_FIELD_NAME`] /
1849    /// [`WitTarget::STORE_FIELD_NAME`] on the payload-field-name axis;
1850    /// see [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1851    pub const PUBSUB_FIELD_NAME: &'static str = "subject";
1852    /// Canonical author-facing `:contratos` payload field name for the
1853    /// key/value-store-shaped arm. Peer of
1854    /// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`]
1855    /// on the payload-field-name axis; see
1856    /// [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1857    pub const STORE_FIELD_NAME: &'static str = "slot";
1858
1859    /// Canonical stable human-readable label the payload-less
1860    /// [`WitTarget::Capability`] arm renders as under [`Self::label`] —
1861    /// the byte-string every consumer that formats a payload-less
1862    /// typed capability edge as text lands on (the
1863    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` diagnostic
1864    /// naming which identical edge was declared twice, the future
1865    /// `feira app graph` verb's per-arm prefix, the future M4 per-edge
1866    /// policy resolver's audit view, the operator's mesh-graph audit).
1867    /// Peer of the payload-arm [`Self::HTTP_FIELD_NAME`] /
1868    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`]
1869    /// author-facing label-scalar consts — the same
1870    /// "one canonical declaration per arm, next to the variant, so a
1871    /// future rename lands in one place" discipline extended to the
1872    /// payload-less arm. Until this lift landed the byte-string sat
1873    /// twice — once inline in [`Self::label`]'s [`WitTarget::Capability`]
1874    /// match arm, once in the pin test asserting the label's
1875    /// [`WitTarget::Capability`] output — with no compile-time link
1876    /// between the two: a rebrand on either side (an operator-facing
1877    /// vocabulary shift, a per-consumer disambiguation like
1878    /// `"(capability — no payload; typed edge only)"`) would silently
1879    /// desynchronize until a downstream consumer surfaced the drift at
1880    /// runtime.
1881    pub const CAPABILITY_LABEL: &'static str = "(capability — no payload)";
1882
1883    /// Canonical `expected:` scalar the
1884    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1885    /// through for the payload-less [`WitTarget::Capability`] arm — the
1886    /// byte-string authors read as "this WIT world's shape is not one
1887    /// of {`HTTP`, `PubSub`, `Store`}, so it must not carry
1888    /// `:endpoint` / `:subject` / `:slot`". Peer of the payload-arm
1889    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1890    /// [`Self::STORE_FIELD_NAME`] consts on the
1891    /// `ContratoWrongTarget::expected` axis — the fourth arm of the
1892    /// same "which payload field name goes in the diagnostic" dispatch
1893    /// the three payload-arm consts cover, extended to the payload-less
1894    /// arm. Until this lift landed the byte-string sat twice — once
1895    /// inline in the [`Self::target`] Capability-arm rejection at the
1896    /// production dispatch, once in the pin test asserting the
1897    /// diagnostic's `expected:` scalar carries `"none"` verbatim — with
1898    /// no compile-time link between the two: a rebrand on either side
1899    /// (an author-facing vocabulary shift to `"capability"` /
1900    /// `"(none)"` / `"no-payload"` as the WIT registry's shape
1901    /// vocabulary sharpens, a per-consumer disambiguation as M4 splits
1902    /// [`WitTarget::Capability`] into per-shape peers) would silently
1903    /// desynchronize until a downstream consumer surfaced the drift at
1904    /// runtime. Same "one canonical declaration per arm, next to the
1905    /// variant, so a future rename lands in one place" discipline the
1906    /// peer [`Self::CAPABILITY_LABEL`] lift (7ed03a3-era) already
1907    /// established for the payload-less arm's human-readable label
1908    /// axis; this lift extends it onto the peer diagnostic-scalar axis
1909    /// so both halves of the "how does the Capability arm surface at
1910    /// its two consumer axes (human-readable label, wrong-target
1911    /// diagnostic)" pipeline route through peer consts declared next
1912    /// to the variant.
1913    ///
1914    /// Pairwise-distinctness against the three payload-arm scalars
1915    /// ([`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1916    /// [`Self::STORE_FIELD_NAME`]) is pinned by the sibling
1917    /// `wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`
1918    /// test — the 4-way closure of the 3-way
1919    /// `wit_target_field_names_are_pairwise_distinct` sibling pin onto
1920    /// the `ContratoWrongTarget::expected` axis, matching the peer
1921    /// `m3_placement_estrategia_consts_are_pairwise_distinct` closed-set
1922    /// scalar-value distinctness discipline the sibling M3 typed-enum
1923    /// discriminator axis already carries.
1924    pub const CAPABILITY_EXPECTED: &'static str = "none";
1925
1926    /// Canonical `feira app graph` per-`:contratos`-edge payload-column
1927    /// byte-string the payload-less [`WitTarget::Capability`] arm renders
1928    /// as under [`Self::graph_label`] — the sibling
1929    /// [`WitTarget::CAPABILITY_LABEL`] scalar on the peer graph-verb
1930    /// payload-column axis (the graph verb spells payload-less as
1931    /// `(capability-only)`, distinct from the duplicate-`:contratos`
1932    /// diagnostic's `(capability — no payload)` on the human-readable
1933    /// [`Self::label`] axis). Peer of [`Self::CAPABILITY_LABEL`] /
1934    /// [`Self::CAPABILITY_EXPECTED`] on the payload-less-arm scalar-const
1935    /// family — extends the "one canonical declaration per arm, next to
1936    /// the variant, so a future rename lands in one place" discipline
1937    /// onto the third payload-less-arm consumer axis (`feira app graph`
1938    /// payload column, joining the [`Self::label`] duplicate-`:contratos`
1939    /// diagnostic axis and the [`Self::target`] wrong-target diagnostic
1940    /// axis).
1941    ///
1942    /// Until this lift landed the byte-string sat inline in
1943    /// [`caixa-feira`]'s `cmd::app::GraphArgs::run` per-`:contratos` payload-
1944    /// column match at `caixa-feira/src/cmd/app.rs:111` as a raw
1945    /// `"(capability-only)".to_string()` literal, with no compile-time link
1946    /// back to the [`WitTarget::Capability`] variant declaration nor to
1947    /// the sibling [`Self::CAPABILITY_LABEL`] / [`Self::CAPABILITY_EXPECTED`]
1948    /// peer consts already carrying the "one canonical declaration per
1949    /// payload-less-arm consumer axis" discipline. A rebrand on either
1950    /// side (the graph verb's operator-facing vocabulary tightening from
1951    /// `"(capability-only)"` to `"capability"` / `"(capability edge)"` as
1952    /// the WIT registry vocabulary sharpens, an M4 split of
1953    /// [`Self::Capability`] into per-shape peers) would silently
1954    /// desynchronize the graph-verb byte-string from the paired
1955    /// per-arm-adjacent const and land two spellings of the same axis in
1956    /// two spots.
1957    pub const CAPABILITY_GRAPH_LABEL: &'static str = "(capability-only)";
1958
1959    /// The `(author-facing field name, payload)` pair this typed target
1960    /// arm carries — `Some((HTTP_FIELD_NAME, endpoint))` for
1961    /// [`Self::Http`], `Some((PUBSUB_FIELD_NAME, subject))` for
1962    /// [`Self::PubSub`], `Some((STORE_FIELD_NAME, slot))` for
1963    /// [`Self::Store`], `None` for the payload-less
1964    /// [`Self::Capability`] arm.
1965    ///
1966    /// Lifted as the single 4-arm dispatch that both [`Self::label`]
1967    /// (formats `":{field} {payload:?}"` on `Some`, falls to
1968    /// [`Self::CAPABILITY_LABEL`] on `None`) and [`Self::field_name`]
1969    /// (returns the first component) route through, so a future
1970    /// [`WitTarget`] variant addition — the M4-and-later per-edge WIT
1971    /// registry may split [`Self::Http`] into `Rest` / `Grpc` peers,
1972    /// or extend [`Self::Store`] with a `Queue`-shaped peer — becomes
1973    /// exactly one new match-arm here (a compile-time exhaustiveness
1974    /// error otherwise), not a coordinated three-way rewrite of the
1975    /// prior [`Self::label`] template + [`Self::field_name`] dispatch
1976    /// + every downstream consumer that reaches for the pair.
1977    ///
1978    /// Until this lift landed the three payload arms sat in
1979    /// [`Self::label`] as three near-identical `format!(":{} {…:?}", …)`
1980    /// invocations (one per variant, each hand-quoting the paired
1981    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1982    /// [`Self::STORE_FIELD_NAME`] const) — the canonical
1983    /// "same shape, written N times" duplication THEORY.md §I.3.5
1984    /// ("Generation first, composition second, hand-authoring last;
1985    /// the duplication budget is zero") promotes to a build-time
1986    /// concern, with each per-arm site paired to its own const with no
1987    /// compile-time link between the format template and the arm's
1988    /// payload extraction.
1989    #[must_use]
1990    pub const fn payload_pair(&self) -> Option<(&'static str, &'a str)> {
1991        match *self {
1992            WitTarget::Http { endpoint } => Some((Self::HTTP_FIELD_NAME, endpoint)),
1993            WitTarget::PubSub { subject } => Some((Self::PUBSUB_FIELD_NAME, subject)),
1994            WitTarget::Store { slot } => Some((Self::STORE_FIELD_NAME, slot)),
1995            WitTarget::Capability => None,
1996        }
1997    }
1998
1999    /// The canonical author-facing `:contratos` payload field name
2000    /// this typed target arm carries (`Http` → `Some("endpoint")`,
2001    /// `PubSub` → `Some("subject")`, `Store` → `Some("slot")`), or
2002    /// `None` for the payload-less `Capability` arm.
2003    ///
2004    /// Routes through [`Self::payload_pair`] — the single 4-arm
2005    /// dispatch [`Self::label`] also reads — so a future variant
2006    /// addition is one match-arm edit at [`Self::payload_pair`], not a
2007    /// per-consumer rewrite. Same "exhaustive-match at one canonical
2008    /// dispatch, thin projections at each consumer" trajectory the
2009    /// peer [`PlacementStrategy::as_str`] / [`std::fmt::Display`]
2010    /// pair (0a2f653) landed on the sibling M3 typed-enum axis.
2011    #[must_use]
2012    pub const fn field_name(&self) -> Option<&'static str> {
2013        match self.payload_pair() {
2014            Some((f, _)) => Some(f),
2015            None => None,
2016        }
2017    }
2018
2019    /// The underlying scalar the payload-carrying arm carries — the
2020    /// per-arm request path ([`Self::Http`] `:endpoint`), event-stream
2021    /// subject ([`Self::PubSub`] `:subject`), or slot template
2022    /// ([`Self::Store`] `:slot`), borrowed from the typed slot's own
2023    /// `&'a str` storage — or `None` on the payload-less
2024    /// [`Self::Capability`] arm.
2025    ///
2026    /// Thin projection onto the single 4-arm [`Self::payload_pair`]
2027    /// dispatch (`self.payload_pair().map(|(_, p)| p)` in `const fn`
2028    /// form) — peer of [`Self::field_name`] (`.payload_pair().0`) on
2029    /// the paired sub-selector axis. Both per-half accessors read from
2030    /// one authoritative match, so a future [`WitTarget`] variant
2031    /// addition (`Rest`/`Grpc` split of [`Self::Http`], `Queue`-shaped
2032    /// peer of [`Self::Store`]) lands at exactly one caixa-core edit
2033    /// on [`Self::payload_pair`] and both per-half projections + every
2034    /// downstream consumer picks the new arm up by construction — no
2035    /// coordinated N-way rewrite across the paired accessor dispatches,
2036    /// the [`Self::label`] / [`Self::graph_label`] format templates,
2037    /// and every future WIT-registry-shaped consumer.
2038    ///
2039    /// Peer of the sibling [`caixa-flux`][caixa-flux-crate]
2040    /// `GitRefSpec::ref_value` projection on the `FluxCD` source-
2041    /// controller `spec.ref.<field>` axis — same "one paired dispatch,
2042    /// both per-half projections as thin readers, every downstream
2043    /// consumer through the same match" discipline extended onto the
2044    /// M3 `:contratos` payload-arm axis. Closes the discipline-parity
2045    /// gap between the two paired-dispatch surfaces: the peer
2046    /// [`Self::payload_pair`] + [`Self::field_name`] pair carried only
2047    /// the first-component projection until this lift; the second-
2048    /// component sibling now sits alongside so both halves reach every
2049    /// future consumer through the same substrate-primitive dispatch.
2050    ///
2051    /// [caixa-flux-crate]: https://docs.rs/caixa-flux/latest/caixa_flux/enum.GitRefSpec.html#method.ref_value
2052    #[must_use]
2053    pub const fn payload(&self) -> Option<&'a str> {
2054        match self.payload_pair() {
2055            Some((_, p)) => Some(p),
2056            None => None,
2057        }
2058    }
2059
2060    /// Substrate-canonical per-arm HTTP-endpoint scalar accessor every
2061    /// consumer that fans on the L7-HTTP-shaped payload keys off —
2062    /// returns the [`Self::Http`]-arm's author-declared request path
2063    /// verbatim as an `Option<&'a str>`, `Some(endpoint)` when the
2064    /// projected target is [`Self::Http { endpoint }`], `None` on the
2065    /// three sibling arms ([`Self::PubSub`] / [`Self::Store`] /
2066    /// [`Self::Capability`], each of which carries no HTTP endpoint by
2067    /// definition).
2068    ///
2069    /// The [`Self::Http`] arm carries the Cilium L7 `HTTPNetworkPolicy`
2070    /// `path:` rule payload every substrate-side L7-introspecting
2071    /// per-`(:de, :para)` `CiliumNetworkPolicy` emitter reads (today: the
2072    /// [`caixa_mesh::cilium_network_policies`] per-edge `toPorts[].rules
2073    /// .http[0].path` scalar the HTTP-shape-only L7 rule builder emits
2074    /// on the L7 introspection branch; every peer WIT shape stays
2075    /// L4-only because Cilium can't introspect NATS / key-value / plain
2076    /// capability edges), and every future L7-introspecting consumer
2077    /// of the projected target's HTTP endpoint (the future M4
2078    /// per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao` CR
2079    /// materializer's per-edge L7 admission-webhook overlay, the
2080    /// future Envoy-side `local_rate_limit.descriptor_entries` per-HTTP-
2081    /// path bucket-key resolver, the future per-`:contratos`-edge
2082    /// mTLS-required overlay's HTTP-shape scope filter, the future
2083    /// `feira app graph --l7` per-Aplicacao HTTP-path column) reaches
2084    /// through the same typed dispatch.
2085    ///
2086    /// Prior to this lift the sole production consumer of the projected-
2087    /// target HTTP endpoint — the [`caixa_mesh::cilium_network_policies`]
2088    /// per-edge L7 introspection branch at `caixa-mesh/src/lib.rs:2759`
2089    /// (`if let WitTarget::Http { endpoint } = c.target().expect(…) {
2090    /// http_rule.insert_string(CILIUM_KEY_PATH, endpoint.to_string()); …
2091    /// }`) — reached the payload through a raw per-arm `if let` pattern-
2092    /// match that expressed no compile-time link back to the substrate
2093    /// primitive's typed dispatch, sibling to the [`WitContract`] pre-
2094    /// projection [`WitContract::endpoint`] (7020470) `Option<&str>`
2095    /// scalar accessor on the peer per-`:contratos` raw-field axis but
2096    /// with no post-projection peer on the typed-view surface. A future
2097    /// [`WitTarget`] variant addition that splits [`Self::Http`] into
2098    /// peers (a `Rest`/`Grpc` split once the WIT registry stabilizes
2099    /// gRPC-shaped worlds per this enum's own docstring at
2100    /// aplicacao.rs:1341-1343 — with a `Rest`-arm `endpoint: &'a str`
2101    /// payload alongside a `Grpc`-arm `service_method: &'a str` payload)
2102    /// would have had to be threaded through the caixa-mesh L7 emit
2103    /// branch's raw `if let` in lockstep — either coalescing the two
2104    /// L7-HTTP-family arms under a shared `path:` emit, or splitting the
2105    /// emit path per-arm — with no substrate-primitive dispatch making
2106    /// the "which arms count as L7-HTTP-shaped for path-emission
2107    /// purposes" question the substrate's answer to give. Lifting the
2108    /// resolution to a typed method on the substrate primitive means
2109    /// every downstream L7-HTTP-facing consumer of the Aplicacao's
2110    /// projected-target HTTP endpoint reaches for exactly one typed
2111    /// dispatch — the resolver's accept-set migrates as a unit on any
2112    /// future arm-family widening, and the caixa-mesh L7 emit branch
2113    /// reads through the same substrate primitive.
2114    ///
2115    /// Peer of the sibling pre-projection [`WitContract::endpoint`]
2116    /// (7020470) `Option<&str>` scalar accessor on the raw
2117    /// `:contratos :endpoint` field-access axis — same "one typed
2118    /// dispatch on the substrate primitive, thin projections at each
2119    /// consumer" discipline extended onto the peer post-projection typed-
2120    /// view surface (the [`WitContract::endpoint`] pre-projection
2121    /// accessor returns `Some` for any author-declared `:endpoint`
2122    /// value regardless of the paired `:wit` world's HTTP-shape
2123    /// classification — the raw slot before validation crosses it —
2124    /// while this post-projection [`Self::http_endpoint`] accessor
2125    /// returns `Some` iff the target has been projected onto the
2126    /// [`Self::Http`] arm, i.e. only after the [`WitContract::target`]
2127    /// gate has admitted the `(:wit, :endpoint/:subject/:slot)` shape
2128    /// coherence; the two accessors close the pre-projection /
2129    /// post-projection pair on the HTTP-endpoint axis). Sibling of the
2130    /// unified pan-arm [`Self::payload`] (`Option<&'a str>` for any of
2131    /// the three payload-carrying arms) — extends the per-arm
2132    /// projection family onto the [`Self::Http`] specialization axis
2133    /// that the pan-arm accessor's shape blends into a single arm-
2134    /// agnostic view; paired with [`Self::pubsub_subject`] /
2135    /// [`Self::store_slot`] on the sibling per-arm axes so every
2136    /// per-payload-arm shape carries a named post-projection accessor
2137    /// on the same shape as `http_endpoint`, closing the per-arm-shape
2138    /// accept-set the substrate primitive owns.
2139    #[must_use]
2140    pub const fn http_endpoint(&self) -> Option<&'a str> {
2141        match *self {
2142            WitTarget::Http { endpoint } => Some(endpoint),
2143            WitTarget::PubSub { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
2144        }
2145    }
2146
2147    /// Substrate-canonical per-arm pub-sub-subject scalar accessor every
2148    /// consumer that fans on the pub-sub-shaped payload keys off —
2149    /// returns the [`Self::PubSub`]-arm's author-declared event-stream
2150    /// subject verbatim as an `Option<&'a str>`, `Some(subject)` when
2151    /// the projected target is [`Self::PubSub { subject }`], `None` on
2152    /// the three sibling arms ([`Self::Http`] / [`Self::Store`] /
2153    /// [`Self::Capability`], each of which carries no NATS-shaped
2154    /// subject by definition).
2155    ///
2156    /// The [`Self::PubSub`] arm carries the NATS-server-accepted subject
2157    /// the future substrate-side pub-sub-introspecting per-`(:de, :para)`
2158    /// consumer keys off (the M4 per-Aplicacao NATS `Stream` / `Consumer`
2159    /// CR materializer's `spec.subjects[]` projection, the future
2160    /// Envoy-side per-subject `local_rate_limit.descriptor_entries`
2161    /// bucket-key resolver, the future `feira app graph --pubsub`
2162    /// per-Aplicacao subject column, any future substrate-lifted
2163    /// pub-sub-shape emitter that reads a projected `WitTarget` in the
2164    /// same shape [`caixa_mesh::cilium_network_policies`] reads the
2165    /// HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today). Every
2166    /// future pub-sub-shape consumer reaches for the same typed
2167    /// dispatch this accessor exposes so the "which arm carries the
2168    /// subject scalar?" answer lives at one caixa-core edit rather
2169    /// than open-coded across per-consumer `if let WitTarget::PubSub
2170    /// { subject } = c.target()…` pattern-matches.
2171    ///
2172    /// Peer of the sibling [`Self::http_endpoint`] (5d6dc92 trajectory)
2173    /// per-arm HTTP-endpoint accessor on the peer per-arm axis and of
2174    /// the pre-projection [`WitContract::subject`] scalar accessor on
2175    /// the raw `:contratos :subject` field-access axis — same "one
2176    /// typed dispatch on the substrate primitive, thin projections at
2177    /// each consumer" discipline extended onto the per-arm pub-sub
2178    /// post-projection axis. The pre-projection accessor returns
2179    /// `Some` for any author-declared `:subject` value regardless of
2180    /// the paired `:wit` world's pub-sub-shape classification (the raw
2181    /// slot before validation crosses it); this post-projection
2182    /// accessor returns `Some` iff the target has been projected onto
2183    /// the [`Self::PubSub`] arm, i.e. only after the
2184    /// [`WitContract::target`] gate has admitted the
2185    /// `(:wit, :endpoint/:subject/:slot)` shape coherence — closing
2186    /// the pre-/post-projection pair on the pub-sub-subject axis to
2187    /// match the pair the [`WitContract::endpoint`] +
2188    /// [`Self::http_endpoint`] surfaces already close on the peer
2189    /// HTTP-endpoint axis.
2190    ///
2191    /// Sibling of the unified pan-arm [`Self::payload`]
2192    /// (`Option<&'a str>` for any of the three payload-carrying arms) —
2193    /// extends the per-arm projection family onto the [`Self::PubSub`]
2194    /// specialization axis that the pan-arm accessor's shape blends
2195    /// into a single arm-agnostic view; the pair
2196    /// (`pubsub_subject`, `store_slot`) closes the trio
2197    /// (`http_endpoint`, `pubsub_subject`, `store_slot`) so every
2198    /// payload arm now carries its own per-arm-shape post-projection
2199    /// accessor.
2200    #[must_use]
2201    pub const fn pubsub_subject(&self) -> Option<&'a str> {
2202        match *self {
2203            WitTarget::PubSub { subject } => Some(subject),
2204            WitTarget::Http { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
2205        }
2206    }
2207
2208    /// Substrate-canonical per-arm key/value-store-slot scalar accessor
2209    /// every consumer that fans on the store-shaped payload keys off —
2210    /// returns the [`Self::Store`]-arm's author-declared slot template
2211    /// verbatim as an `Option<&'a str>`, `Some(slot)` when the
2212    /// projected target is [`Self::Store { slot }`], `None` on the
2213    /// three sibling arms ([`Self::Http`] / [`Self::PubSub`] /
2214    /// [`Self::Capability`], each of which carries no
2215    /// key/value-store slot by definition).
2216    ///
2217    /// The [`Self::Store`] arm carries the WASI-key/value-accepted slot
2218    /// template (validated by [`crate::render::is_wasi_keyvalue_slot`])
2219    /// every future substrate-side store-introspecting per-`(:de,
2220    /// :para)` consumer keys off (the M4 per-Aplicacao WASI-key/value
2221    /// namespace / prefix reconciler's per-slot projection, the future
2222    /// per-store-backend routing overlay's slot-shape gate, the future
2223    /// `feira app graph --store` per-Aplicacao slot column, any future
2224    /// substrate-lifted store-shape emitter that reads a projected
2225    /// `WitTarget` in the same shape [`caixa_mesh::cilium_network_policies`]
2226    /// reads the HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today).
2227    /// Every future store-shape consumer reaches for the same typed
2228    /// dispatch this accessor exposes so the "which arm carries the
2229    /// slot scalar?" answer lives at one caixa-core edit rather than
2230    /// open-coded across per-consumer
2231    /// `if let WitTarget::Store { slot } = c.target()…`
2232    /// pattern-matches.
2233    ///
2234    /// Peer of the sibling [`Self::http_endpoint`] +
2235    /// [`Self::pubsub_subject`] per-arm accessors on the peer per-arm
2236    /// axes and of the pre-projection [`WitContract::slot`] scalar
2237    /// accessor on the raw `:contratos :slot` field-access axis — same
2238    /// "one typed dispatch on the substrate primitive, thin projections
2239    /// at each consumer" discipline extended onto the per-arm store
2240    /// post-projection axis. Closes the pre-/post-projection pair on
2241    /// the store-slot axis to match the pairs the
2242    /// [`WitContract::endpoint`] + [`Self::http_endpoint`] and
2243    /// [`WitContract::subject`] + [`Self::pubsub_subject`] surfaces
2244    /// already close on the peer HTTP-endpoint and pub-sub-subject
2245    /// axes; the substrate-side pre-/post-projection accessor family
2246    /// now spans all three payload arms as a matched trio, so any
2247    /// future arm-shape widening (a `Rest`/`Grpc` split of
2248    /// [`Self::Http`], a `Queue`-shaped peer of [`Self::Store`]) that
2249    /// lands one accessor without threading through the sibling
2250    /// pre-projection or the peer per-arm post-projection surfaces a
2251    /// compile-time exhaustiveness error at the substrate primitive,
2252    /// not a silent per-consumer split at renderer emit time.
2253    ///
2254    /// Sibling of the unified pan-arm [`Self::payload`]
2255    /// (`Option<&'a str>` for any of the three payload-carrying arms) —
2256    /// closes the per-arm projection family onto the [`Self::Store`]
2257    /// specialization axis that the pan-arm accessor's shape blends
2258    /// into a single arm-agnostic view. The trio
2259    /// (`http_endpoint`, `pubsub_subject`, `store_slot`) partitions the
2260    /// pan-arm accept-set on every payload-carrying arm: exactly one
2261    /// per-arm accessor returns `Some(payload)` and the two peers
2262    /// return `None`, and every payload-less [`Self::Capability`]
2263    /// input returns `None` on all three — the partition the sibling
2264    /// `wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`
2265    /// pin locks in load-bearing.
2266    #[must_use]
2267    pub const fn store_slot(&self) -> Option<&'a str> {
2268        match *self {
2269            WitTarget::Store { slot } => Some(slot),
2270            WitTarget::Http { .. } | WitTarget::PubSub { .. } | WitTarget::Capability => None,
2271        }
2272    }
2273
2274    /// Render this typed target as a stable human-readable label
2275    /// (`:endpoint "/charge"`, `:subject "events.x"`,
2276    /// `:slot "checkout/$order"`, or `(capability — no payload)` when
2277    /// the WIT world is a pure capability edge).
2278    ///
2279    /// Used by the [`AplicacaoSpec::validate`] duplicate-`:contratos`
2280    /// gate so the diagnostic names *which* identical edge was
2281    /// declared twice (not just which `(de, para, wit)` triple).
2282    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
2283    /// on the payload-carrying arms (`Some((field, payload)) →
2284    /// format!(":{field} {payload:?}")`) and through the lifted
2285    /// [`Self::CAPABILITY_LABEL`] const on the payload-less
2286    /// [`Self::Capability`] arm — so a future variant addition (the
2287    /// M4-and-later per-edge WIT registry may split [`Self::Http`]
2288    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
2289    /// `Queue`-shaped peer) becomes a single new match-arm on
2290    /// [`Self::payload_pair`] rather than a rewrite of this template
2291    /// (and every downstream consumer that reaches for the label
2292    /// shape: the per-edge policy resolver in M4, the `feira app
2293    /// graph` view, the operator's mesh-graph audit). Until this
2294    /// lift landed the three payload arms carried three near-identical
2295    /// per-arm `format!(":{} {…:?}", …)` invocations, and the
2296    /// [`Self::Capability`] arm carried the payload-less byte-string
2297    /// twice (once inline here, once in the pin test) — closing the
2298    /// duplication trajectory the peer [`Self::HTTP_FIELD_NAME`] /
2299    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`] (174e96a
2300    /// / 4a1e490) peer-const lifts already established for the
2301    /// payload-carrying arms.
2302    #[must_use]
2303    pub fn label(&self) -> String {
2304        match self.payload_pair() {
2305            Some((field, payload)) => format!(":{field} {payload:?}"),
2306            None => Self::CAPABILITY_LABEL.to_string(),
2307        }
2308    }
2309
2310    /// Render this typed target as the `feira app graph` per-`:contratos`
2311    /// payload-column byte-string (`endpoint=/charge`, `subject=events.x`,
2312    /// `slot=checkout/$order`, or [`Self::CAPABILITY_GRAPH_LABEL`] on the
2313    /// payload-less arm).
2314    ///
2315    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
2316    /// on the payload-carrying arms (`Some((field, payload)) →
2317    /// format!("{field}={payload}")`) and through the lifted
2318    /// [`Self::CAPABILITY_GRAPH_LABEL`] const on the payload-less
2319    /// [`Self::Capability`] arm — so a future variant addition
2320    /// (the M4-and-later per-edge WIT registry may split [`Self::Http`]
2321    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
2322    /// `Queue`-shaped peer) becomes one match-arm edit at
2323    /// [`Self::payload_pair`], propagating through this graph-verb
2324    /// projection at zero call-site cost, sibling to the peer
2325    /// [`Self::label`] duplicate-`:contratos` diagnostic emission on the
2326    /// same 4-arm dispatch.
2327    ///
2328    /// Until this lift landed the [`caixa-feira`]
2329    /// `cmd::app::GraphArgs::run` per-`:contratos` payload column
2330    /// (`caixa-feira/src/cmd/app.rs:101-112`) hand-rolled the same 4-arm
2331    /// dispatch inline, re-projecting `HTTP_FIELD_NAME` /
2332    /// `PUBSUB_FIELD_NAME` / `STORE_FIELD_NAME` under a per-arm
2333    /// `format!("{}={endpoint}", ...)` template and hard-coding
2334    /// `"(capability-only)"` as a fifth payload-less scalar with no link
2335    /// back to the paired [`WitTarget::Capability`] variant declaration.
2336    /// A future variant addition would have had to be threaded through
2337    /// both [`Self::label`] (via [`Self::payload_pair`]) *and* the graph
2338    /// verb's inline match in lockstep or the two projections would
2339    /// silently disagree on the arm-set the graph verb prints — the
2340    /// duplicate-`:contratos` diagnostic reading one shape while the
2341    /// graph verb's payload column silently dropped the new arm to
2342    /// `(capability-only)`. Lifting the graph-verb projection onto the
2343    /// same substrate-primitive [`Self::payload_pair`] dispatch closes
2344    /// the axis: both projections migrate as a unit.
2345    ///
2346    /// The `field=payload` (no colon prefix, `=` separator, no `Debug`
2347    /// quoting) shape is graph-verb-canonical — distinct from the
2348    /// sibling [`Self::label`] `":{field} {payload:?}"` shape the
2349    /// duplicate-`:contratos` diagnostic seeds (see
2350    /// [`Self::CAPABILITY_LABEL`] vs. [`Self::CAPABILITY_GRAPH_LABEL`]
2351    /// on the payload-less axis for the paired distinction).
2352    #[must_use]
2353    pub fn graph_label(&self) -> String {
2354        match self.payload_pair() {
2355            Some((field, payload)) => format!("{field}={payload}"),
2356            None => Self::CAPABILITY_GRAPH_LABEL.to_string(),
2357        }
2358    }
2359}
2360
2361/// [`std::fmt::Display`] routed through [`WitTarget::label`], so the
2362/// pretty-printed byte-string every consumer that formats a typed
2363/// payload target as user-facing text lands on (the
2364/// [`AplicacaoError::ContratoDuplicate`] diagnostic's `target:` carry
2365/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds via
2366/// [`WitTarget::label`] at aplicacao.rs:5491, the future `feira app
2367/// graph` per-`:contratos`-edge payload column that reaches the graph
2368/// verb through `format!("{target}")`, the future M4 per-edge policy
2369/// resolver's per-edge audit-log line, the operator's mesh-graph
2370/// per-edge inspection view) reaches for the same lifted
2371/// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`] /
2372/// [`WitTarget::STORE_FIELD_NAME`] / [`WitTarget::CAPABILITY_LABEL`]
2373/// const set the [`WitTarget::payload_pair`] 4-arm dispatch already
2374/// routes through — extending the three-path-convergence
2375/// (`Debug` for structural inspection, `Display` for user-facing text,
2376/// per-arm typed accessor for the canonical byte-string) discipline the
2377/// sibling M3 [`PlacementStrategy`] and M2 [`crate::supervisor::RestartStrategy`]
2378/// / [`crate::supervisor::RestartPolicy`] OTP-shape typed enums carry
2379/// onto the fourth (and only remaining) typed-shape-discriminator axis
2380/// on the caixa surface.
2381///
2382/// Pre-lift the two paths were structurally independent — every consumer
2383/// reaching for a payload byte-string past the [`WitTarget::label`]
2384/// helper had to pick between three paths ([`WitTarget::label`],
2385/// `format!("{v:?}")` on the `Debug` derive, hand-rolled per-arm
2386/// formatting through the [`WitTarget::HTTP_FIELD_NAME`] /
2387/// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`] /
2388/// [`WitTarget::CAPABILITY_LABEL`] const set), and a future consumer
2389/// that reached for `format!("{target}")` — the canonical shape every
2390/// user-facing pretty-print site on the sibling typed-enum axes already
2391/// uses — would silently land on the `Debug` derive's structural output
2392/// (`Http { endpoint: "/charge" }` — Rust struct-literal syntax) rather
2393/// than the `label()` helper's stable byte-string (`:endpoint
2394/// "/charge"` — the author-facing `:contratos` keyword form) the
2395/// substrate-side duplicate-`:contratos` gate at aplicacao.rs:5491
2396/// already threads through. The two spellings would diverge silently in
2397/// every downstream diagnostic / graph / audit line reached through
2398/// `format!` rather than through the `label()` helper. Routing
2399/// [`std::fmt::Display`] through [`WitTarget::label`] closes the third
2400/// path: every `format!("{v}")` call reaches the same
2401/// [`WitTarget::payload_pair`]-shaped byte-string the `label()` helper
2402/// and the duplicate-`:contratos` gate already route through, so a
2403/// future variant addition (the M4-and-later per-edge WIT registry may
2404/// split [`WitTarget::Http`] into `Rest` / `Grpc` peers, or extend
2405/// [`WitTarget::Store`] with a `Queue`-shaped peer) reaches every
2406/// consumer at exactly one place — the [`WitTarget::payload_pair`]
2407/// match — rather than fanning out through hand-rolled per-arm
2408/// [`std::fmt::Display`] arms.
2409///
2410/// The dispatcher-catalog identity remains unaffected — [`WitTarget`]
2411/// is the typed view returned by [`WitContract::target`], not a
2412/// closed-set discriminator enum with a gen-platform Discriminant
2413/// registration, so the `Debug` derive's structural output (which every
2414/// `{v:?}` consumer still reaches) stays distinct from the `Display`
2415/// helper's stable pretty-printed byte-string. `Debug` reveals variant
2416/// shape for structural inspection; `Display` (via `label`) reveals the
2417/// stable author-facing payload projection.
2418///
2419/// Pin tests
2420/// [`tests::wit_target_display_routes_through_label_helper`] and
2421/// [`tests::wit_target_display_matches_duplicate_contratos_diagnostic_carrier`]
2422/// assert the two paths agree byte-for-byte on every variant, so a
2423/// future variant addition or `label()` reimplementation that hand-rolls
2424/// the arms instead of delegating to [`WitTarget::payload_pair`] is a
2425/// build error visible at caixa-core test time, not a silent
2426/// per-consumer dispatch miss at diagnostic / audit / graph time.
2427impl std::fmt::Display for WitTarget<'_> {
2428    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2429        f.write_str(&self.label())
2430    }
2431}
2432
2433// ── one Aplicacao member ─────────────────────────────────────────────
2434
2435/// A Servico participating in the Aplicacao. Same shape as
2436/// `crate::supervisor::ChildSpec` but without a restart policy —
2437/// supervision is per-Servico (each member has its own
2438/// `:supervisor`), the Aplicacao orchestrates *placement*.
2439#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2440#[serde(rename_all = "camelCase")]
2441pub struct Membro {
2442    /// Member caixa's `:nome`. Resolves through the same dep
2443    /// resolution path as `crate::dep::Dep`.
2444    pub caixa: String,
2445
2446    /// Semver constraint.
2447    pub versao: String,
2448}
2449
2450impl Membro {
2451    /// Substrate-canonical per-`:membros` member-caixa `:nome` scalar
2452    /// accessor every consumer that reads the member's Servico identity
2453    /// keys off — returns the author-declared `:membros :caixa`
2454    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
2455    /// own [`String`] storage.
2456    ///
2457    /// The `:membros :caixa` slot carries the caixa `:nome` of a Servico
2458    /// participating in the Aplicacao — validated by
2459    /// [`AplicacaoSpec::validate`] to be a non-empty DNS-1123 label
2460    /// (via [`validate_membro_caixa`]), unique across the Aplicacao's
2461    /// `:membros` list, distinct from the Aplicacao's own `:nome` (via
2462    /// [`validate_no_self_membership`]) — and every downstream consumer
2463    /// that fans on the member's identity keys off this scalar (the
2464    /// [`AplicacaoSpec::validate`] `:contratos`/`:entrada` member-set
2465    /// lookup, the per-`:membros` duplicate gate's dedup key, the
2466    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency map's node
2467    /// identity, the self-membership gate, the
2468    /// [`caixa_mesh::fleet_programs`] per-member programs.yaml entry
2469    /// `name:` axis, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
2470    /// CR materializer's per-member resolver).
2471    ///
2472    /// Prior to this lift the `.caixa` byte-string was read inline at
2473    /// five caixa-core sites (the [`AplicacaoSpec::validate`] member-name
2474    /// set collector at
2475    /// `self.membros.iter().map(|m| m.caixa.as_str())`, the
2476    /// [`validate_membros`] validation-side member-caixa gate at
2477    /// `validate_membro_caixa(&m.caixa)`, the [`validate_membros`]
2478    /// per-member duplicate-gate dedup key at
2479    /// `insert_first_seen(&mut seen, m.caixa.as_str(), …)`, the
2480    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency-map seed at
2481    /// `adj.entry(m.caixa.as_str()).or_default()`, and the
2482    /// [`validate_no_self_membership`] self-loop gate at
2483    /// `m.caixa == parent_nome`) — five open-coded field-accesses that
2484    /// expressed no compile-time link back to the typed slot. Every
2485    /// caixa-mesh `metadata.name` derived from a `:membros :caixa`
2486    /// value flows through the [`caixa_mesh::fleet_programs`] per-entry
2487    /// `name:` axis, so a future extension of the `:membros :caixa`
2488    /// axis to a richer author surface — a per-cluster alias table the
2489    /// operator pins through a future `:placement`-scoped slot, a
2490    /// namespace-qualified rewrite the M4 CR materializer applies
2491    /// per-CR, a per-member overlay from the future `:membros
2492    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
2493    /// acknowledges — would have had to be threaded through every
2494    /// open-coded copy in lockstep or one consumer would silently
2495    /// disagree with the peers on which caixa a given member resolves
2496    /// to. A member-set lookup that treated the name as `"cart"` while
2497    /// the peer adjacency map treated it as `"tenant-a/cart"` would
2498    /// silently split the `:contratos` membership-lookup diagnostic from
2499    /// the cycle-detector's node identity — a two-consumer split at the
2500    /// validator far from the source `caixa.lisp` with no field naming
2501    /// the identity-drift root cause. Lifting the resolution rule to a
2502    /// typed method on the substrate primitive means every downstream
2503    /// consumer of the Aplicacao's per-`:membros` identity surface
2504    /// reaches for exactly one typed dispatch — the resolver's
2505    /// accept-set migrates as a unit on any future axis addition.
2506    ///
2507    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2508    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2509    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2510    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2511    /// destination-Servico scalar accessors — same "one typed dispatch
2512    /// on the substrate primitive, thin projections at each consumer"
2513    /// discipline extended onto the per-`:membros` member-caixa `:nome`
2514    /// byte-string axis. Named `nome()` to match the tatara-lisp
2515    /// author-surface term the field's docstring already reaches for
2516    /// ("Member caixa's `:nome`") and the peer [`crate::Caixa::nome`] /
2517    /// [`crate::dep::Dep::nome`] field-name discipline the substrate
2518    /// already carries — the accessor's name maps directly onto the
2519    /// canonical caixa-identity vocabulary rather than shadowing the
2520    /// field's storage-side `caixa` label.
2521    #[must_use]
2522    pub const fn nome(&self) -> &str {
2523        self.caixa.as_str()
2524    }
2525
2526    /// Substrate-canonical per-`:membros` member-caixa `:versao` semver-
2527    /// requirement scalar accessor every consumer that reads the
2528    /// member's version pin keys off — returns the author-declared
2529    /// `:membros :versao` byte-string verbatim as a `&str`, borrowed
2530    /// from the typed slot's own [`String`] storage.
2531    ///
2532    /// The `:membros :versao` slot carries the Cargo-shaped semver
2533    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that
2534    /// pins which release of the member-caixa the Aplicacao composes
2535    /// against — the same requirement grammar the peer `:deps :versao`
2536    /// / `:children :versao` axes carry, resolved through the shared
2537    /// [`crate::render::require_valid_versao_requirement`] cascade and
2538    /// the shared [`crate::version::parse_requirement`] parser. Every
2539    /// downstream consumer that fans on the member's version pin keys
2540    /// off this scalar (the [`validate_membros`] per-member requirement
2541    /// gate at `require_valid_versao_requirement(m.versao_requirement(),
2542    /// …)`, the [`feira app graph`] per-member `println!("    - {} {}",
2543    /// m.nome(), m.versao_requirement())` line, every future per-cluster
2544    /// version-lock overlay the operator pins through a future
2545    /// `:placement`-scoped slot, the future
2546    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-member
2547    /// version resolver, the future `feira app deploy` pipeline's
2548    /// per-member lacre BLAKE3-closure lookup).
2549    ///
2550    /// Prior to this lift the `.versao` byte-string was accessed inline
2551    /// at two `&str`-shaped sites — the [`validate_membros`]
2552    /// requirement-gate call `require_valid_versao_requirement(&m.versao,
2553    /// …)` and the `feira app graph` per-member printer's `println!(
2554    /// "    - {} {}", m.caixa, m.versao)` (caixa-feira/src/cmd/app.rs:78
2555    /// prior to this lift) — two open-coded field-accesses that expressed
2556    /// no compile-time link back to the typed slot. A future extension of
2557    /// the `:membros :versao` axis to a richer author surface (a
2558    /// per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
2559    /// flow, a lacre-projected concrete-version rewrite the operator
2560    /// materializes at CR-admission time, a future `:membros :versao-lock`
2561    /// per-cluster override slot) would have had to be threaded through
2562    /// every open-coded copy in lockstep or one consumer would silently
2563    /// disagree with the peers on which release constraint a given
2564    /// member resolves to. Lifting the resolution rule to a typed method
2565    /// on the substrate primitive means every downstream requirement-
2566    /// facing consumer reaches for exactly one typed dispatch — the
2567    /// resolver's accept-set migrates as a unit on any future axis
2568    /// addition.
2569    ///
2570    /// Sibling of the peer per-`:membros` [`Membro::nome`] (4a32abf)
2571    /// member-caixa `:nome` scalar accessor — the pair
2572    /// `(nome(), versao_requirement())` jointly projects the
2573    /// `(caixa, versao)` field pair every renderer that fans on
2574    /// per-member identity + version pin keys off, closing the last
2575    /// unlifted per-`:membros` scalar axis so every downstream
2576    /// per-`:membros` reader now routes through a typed dispatch on the
2577    /// substrate primitive. Named `versao_requirement()` rather than
2578    /// `versao()` because the field's storage-side `.versao` label is
2579    /// already the author-surface term (`:versao`); the accessor's name
2580    /// carries the semantic role — the semver *requirement* string the
2581    /// shared [`crate::version::parse_requirement`] entry-point consumes
2582    /// — so a raw field access and a typed dispatch read differently at
2583    /// every consumer site.
2584    ///
2585    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2586    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2587    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2588    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2589    /// destination-Servico scalar accessors — same "one typed dispatch
2590    /// on the substrate primitive, thin projections at each consumer"
2591    /// discipline extended onto the per-`:membros` member-`:versao`
2592    /// semver-requirement byte-string axis.
2593    #[must_use]
2594    pub const fn versao_requirement(&self) -> &str {
2595        self.versao.as_str()
2596    }
2597}
2598
2599// ── mesh-level policies ──────────────────────────────────────────────
2600
2601/// Mesh policies that apply to every `:contratos` edge unless
2602/// overridden per-edge in M4. V0 is a single global policy block.
2603#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
2604#[serde(rename_all = "camelCase")]
2605pub struct MeshPolicy {
2606    /// Per-call timeout. Authored as a duration string (`"30s"`).
2607    #[serde(
2608        default,
2609        skip_serializing_if = "Option::is_none",
2610        with = "supervisor::duration_codec"
2611    )]
2612    pub timeout: Option<Duration>,
2613
2614    /// Number of retries on transient failure. None = no retries.
2615    #[serde(default, skip_serializing_if = "Option::is_none")]
2616    pub retries: Option<u32>,
2617
2618    /// Circuit breaker config. Trips after N failures within W
2619    /// duration; closes after a cooldown.
2620    #[serde(default, skip_serializing_if = "Option::is_none")]
2621    pub circuit_breaker: Option<CircuitBreaker>,
2622
2623    /// Whether mTLS is required for every contrato. Default: true
2624    /// (sandboxing-by-default; explicit opt-out only).
2625    #[serde(default, skip_serializing_if = "Option::is_none")]
2626    pub mtls_required: Option<bool>,
2627
2628    /// Token-bucket rate limit. Authored as `"100/s"` or
2629    /// `"5000/m"`; stored as `(rate, window)`.
2630    #[serde(
2631        default,
2632        skip_serializing_if = "Option::is_none",
2633        with = "rate_limit_codec"
2634    )]
2635    pub rate_limit: Option<RateLimit>,
2636}
2637
2638impl MeshPolicy {
2639    /// True when no `:politicas` axis carries a value — every field is
2640    /// `None`. The same emptiness contract every other M2/M3 typed
2641    /// surface carries ([`crate::LimitsSpec::is_empty`],
2642    /// [`crate::BehaviorSpec::is_empty`]): renderers that overlay the
2643    /// typed slot onto a cluster artifact key off this predicate to
2644    /// decide "emit the slot" vs "skip the slot entirely", so an
2645    /// authored-but-unset `:politicas (())` round-trips to a rendered
2646    /// artifact that's structurally identical to one that omits the
2647    /// slot. Lifted as a typed predicate (rather than per-renderer
2648    /// inline `politicas.timeout.is_none() && politicas.retries.is_none()
2649    /// && …` chains) so a future axis added to `MeshPolicy` (per-edge
2650    /// :politicas overlay in M4, per-Aplicacao traffic-shaping in M5)
2651    /// is one struct-field edit + one `&& self.<axis>.is_none()` here,
2652    /// not a coordinated rewrite of every consumer that's reaching
2653    /// for the emptiness semantic.
2654    #[must_use]
2655    pub const fn is_empty(&self) -> bool {
2656        self.timeout().is_none()
2657            && self.retries().is_none()
2658            && self.circuit_breaker().is_none()
2659            && self.mtls_required().is_none()
2660            && self.rate_limit().is_none()
2661    }
2662
2663    /// Substrate-canonical cross-axis coherence predicate on the
2664    /// `:politicas` slot: does the `:circuit-breaker :window` rolling
2665    /// failure-observation interval span at least one full
2666    /// `:timeout`-bounded call?
2667    ///
2668    /// The first *cross-axis* invariant on the `:politicas` surface —
2669    /// every prior gate ([`AplicacaoSpec::validate_politicas`]'s four
2670    /// zero-floor + canonical-form + cap brackets) validates one axis
2671    /// in isolation, so a `MeshPolicy` whose axes are each individually
2672    /// well-formed could still name a structurally inert pair. The
2673    /// pair `{ timeout: 30s, circuit_breaker: { window: 10s, .. } }`
2674    /// passes every per-axis bracket (30s ≤ [`POLICY_TIMEOUT_MAX`],
2675    /// 10s ≤ [`POLICY_BREAKER_WINDOW_MAX`], both integer-millisecond,
2676    /// both above the zero floor) and is nonetheless a breaker that
2677    /// cannot trip on the failure mode it exists to catch: a call
2678    /// dispatched at t=0 is declared failed at t=30s, by which point
2679    /// the 10s window open at dispatch has rolled twice over, so no
2680    /// window can ever hold even one timeout-derived failure however
2681    /// high the call volume. Envoy's `outlier_detection.interval`
2682    /// carries the identical relation against the per-route request
2683    /// timeout; Hystrix ships the canonical ratio in its defaults
2684    /// (10s `metrics.rollingStats.timeInMilliseconds` against a 1s
2685    /// `execution.isolation.thread.timeoutInMilliseconds`).
2686    ///
2687    /// Vacuously `true` when either axis is absent — a `:politicas`
2688    /// that names only one of the pair declares no relation for the
2689    /// substrate to hold it to (`:timeout` alone is a per-call deadline
2690    /// with no breaker; `:circuit-breaker` alone is a breaker whose
2691    /// failures arrive from the transport's own error signal rather
2692    /// than from a substrate-imposed deadline, so no dispatch-to-report
2693    /// lag is knowable at author time). This is the same
2694    /// "unset means the cluster default applies, not zero" partition
2695    /// [`MeshPolicy::is_empty`] and every per-axis accessor's `None`
2696    /// arm already carry.
2697    ///
2698    /// Lifted as a typed predicate on the substrate primitive rather
2699    /// than open-coded at the validate gate so every downstream
2700    /// consumer of the pair reaches the invariant through one dispatch:
2701    /// the [`AplicacaoSpec::validate_politicas`] gate below, the future
2702    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2703    /// (MESH-COMPOSITION §III.2 #3) that must emit
2704    /// `outlier_detection.interval` and the per-route `timeout` as one
2705    /// coherent Envoy block, the future M4
2706    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
2707    /// webhook, and the future per-`:contratos`-edge `:politicas`
2708    /// override that same roadmap acknowledges — which resolves an
2709    /// *effective* pair per edge (edge-level `:timeout` against the
2710    /// Aplicacao-level `:window`, or vice versa) and so must re-check
2711    /// the relation on a pair neither axis's declaration site can see
2712    /// whole. Naming the invariant once means that resolver folds this
2713    /// predicate over its resolved pair instead of re-deriving the
2714    /// comparison, exactly as the sibling cross-slot
2715    /// [`PlacementStrategy::is_shard_keyed`] predicate names the
2716    /// `:placement`/`:shard-key` relation for its own consumers.
2717    #[must_use]
2718    pub const fn breaker_window_observes_timeout(&self) -> bool {
2719        match (self.timeout(), self.circuit_breaker()) {
2720            (Some(timeout), Some(cb)) => cb.window().as_nanos() >= timeout.as_nanos(),
2721            _ => true,
2722        }
2723    }
2724
2725    /// Substrate-canonical cross-axis coherence predicate on the
2726    /// `:politicas` slot: can the token-bucket rate declared by
2727    /// `:rate-limit` dispatch enough calls inside `:circuit-breaker
2728    /// :window` to reach `:max-failures`?
2729    ///
2730    /// The second cross-axis invariant on the `:politicas` surface —
2731    /// sibling to [`MeshPolicy::breaker_window_observes_timeout`] on
2732    /// the `(:timeout, :circuit-breaker :window)` pair, extended onto
2733    /// the `(:rate-limit, :circuit-breaker)` pair. Each axis in the
2734    /// pair is validated in isolation by the per-axis brackets in
2735    /// [`AplicacaoSpec::validate_politicas`] (rate zero-floor + cap,
2736    /// max-failures zero-floor + cap, both windows zero-floor +
2737    /// integer-millisecond + cap, rate-limit window canonical-form),
2738    /// so a `MeshPolicy` whose axes are each individually well-formed
2739    /// can still name a structurally inert pair. The pair
2740    /// `{ rate-limit: "1/h", circuit-breaker: (:max-failures 5 :window
2741    /// "10s") }` passes every per-axis bracket and is nonetheless a
2742    /// breaker that cannot trip on the failure mode it exists to
2743    /// catch: the token bucket admits `rate × (cb.window / rl.window)`
2744    /// = `1 × (10s / 3600s)` ≈ 0 calls per rolling breaker window, so
2745    /// no window can accumulate five failures however catastrophically
2746    /// the upstream is failing. Envoy's
2747    /// `outlier_detection.consecutive_5xx` paired against
2748    /// `local_rate_limit.token_bucket.max_tokens` /
2749    /// `fill_interval` carries the identical relation; every
2750    /// production playbook that pairs the two axes (Envoy, Istio, AWS
2751    /// App Mesh, Kong) recommends sizing the rate at or above the
2752    /// breaker's minimum-request-volume threshold for exactly this
2753    /// reason.
2754    ///
2755    /// The typed test is the integer inequality
2756    /// `rate × cb.window.as_nanos() >= max_failures × rl.window.as_nanos()`
2757    /// (rearranged from `rate × cb.window / rl.window >= max_failures`
2758    /// so no floating-point division mediates the comparison and so
2759    /// the sub-second `rl.window` arms — `"n/s"` = 1s — are treated
2760    /// exactly). Both multiplicands are `saturating_mul`'d into
2761    /// [`u128`] so a struct-literal `MeshPolicy` whose per-axis fields
2762    /// have not yet passed [`AplicacaoSpec::validate_politicas`]
2763    /// (e.g. `rate: u32::MAX, cb_window: Duration::MAX`) does not
2764    /// panic the predicate; a saturated pair collapses to the
2765    /// "vacuously coherent" branch the peer per-axis brackets reject
2766    /// via their own zero-floor / cap arms first.
2767    ///
2768    /// Vacuously `true` when either axis is absent — a `:politicas`
2769    /// that names only one of the pair declares no relation for the
2770    /// substrate to hold it to (`:rate-limit` alone is a per-edge
2771    /// token-bucket declaration with no failure counter to starve;
2772    /// `:circuit-breaker` alone is a rolling-window failure counter
2773    /// whose call rate is unconstrained by the substrate, so no
2774    /// bucket-derived upper bound on calls-per-window is knowable at
2775    /// author time). Same "unset means the cluster default applies,
2776    /// not zero" partition [`MeshPolicy::is_empty`] and the sibling
2777    /// [`MeshPolicy::breaker_window_observes_timeout`] predicate
2778    /// carry.
2779    ///
2780    /// Lifted as a typed predicate on the substrate primitive rather
2781    /// than open-coded at the validate gate so every downstream
2782    /// consumer of the pair reaches the invariant through one
2783    /// dispatch: the [`AplicacaoSpec::validate_politicas`] gate
2784    /// below, the future `CiliumClusterwideEnvoyConfig`
2785    /// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) that
2786    /// must emit `local_rate_limit.token_bucket.{max_tokens,
2787    /// fill_interval}` alongside `outlier_detection.consecutive_5xx`
2788    /// / `outlier_detection.interval` as one coherent Envoy block,
2789    /// the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
2790    /// materializer's admission webhook, and the future
2791    /// per-`:contratos`-edge `:politicas` override the same roadmap
2792    /// acknowledges — which resolves an *effective* pair per edge
2793    /// (edge-level `:rate-limit` against the Aplicacao-level
2794    /// `:circuit-breaker`, or vice versa) and so must re-check the
2795    /// relation on a pair neither axis's declaration site can see
2796    /// whole. Naming the invariant once means that resolver folds
2797    /// this predicate over its resolved pair instead of re-deriving
2798    /// the comparison, exactly as the sibling cross-axis
2799    /// [`MeshPolicy::breaker_window_observes_timeout`] predicate
2800    /// names the `(:timeout, :window)` relation for its own consumers.
2801    #[must_use]
2802    pub const fn breaker_can_trip_under_rate_limit(&self) -> bool {
2803        match (self.rate_limit(), self.circuit_breaker()) {
2804            (Some(rl), Some(cb)) => {
2805                let calls_per_cb_window =
2806                    (rl.rate() as u128).saturating_mul(cb.window().as_nanos());
2807                let trip_threshold_per_cb_window =
2808                    (cb.max_failures() as u128).saturating_mul(rl.window().as_nanos());
2809                calls_per_cb_window >= trip_threshold_per_cb_window
2810            }
2811            _ => true,
2812        }
2813    }
2814
2815    /// Substrate-canonical cross-axis coherence predicate on the
2816    /// `:politicas` slot: can one client's declared `:retries` all
2817    /// complete before `:circuit-breaker :max-failures` trips the
2818    /// breaker mid-retry?
2819    ///
2820    /// The third cross-axis invariant on the `:politicas` surface —
2821    /// sibling to [`MeshPolicy::breaker_window_observes_timeout`] on
2822    /// the `(:timeout, :circuit-breaker :window)` pair and
2823    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] on the
2824    /// `(:rate-limit, :circuit-breaker)` pair, extended onto the
2825    /// `(:retries, :circuit-breaker :max-failures)` pair. Each axis in
2826    /// the pair is validated in isolation by the per-axis brackets in
2827    /// [`AplicacaoSpec::validate_politicas`] (retries zero-floor + cap,
2828    /// max-failures zero-floor + cap), so a `MeshPolicy` whose axes
2829    /// are each individually well-formed can still name a
2830    /// structurally-inert retry policy. The pair
2831    /// `{ :retries 3, :circuit-breaker (:max-failures 3 :window "1s") }`
2832    /// passes every per-axis bracket and is nonetheless a retry
2833    /// policy the substrate cannot honor: one client's initial attempt
2834    /// plus three retries is four attempts, but the breaker trips on
2835    /// the third failure — the fourth attempt (the last declared
2836    /// retry) is blocked by the open breaker, so the substrate
2837    /// declared four attempts and structurally allows three.
2838    ///
2839    /// The typed test is the integer inequality
2840    /// `cb.max_failures() > retries` — the retries count is the
2841    /// *number of retry attempts beyond the initial* (Envoy's
2842    /// `retry_policy.num_retries` semantics), so a client makes at
2843    /// most `retries + 1` attempts per client call, each of which may
2844    /// fail. For the breaker to *admit* the retry policy through
2845    /// completion, its trip threshold must not be reached by one
2846    /// client's failures alone: `retries + 1 <= max_failures`,
2847    /// equivalently `retries < max_failures`, equivalently
2848    /// `max_failures > retries`. The boundary case
2849    /// `max_failures == retries + 1` accepts (the R+1th failure — the
2850    /// last retry — trips the breaker exactly as it completes; retries
2851    /// are fully executed). The strict-below case
2852    /// `max_failures <= retries` rejects (the breaker trips before
2853    /// retries exhaust, silently truncating the declared retry policy
2854    /// mid-run — the same declared-but-structurally-inert footgun the
2855    /// sibling per-axis cap arms close on the single-axis surfaces).
2856    ///
2857    /// Vacuously `true` when either axis is absent — a `:politicas`
2858    /// that names only one of the pair declares no relation for the
2859    /// substrate to hold it to (`:retries` alone is a client-retry
2860    /// policy with no failure counter to trip; `:circuit-breaker`
2861    /// alone is a failure counter whose per-client attempt count is
2862    /// unconstrained by the substrate, so no per-client saturation
2863    /// bound on failures-per-client-call is knowable at author time).
2864    /// Same "unset means the cluster default applies, not zero"
2865    /// partition [`MeshPolicy::is_empty`] and the sibling
2866    /// [`MeshPolicy::breaker_window_observes_timeout`] /
2867    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
2868    /// carry.
2869    ///
2870    /// Lifted as a typed predicate on the substrate primitive rather
2871    /// than open-coded at the validate gate so every downstream
2872    /// consumer of the pair reaches the invariant through one
2873    /// dispatch: the [`AplicacaoSpec::validate_politicas`] gate
2874    /// below, the future `CiliumClusterwideEnvoyConfig`
2875    /// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) that
2876    /// must emit `retry_policy.num_retries` alongside
2877    /// `outlier_detection.consecutive_5xx` as one coherent Envoy
2878    /// block, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
2879    /// materializer's admission webhook, and the future
2880    /// per-`:contratos`-edge `:politicas` override the same roadmap
2881    /// acknowledges — which resolves an *effective* pair per edge
2882    /// (edge-level `:retries` against the Aplicacao-level
2883    /// `:circuit-breaker`, or vice versa) and so must re-check the
2884    /// relation on a pair neither axis's declaration site can see
2885    /// whole. Naming the invariant once means that resolver folds
2886    /// this predicate over its resolved pair instead of re-deriving
2887    /// the comparison, exactly as the sibling cross-axis
2888    /// [`MeshPolicy::breaker_window_observes_timeout`] and
2889    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
2890    /// name the `(:timeout, :window)` and `(:rate-limit,
2891    /// :circuit-breaker)` relations for their own consumers.
2892    #[must_use]
2893    pub const fn retries_fit_under_breaker_trip_threshold(&self) -> bool {
2894        match (self.retries(), self.circuit_breaker()) {
2895            (Some(retries), Some(cb)) => cb.max_failures() > retries,
2896            _ => true,
2897        }
2898    }
2899
2900    /// Substrate-canonical cross-axis coherence predicate on the
2901    /// `:politicas` slot: does the `:rate-limit` token-bucket capacity
2902    /// admit one client's full `:retries + 1` attempt burst inside a
2903    /// single refill window?
2904    ///
2905    /// The fourth cross-axis invariant on the `:politicas` surface,
2906    /// completing the triangle of pairs the three sibling gates carve
2907    /// out — sibling to [`MeshPolicy::breaker_window_observes_timeout`]
2908    /// on the `(:timeout, :circuit-breaker :window)` pair,
2909    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] on the
2910    /// `(:rate-limit, :circuit-breaker)` pair, and
2911    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`] on the
2912    /// `(:retries, :circuit-breaker :max-failures)` pair, extended onto
2913    /// the `(:retries, :rate-limit)` pair — the last cross-axis relation
2914    /// among the three scalar `:politicas` axes (`:retries`,
2915    /// `:rate-limit`, `:circuit-breaker`) whose axis-triple defines the
2916    /// coherence surface every production overlay (Envoy, Istio,
2917    /// resilience4j, AWS App Mesh) resolves as one block. Each axis in
2918    /// the pair is validated in isolation by the per-axis brackets in
2919    /// [`AplicacaoSpec::validate_politicas`] (retries zero-floor + cap,
2920    /// rate zero-floor + cap, window canonical-form), so a `MeshPolicy`
2921    /// whose axes are each individually well-formed can still name a
2922    /// structurally-truncated retry policy the rate limiter refuses to
2923    /// admit. The pair `{ :retries 5, :rate-limit "3/s" }` passes every
2924    /// per-axis bracket and is nonetheless a retry policy the substrate
2925    /// cannot honor: one client's initial attempt plus five retries is
2926    /// six attempts, but the token bucket admits at most three tokens
2927    /// per one-second refill window, so the fourth attempt onward is
2928    /// blocked by the rate limiter itself — the substrate declared six
2929    /// attempts and structurally allows three. Envoy's
2930    /// `local_rate_limit.token_bucket.max_tokens` paired against
2931    /// `retry_policy.num_retries` carries the identical relation; every
2932    /// production playbook that pairs the two axes recommends sizing
2933    /// the bucket capacity above any single client's retry budget so
2934    /// the retry policy is not silently truncated by the same rate
2935    /// limiter it feeds through.
2936    ///
2937    /// The typed test is the integer inequality
2938    /// `rl.rate() >= retries + 1` — the retries count is the *number of
2939    /// retry attempts beyond the initial* (Envoy's
2940    /// `retry_policy.num_retries` semantics), so a client makes at most
2941    /// `retries + 1` attempts per client call, each of which consumes
2942    /// one token from the local rate-limit bucket. For the bucket to
2943    /// *admit* the retry burst without dropping tokens, its capacity
2944    /// must not be reached by one client's attempts alone:
2945    /// `retries + 1 <= rate`, equivalently `rate >= retries + 1`. The
2946    /// boundary case `rate == retries + 1` accepts (the bucket admits
2947    /// exactly one client's full retry sequence per refill window —
2948    /// retries fully executed). The strict-below case `rate <= retries`
2949    /// rejects (the bucket exhausts before retries complete, silently
2950    /// truncating the declared retry policy mid-run — the same
2951    /// declared-but-structurally-inert footgun the sibling per-axis cap
2952    /// arms close on the single-axis surfaces). The equivalent
2953    /// coherent-direction form `rl.rate() > retries` sidesteps the
2954    /// `retries + 1` addition entirely (both `rate` and `retries` are
2955    /// `u32`; the `>` comparison is total on the type with no overflow
2956    /// against past-the-guard struct-literal `retries` values a caller
2957    /// might pass before `validate` runs), matching the peer
2958    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`] direct-
2959    /// `>`-comparison discipline on the sibling
2960    /// `(:retries, :max-failures)` pair.
2961    ///
2962    /// Vacuously `true` when either axis is absent — a `:politicas`
2963    /// that names only one of the pair declares no relation for the
2964    /// substrate to hold it to (`:retries` alone is a client-retry
2965    /// policy with no rate limiter to saturate; `:rate-limit` alone is
2966    /// a token-bucket declaration whose per-client attempt count is
2967    /// unconstrained by the substrate, so no per-client saturation
2968    /// bound on tokens-per-client-call is knowable at author time).
2969    /// Same "unset means the cluster default applies, not zero"
2970    /// partition [`MeshPolicy::is_empty`] and the three sibling
2971    /// cross-axis predicates
2972    /// ([`MeshPolicy::breaker_window_observes_timeout`],
2973    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`],
2974    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]) carry.
2975    ///
2976    /// Lifted as a typed predicate on the substrate primitive rather
2977    /// than open-coded at the validate gate so every downstream
2978    /// consumer of the pair reaches the invariant through one dispatch:
2979    /// the [`AplicacaoSpec::validate_politicas`] gate below, the future
2980    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2981    /// (MESH-COMPOSITION §III.2 #3) that must emit
2982    /// `local_rate_limit.token_bucket.max_tokens` alongside
2983    /// `retry_policy.num_retries` as one coherent Envoy block, the
2984    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
2985    /// admission webhook, and the future per-`:contratos`-edge
2986    /// `:politicas` override the same roadmap acknowledges — which
2987    /// resolves an *effective* pair per edge (edge-level `:retries`
2988    /// against the Aplicacao-level `:rate-limit`, or vice versa) and
2989    /// so must re-check the relation on a pair neither axis's
2990    /// declaration site can see whole. Naming the invariant once means
2991    /// that resolver folds this predicate over its resolved pair
2992    /// instead of re-deriving the comparison, exactly as the three
2993    /// sibling cross-axis predicates name the
2994    /// `(:timeout, :window)` / `(:rate-limit, :circuit-breaker)` /
2995    /// `(:retries, :max-failures)` relations for their own consumers,
2996    /// closing the fourth and last cross-axis relation on the scalar
2997    /// `:politicas` axis-triple.
2998    #[must_use]
2999    pub const fn rate_limit_admits_retry_burst(&self) -> bool {
3000        match (self.retries(), self.rate_limit()) {
3001            (Some(retries), Some(rl)) => rl.rate() > retries,
3002            _ => true,
3003        }
3004    }
3005
3006    /// Substrate-canonical fold over the four cross-axis coherence
3007    /// predicates on the `:politicas` slot — returns the *first*
3008    /// cross-axis violation (as its [`AplicacaoError`] variant) in the
3009    /// canonical "more-foundational-cross-axis first" ordering
3010    /// [`MeshPolicy::breaker_window_observes_timeout`] on
3011    /// `(:timeout, :circuit-breaker :window)` →
3012    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] on
3013    /// `(:rate-limit, :circuit-breaker)` →
3014    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`] on
3015    /// `(:retries, :circuit-breaker :max-failures)` →
3016    /// [`MeshPolicy::rate_limit_admits_retry_burst`] on `(:retries,
3017    /// :rate-limit)`. Returns `None` when every cross-axis relation
3018    /// holds (the vacuous shape [`MeshPolicy::is_empty`] and the fully-
3019    /// coherent shape both land here).
3020    ///
3021    /// The ordering discipline this method encodes was open-coded four
3022    /// times at [`AplicacaoSpec::validate_politicas`] — each cross-axis
3023    /// gate was an `if !<predicate>() { let <a> = self.<axis>().expect(
3024    /// "cross-axis gate fires only when :<axis> is present"); let <b>
3025    /// = self.<axis>().expect(…); return Err(<variant>) }` block whose
3026    /// axis-fetch step depended on the predicate having just returned
3027    /// `false` (structurally guaranteed both paired axes are `Some`,
3028    /// but the compiler cannot see through the predicate body, so
3029    /// every arm re-called the accessor with `.expect(…)` to reach
3030    /// the axis it just tested). Two unsound consequences: (1) the
3031    /// validate gate carried eight `.expect(…)` panic call sites the
3032    /// predicate contract already forbids on every well-typed input
3033    /// but the type system does not enforce; (2) the
3034    /// "which-cross-axis-fires-first-when-two-apply" contract lived
3035    /// twice — once in each predicate's own doc comments and once at
3036    /// the validate call site's four-arm cascade. Lifting the four-arm
3037    /// cascade onto this substrate primitive collapses both
3038    /// duplications: the predicate contract and the axis-fetch step
3039    /// live in the same body (no `.expect(…)` — the pattern match at
3040    /// each arm rebinds the paired axes so their `Some` presence is a
3041    /// compile-time property of the local scope), and the ordering
3042    /// discipline lives once at the top of the primitive rather than
3043    /// scattered across four sibling doc-comment blocks that must
3044    /// stay in lockstep.
3045    ///
3046    /// Every downstream cross-axis consumer (the [`AplicacaoSpec::
3047    /// validate_politicas`] gate below, the future M4 `mesh.pleme.io/
3048    /// v1alpha1/Aplicacao` CR materializer's admission webhook, the
3049    /// per-`:contratos`-edge `:politicas` override MESH-COMPOSITION
3050    /// §III.2 #3 acknowledges — the last of which resolves an
3051    /// *effective* per-edge pair and must emit *the same* diagnostic
3052    /// on the same paired-axis input as `feira build`) reaches through
3053    /// one call rather than re-inlining the four pattern-matches +
3054    /// accessor-fetches + variant-constructions + ordering-cascade.
3055    ///
3056    /// Returns owned copies of every axis carried into the diagnostic:
3057    /// [`Duration`] and [`u32`] are `Copy`, so no `String` allocation
3058    /// occurs on the happy path when no violation fires.
3059    #[must_use]
3060    pub fn first_cross_axis_violation(&self) -> Option<AplicacaoError> {
3061        // Ordering discipline this fold encodes matches the four
3062        // per-arm predicate doc comments' pairwise-ordering contract:
3063        // window-below-timeout wins over every arm that names `:rate-
3064        // limit` or `:retries` (its diagnostic is more self-locating —
3065        // the pair is a per-call-deadline invariant every synchronous
3066        // edge carries whether or not `:rate-limit`/`:retries` is
3067        // declared); the starve arm wins over the two retry arms (its
3068        // diagnostic reasons across the token-bucket-vs-breaker
3069        // relation, an axis the retry arms do not touch); the
3070        // retries-saturate arm wins over the retries-burst arm (its
3071        // diagnostic reasons across the per-client-vs-breaker
3072        // relation, which carries whether or not `:rate-limit` is
3073        // declared). Each arm rebinds the paired axes through the
3074        // pattern match, so the `.expect(…)` panics the four-block
3075        // cascade at `validate_politicas` carried collapse to no-op
3076        // pattern rebindings the compiler statically proves exhaust.
3077        if let (Some(t), Some(cb)) = (self.timeout(), self.circuit_breaker())
3078            && !self.breaker_window_observes_timeout()
3079        {
3080            return Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
3081                window: cb.window(),
3082                timeout: t,
3083            });
3084        }
3085        if let (Some(rl), Some(cb)) = (self.rate_limit(), self.circuit_breaker())
3086            && !self.breaker_can_trip_under_rate_limit()
3087        {
3088            return Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
3089                rate: rl.rate(),
3090                rl_window: rl.window(),
3091                max_failures: cb.max_failures(),
3092                cb_window: cb.window(),
3093            });
3094        }
3095        if let (Some(retries), Some(cb)) = (self.retries(), self.circuit_breaker())
3096            && !self.retries_fit_under_breaker_trip_threshold()
3097        {
3098            return Some(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
3099                retries,
3100                max_failures: cb.max_failures(),
3101            });
3102        }
3103        if let (Some(retries), Some(rl)) = (self.retries(), self.rate_limit())
3104            && !self.rate_limit_admits_retry_burst()
3105        {
3106            return Some(AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
3107                retries,
3108                rate: rl.rate(),
3109            });
3110        }
3111        None
3112    }
3113
3114    /// Substrate-canonical compound entry gate over the whole
3115    /// `:politicas` typed slot — folds every per-axis bracket
3116    /// (`:timeout` / `:retries` / `:circuit-breaker :max-failures` /
3117    /// `:circuit-breaker :window` / `:rate-limit` rate / `:rate-limit`
3118    /// window-canonical-form) *and* the compound cross-axis fold
3119    /// [`MeshPolicy::first_cross_axis_violation`] into one call every
3120    /// consumer of a validated [`MeshPolicy`] reaches through.
3121    ///
3122    /// Returns the first violation as its [`AplicacaoError`] variant,
3123    /// or `Ok(())` when every per-axis value lies in its accept-set and
3124    /// every cross-axis relation holds. Per-axis brackets run strictly
3125    /// before the cross-axis fold — the sibling
3126    /// [`AplicacaoSpec::validate_politicas`] gate carried the same
3127    /// ordering discipline for the same reason: a per-axis
3128    /// structurally-invalid value (a `Duration::ZERO` `:window`, an
3129    /// above-cap `:rate-limit` rate) surfaces its own self-locating
3130    /// diagnostic first, ahead of any cross-axis arm that would send
3131    /// the author to reconcile two values one of which is not a
3132    /// meaningful window at all. Within the per-axis phase, arms fire
3133    /// in the same slot-order the peer per-axis brackets carry
3134    /// (`:timeout` → `:retries` → `:circuit-breaker` → `:rate-limit`,
3135    /// each internally ordered zero-floor before canonical-form before
3136    /// cap by [`crate::render::require_positive_bounded_u32`] /
3137    /// [`crate::render::require_positive_canonical_bounded_duration`]);
3138    /// within the cross-axis phase, arms fire in the canonical
3139    /// more-foundational-cross-axis-first ordering
3140    /// [`MeshPolicy::first_cross_axis_violation`] encodes.
3141    ///
3142    /// Lifted as a typed method on the substrate primitive so every
3143    /// downstream consumer of a validated [`MeshPolicy`] reaches the
3144    /// invariant through one dispatch: the
3145    /// [`AplicacaoSpec::validate_politicas`] gate below (whose whole
3146    /// body collapses to `self.politicas().validate()`), the future
3147    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
3148    /// admission webhook, the future per-`:contratos`-edge `:politicas`
3149    /// override MESH-COMPOSITION §III.2 #3 acknowledges — the last of
3150    /// which resolves an *effective* per-edge [`MeshPolicy`] and must
3151    /// emit *the same* diagnostic on the same input as `feira build`.
3152    /// Naming the compound gate once on the substrate primitive means
3153    /// every downstream consumer inherits both the per-axis brackets
3154    /// *and* the cross-axis fold through one call, rather than
3155    /// re-inlining the four-per-axis + one-cross-axis cascade in
3156    /// lockstep with `validate_politicas`.
3157    ///
3158    /// Peer of the per-kind compound entry gates lifted at
3159    /// [`crate::render::require_aplicacao_view`] (7242d45 / 3aefefb),
3160    /// [`crate::render::require_supervisor_view`] (8d8a5c3), and
3161    /// [`crate::render::require_v0_servico_shape`] on the per-Caixa
3162    /// layout axis, and the sibling compound cross-axis fold
3163    /// [`MeshPolicy::first_cross_axis_violation`] on the same
3164    /// `:politicas` axis — extended here onto the per-slot per-axis +
3165    /// cross-axis compound entry gate that folds both surfaces.
3166    pub fn validate(&self) -> Result<(), AplicacaoError> {
3167        if let Some(t) = self.timeout() {
3168            crate::render::require_positive_canonical_bounded_duration(
3169                t,
3170                POLICY_TIMEOUT_MAX,
3171                || AplicacaoError::PolicyTimeoutZero,
3172                AplicacaoError::policy_timeout_not_canonical,
3173                AplicacaoError::policy_timeout_exceeds_cap,
3174            )?;
3175        }
3176        if let Some(r) = self.retries() {
3177            crate::render::require_positive_bounded_u32(
3178                r,
3179                POLICY_RETRIES_MAX,
3180                || AplicacaoError::PolicyRetriesZero,
3181                AplicacaoError::policy_retries_exceeds_cap,
3182            )?;
3183        }
3184        if let Some(cb) = self.circuit_breaker() {
3185            crate::render::require_positive_bounded_u32(
3186                cb.max_failures(),
3187                POLICY_BREAKER_MAX_FAILURES_MAX,
3188                || AplicacaoError::PolicyBreakerZeroFailures,
3189                AplicacaoError::policy_breaker_max_failures_exceeds_cap,
3190            )?;
3191            crate::render::require_positive_canonical_bounded_duration(
3192                cb.window(),
3193                POLICY_BREAKER_WINDOW_MAX,
3194                || AplicacaoError::PolicyBreakerZeroWindow,
3195                AplicacaoError::policy_breaker_window_not_canonical,
3196                AplicacaoError::policy_breaker_window_exceeds_cap,
3197            )?;
3198        }
3199        if let Some(rl) = self.rate_limit() {
3200            crate::render::require_positive_bounded_u32(
3201                rl.rate(),
3202                POLICY_RATE_LIMIT_MAX,
3203                || AplicacaoError::PolicyRateLimitZero,
3204                AplicacaoError::policy_rate_limit_exceeds_cap,
3205            )?;
3206            if rl.canonical_unit().is_none() {
3207                return Err(AplicacaoError::policy_rate_limit_window_not_canonical(
3208                    rl.window(),
3209                ));
3210            }
3211        }
3212        if let Some(err) = self.first_cross_axis_violation() {
3213            return Err(err);
3214        }
3215        Ok(())
3216    }
3217
3218    /// Substrate-canonical per-`:politicas` `:timeout` Gateway-API-mesh
3219    /// per-call-deadline scalar accessor every consumer of the
3220    /// Aplicacao's Gateway API v1.x per-rule request-timeout keys off —
3221    /// returns the author-declared `:politicas :timeout` typed
3222    /// [`Duration`] verbatim as an `Option<Duration>`, copied out of the
3223    /// typed slot's own `Option<Duration>` storage (`Option<Duration>`
3224    /// is `Copy`, so the accessor returns by value; no borrow of
3225    /// `&self` past the call). `None` when the slot is absent (the
3226    /// "cluster default applies — typically the gateway class's
3227    /// implementation-side per-request wall-clock cap" arm caixa-mesh's
3228    /// `timeout_overlay` builder documents at caixa-mesh/src/lib.rs:2911
3229    /// — [`MeshPolicy::is_empty`]'s `timeout.is_none()` arm reads this
3230    /// predicate too, so an authored-but-unset `:politicas (:timeout ())`
3231    /// round-trips to a rendered `HTTPRoute` structurally identical to
3232    /// one that omits the slot).
3233    ///
3234    /// The `:politicas :timeout` slot carries the "no infinite blocking"
3235    /// per-call deadline contract (MESH-COMPOSITION §V CSE invariant) —
3236    /// the typed slot's `Option<Duration>` accept-set (zero-floor
3237    /// rejected through [`AplicacaoError::PolicyTimeoutZero`], canonical-
3238    /// form rejected through [`AplicacaoError::PolicyTimeoutNotCanonical`],
3239    /// upper-bounded by [`POLICY_TIMEOUT_MAX`]) maps onto the Gateway API
3240    /// v1.x `HTTPRoute.spec.rules[].timeouts.request` per-rule request-
3241    /// deadline scalar the caixa-mesh `timeout_overlay` builder writes.
3242    /// Every downstream consumer that reads the per-call cap keys off
3243    /// this scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
3244    /// renderers key off to decide "emit :politicas overlay" vs "skip
3245    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
3246    /// `timeouts.request` builder at caixa-mesh/src/lib.rs:2979 that
3247    /// fans the deadline into every rule via
3248    /// [`crate::render::single_field_overlay`], the future M4 per-
3249    /// Aplicacao Gateway API reconciler materialization pass, the
3250    /// future per-`:contratos`-edge timeout-override overlay the
3251    /// MESH-COMPOSITION §III.2 roadmap acknowledges).
3252    ///
3253    /// Prior to this lift the `.timeout` field was accessed inline at
3254    /// two sites — [`MeshPolicy::is_empty`]'s `self.timeout.is_none()`
3255    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.timeout,
3256    /// …)` call — two open-coded field-accesses that expressed no
3257    /// compile-time link back to the typed slot. A future extension of
3258    /// the `:politicas :timeout` axis to a richer author surface — a
3259    /// per-`:contratos`-edge timeout override the operator pins through
3260    /// a future `:contratos :timeout` slot the MESH-COMPOSITION §III.2
3261    /// roadmap acknowledges, a per-cluster timeout-default overlay the
3262    /// M4 CR materializer resolves per-CR, a split of the single
3263    /// per-call `Duration` into a richer `{request, backendRequest}`
3264    /// pair once the Gateway API's per-rule `timeouts` block grows the
3265    /// upstream-facing backendRequest arm alongside the client-facing
3266    /// request arm — would have had to be threaded through both open-
3267    /// coded copies in lockstep or the emptiness predicate and the
3268    /// caixa-mesh emit path would silently disagree on which per-call
3269    /// deadline a given [`MeshPolicy`] resolves to (a `:politicas` block
3270    /// whose only axis is a `Some :timeout` would satisfy `is_empty()
3271    /// == false` while the renderer's overlay-emit path silently read
3272    /// a drifted other value, or vice versa: an author's `:timeout
3273    /// "30s"` would omit the `HTTPRoute` `timeouts.request` block while
3274    /// the emptiness predicate still classified the policy as non-
3275    /// empty, and every `kubectl -n tatara-system get httproute -o yaml
3276    /// | grep -A2 timeouts` audit would land on a route whose author's
3277    /// typed slot value silently vanished at the renderer layer).
3278    /// Lifting the resolution to a typed method on the substrate
3279    /// primitive means every downstream consumer of the Aplicacao's
3280    /// per-`:politicas` deadline surface reaches for exactly one typed
3281    /// dispatch — the resolver's accept-set migrates as a unit on any
3282    /// future axis addition.
3283    ///
3284    /// Third `Option<Copy-T>`-return accessor on the M3 mesh-slot
3285    /// family (sibling of the peer per-`:politicas`
3286    /// [`MeshPolicy::retries`] bdfb399 `Option<u32>` accessor and the
3287    /// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1
3288    /// `Option<bool>` accessor — same "one typed dispatch on the
3289    /// substrate primitive, thin projections at each consumer"
3290    /// discipline extended onto the peer per-`:politicas` typed-
3291    /// [`Duration`] optional-scalar axis; closes the "optional per-slot
3292    /// numeric-Copy-T scalar" projection pattern the sibling
3293    /// `Option<u32>` / `Option<bool>` lifts opened, since every
3294    /// remaining `MeshPolicy` axis (`circuit_breaker: Option<CircuitBreaker>`,
3295    /// `rate_limit: Option<RateLimit>`) carries a struct payload rather
3296    /// than a scalar). Named `timeout()` to match the storage field's
3297    /// name; the accessor's identity maps onto the canonical MESH-
3298    /// COMPOSITION §III.2 vocabulary the slot's docstring already carries.
3299    #[must_use]
3300    pub const fn timeout(&self) -> Option<Duration> {
3301        self.timeout
3302    }
3303
3304    /// Substrate-canonical per-`:politicas` `:retries` transient-failure-
3305    /// retry-budget scalar accessor every consumer of the Aplicacao's
3306    /// Gateway API v1.x per-rule retry-cap keys off — returns the
3307    /// author-declared `:politicas :retries` typed `u32` verbatim as an
3308    /// `Option<u32>`, copied out of the typed slot's own `Option<u32>`
3309    /// storage (`Option<u32>` is `Copy`, so the accessor returns by
3310    /// value; no borrow of `&self` past the call). `None` when the slot
3311    /// is absent (the "cluster default applies — typically 'no retries
3312    /// beyond a single dispatch attempt'" arm the caixa-mesh
3313    /// `retry_overlay` builder documents at caixa-mesh/src/lib.rs:2985
3314    /// — [`MeshPolicy::is_empty`]'s `retries.is_none()` arm reads
3315    /// this predicate too, so an authored-but-unset `:politicas
3316    /// (:retries ())` round-trips to a rendered `HTTPRoute` structurally
3317    /// identical to one that omits the slot).
3318    ///
3319    /// The `:politicas :retries` slot carries the "transient failure
3320    /// retry cap" contract (MESH-COMPOSITION §III.2 #2) — the typed
3321    /// slot's `Option<u32>` accept-set (lower-bounded by 1 through
3322    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
3323    /// [`POLICY_RETRIES_MAX`]) maps onto the Gateway API v1.x
3324    /// `HTTPRoute.spec.rules[].retry.attempts` per-rule retry-attempt-
3325    /// count scalar the caixa-mesh `retry_overlay` builder writes.
3326    /// Every downstream consumer that reads the retry cap keys off this
3327    /// scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
3328    /// renderers key off to decide "emit :politicas overlay" vs "skip
3329    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
3330    /// `retry.attempts` builder at caixa-mesh/src/lib.rs:3007 that fans
3331    /// the value into every rule via [`crate::render::single_field_overlay`],
3332    /// the future M4 per-Aplicacao Gateway API reconciler
3333    /// materialization pass, the future per-`:contratos`-edge retry-
3334    /// override overlay the MESH-COMPOSITION §III.2 #2 roadmap
3335    /// acknowledges).
3336    ///
3337    /// Prior to this lift the `.retries` field was accessed inline at
3338    /// two sites — [`MeshPolicy::is_empty`]'s `self.retries.is_none()`
3339    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.retries,
3340    /// …)` call — two open-coded field-accesses that expressed no
3341    /// compile-time link back to the typed slot. A future extension of
3342    /// the `:politicas :retries` axis to a richer author surface — a
3343    /// per-`:contratos`-edge retry override the operator pins through a
3344    /// future `:contratos :retries` slot, a per-cluster retry-default
3345    /// overlay the M4 CR materializer resolves per-CR, a promotion of
3346    /// the plain `u32` attempt-count to a richer `{attempts, codes,
3347    /// backoff}` sub-block once the Gateway API grows the peer
3348    /// `retry.codes` / `retry.backoff` axes — would have had to be
3349    /// threaded through both open-coded copies in lockstep or the
3350    /// emptiness predicate and the caixa-mesh emit path would silently
3351    /// disagree on which retry budget a given [`MeshPolicy`] resolves to
3352    /// (a `:politicas` block whose only axis is a `Some :retries` would
3353    /// satisfy `is_empty() == false` while the renderer's overlay-emit
3354    /// path silently read a drifted other value, or vice versa: an
3355    /// author's `:retries 3` would omit the `HTTPRoute` `retry.attempts`
3356    /// block while the emptiness predicate still classified the policy
3357    /// as non-empty). Lifting the resolution to a typed method on the
3358    /// substrate primitive means every downstream consumer of the
3359    /// Aplicacao's per-`:politicas` retry surface reaches for exactly
3360    /// one typed dispatch — the resolver's accept-set migrates as a
3361    /// unit on any future axis addition.
3362    ///
3363    /// Second `Option<Copy-T>`-return accessor on the M3 mesh-slot
3364    /// family (sibling of the peer per-`:politicas`
3365    /// [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` accessor —
3366    /// same "one typed dispatch on the substrate primitive, thin
3367    /// projections at each consumer" discipline extended onto the
3368    /// peer per-`:politicas` typed-`u32` optional-scalar axis; opens
3369    /// the "optional per-slot numeric-Copy-T scalar" projection pattern
3370    /// the sibling per-`:politicas` `:timeout` (Option<Duration>) /
3371    /// per-`CircuitBreaker` `:max-failures` / `:window` future lifts
3372    /// fold on). Named `retries()` to match the storage field's name;
3373    /// the accessor's identity maps onto the canonical MESH-COMPOSITION
3374    /// §III.2 vocabulary the slot's docstring already carries.
3375    #[must_use]
3376    pub const fn retries(&self) -> Option<u32> {
3377        self.retries
3378    }
3379
3380    /// Substrate-canonical per-`:politicas` `:mtls-required` mTLS-
3381    /// enforcement-toggle scalar accessor every consumer of the
3382    /// Aplicacao's Cilium-mesh L4 mutual-authentication policy keys off
3383    /// — returns the author-declared `:politicas :mtls-required` typed
3384    /// bool verbatim as an `Option<bool>`, copied out of the typed
3385    /// slot's own `Option<bool>` storage (`Option<bool>` is `Copy`, so
3386    /// the accessor returns by value; no borrow of `&self` past the
3387    /// call). `None` when the slot is absent (the "cluster default
3388    /// applies — typically 'disabled' cluster-wide" arm the caixa-mesh
3389    /// `mtls_overlay` builder documents at caixa-mesh/src/lib.rs:2540
3390    /// — [`MeshPolicy::is_empty`]'s `mtls_required.is_none()` arm reads
3391    /// this predicate too, so an authored-but-unset `:politicas
3392    /// (:mtls-required ())` round-trips to a rendered
3393    /// `CiliumNetworkPolicy` structurally identical to one that omits
3394    /// the slot).
3395    ///
3396    /// The `:politicas :mtls-required` slot carries the "explicit opt-
3397    /// out only, sandboxing-by-default" mTLS-enforcement toggle
3398    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's three-way
3399    /// `{None, Some(true), Some(false)}` accept-set maps onto the
3400    /// Cilium `authentication.mode` bijection through
3401    /// [`crate::cilium_auth_mode`]: `Some(true) → "required"` (mTLS
3402    /// handshake enforced), `Some(false) → "disabled"` (handshake
3403    /// skipped — the debug-edge opt-out), `None` → omit the block
3404    /// (cluster default applies). Every downstream consumer that
3405    /// reads the toggle keys off this scalar (the
3406    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
3407    /// off to decide "emit :politicas overlay" vs "skip entirely", the
3408    /// caixa-mesh per-`(:de, :para)` CNP `mtls_overlay` builder at
3409    /// caixa-mesh/src/lib.rs:2549 that fans the toggle into every
3410    /// ingress rule via [`crate::render::single_field_overlay`], the
3411    /// future M4 per-Aplicacao Cilium `authentication.mode` reconciler
3412    /// materialization pass, the future per-`:contratos`-edge mTLS
3413    /// override MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3414    ///
3415    /// Prior to this lift the `.mtls_required` field was accessed
3416    /// inline at two sites — [`MeshPolicy::is_empty`]'s
3417    /// `self.mtls_required.is_none()` arm and caixa-mesh's
3418    /// `single_field_overlay(spec.politicas.mtls_required, …)` call —
3419    /// two open-coded field-accesses that expressed no compile-time
3420    /// link back to the typed slot. A future extension of the
3421    /// `:politicas :mtls-required` axis to a richer author surface —
3422    /// a per-`:contratos`-edge mTLS override the operator pins through
3423    /// a future `:contratos :mtls` slot the MESH-COMPOSITION §III.2
3424    /// #3 roadmap acknowledges, a per-cluster mTLS-default overlay the
3425    /// M4 CR materializer resolves per-CR, a three-valued
3426    /// `{None, Some(true), Some(false), Some(Optional)}` promotion
3427    /// once Cilium's `authentication.mode` grows an `"optional"` arm —
3428    /// would have had to be threaded through both open-coded copies in
3429    /// lockstep or the emptiness predicate and the caixa-mesh emit
3430    /// path would silently disagree on which toggle a given
3431    /// [`MeshPolicy`] resolves to (a `:politicas` block whose only
3432    /// axis is a `Some`
3433    /// `:mtls-required` would satisfy `is_empty() == false` while the
3434    /// renderer's overlay-emit path silently read a drifted other
3435    /// value, or vice versa). Lifting the resolution to a typed method
3436    /// on the substrate primitive means every downstream consumer of
3437    /// the Aplicacao's per-`:politicas` mTLS-toggle surface reaches
3438    /// for exactly one typed dispatch — the resolver's accept-set
3439    /// migrates as a unit on any future axis addition.
3440    ///
3441    /// First `Option<Copy-T>`-return accessor on the M3 mesh-slot
3442    /// family (peer of the sibling per-`:placement`
3443    /// [`Placement::shard_key`] 7cd2a28 `Option<&str>` accessor —
3444    /// same "one typed dispatch on the substrate primitive, thin
3445    /// projections at each consumer" discipline extended onto the
3446    /// peer per-`:politicas` typed-bool optional-scalar axis; opens
3447    /// the "optional per-slot Copy-T scalar" projection pattern the
3448    /// sibling per-`:politicas` `:retries` (Option<u32>) /
3449    /// `:timeout` (Option<Duration>) future lifts fold on). Named
3450    /// `mtls_required()` to match the storage field's name; the
3451    /// accessor's identity maps onto the canonical MESH-COMPOSITION
3452    /// §III.2 vocabulary the slot's docstring already carries.
3453    #[must_use]
3454    pub const fn mtls_required(&self) -> Option<bool> {
3455        self.mtls_required
3456    }
3457
3458    /// Substrate-canonical per-`:politicas` `:rate-limit` Envoy-
3459    /// `local_rate_limit`-mesh token-bucket-declaration scalar
3460    /// accessor every consumer of the Aplicacao's per-`:politicas`
3461    /// per-`(rate, window)` rate-limit surface keys off — returns the
3462    /// author-declared `:politicas :rate-limit` typed [`RateLimit`]
3463    /// verbatim as an `Option<RateLimit>`, copied out of the typed
3464    /// slot's own `Option<RateLimit>` storage ([`RateLimit`] is
3465    /// `Copy`, so the accessor returns by value; no borrow of `&self`
3466    /// past the call). `None` when the slot is absent (the "cluster
3467    /// default applies — typically 'no per-Aplicacao rate declaration,
3468    /// gateway-class per-listener default applies'" arm the future
3469    /// caixa-mesh `local_rate_limit_overlay` emitter MESH-COMPOSITION
3470    /// §III.2 #3 names — [`MeshPolicy::is_empty`]'s
3471    /// `rate_limit().is_none()` arm reads this predicate too, so an
3472    /// authored-but-unset `:politicas (:rate-limit ())` round-trips
3473    /// to a rendered `CiliumClusterwideEnvoyConfig` structurally
3474    /// identical to one that omits the slot).
3475    ///
3476    /// The `:politicas :rate-limit` slot carries the "per-Aplicacao
3477    /// token-bucket rate declaration" contract (MESH-COMPOSITION
3478    /// §III.2 #3) — the typed slot's `Option<RateLimit>` accept-set
3479    /// (rate lower-bounded by 1 through
3480    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
3481    /// [`POLICY_RATE_LIMIT_MAX`], window canonically bijected to the
3482    /// three-unit `{"s", "m", "h"}` [`rate_limit_codec`] table through
3483    /// [`is_canonical_rate_limit_window`]) maps onto the Envoy
3484    /// `local_rate_limit.token_bucket.{max_tokens, fill_interval}`
3485    /// bijection the future `CiliumClusterwideEnvoyConfig` per-
3486    /// `:politicas` overlay emits. Every downstream consumer that
3487    /// reads the rate declaration keys off this scalar (the
3488    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
3489    /// off to decide "emit :politicas overlay" vs "skip entirely", the
3490    /// [`AplicacaoSpec::validate_politicas`] per-value-shape gate that
3491    /// brackets `rl.rate` against [`POLICY_RATE_LIMIT_MAX`] and pins
3492    /// `rl.window` against [`is_canonical_rate_limit_window`], the
3493    /// future M4 per-Aplicacao Envoy reconciler materialization pass,
3494    /// the future per-`:contratos`-edge rate-limit override the
3495    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3496    ///
3497    /// Prior to this lift the `.rate_limit` field was accessed inline
3498    /// at two sites — [`MeshPolicy::is_empty`]'s
3499    /// `self.rate_limit.is_none()` arm and the `validate_politicas`
3500    /// gate's `if let Some(rl) = &p.rate_limit` bind — two open-coded
3501    /// field-accesses that expressed no compile-time link back to the
3502    /// typed slot. A future extension of the `:politicas :rate-limit`
3503    /// axis to a richer author surface — a per-`:contratos`-edge
3504    /// rate-limit override the operator pins through a future
3505    /// `:contratos :rate-limit` slot the MESH-COMPOSITION §III.2 #3
3506    /// roadmap acknowledges, a per-cluster rate-limit-default overlay
3507    /// the M4 CR materializer resolves per-CR, a promotion of the
3508    /// plain `(rate, window)` scalar pair to a richer
3509    /// `{rate, window, burst, key}` sub-block once Envoy's
3510    /// `local_rate_limit` grows the peer `burst_size` /
3511    /// `descriptor_key` axes — would have had to be threaded through
3512    /// both open-coded copies in lockstep or the emptiness predicate
3513    /// and the validate gate would silently disagree on which rate
3514    /// declaration a given [`MeshPolicy`] resolves to (a `:politicas`
3515    /// block whose only axis is a `Some :rate-limit` would satisfy
3516    /// `is_empty() == false` while the validate path silently read a
3517    /// drifted other value, or vice versa: an author's
3518    /// `:rate-limit "100/s"` would omit the value-shape gate while the
3519    /// emptiness predicate still classified the policy as non-empty).
3520    /// Lifting the resolution to a typed method on the substrate
3521    /// primitive means every downstream consumer of the Aplicacao's
3522    /// per-`:politicas` rate-limit surface reaches for exactly one
3523    /// typed dispatch — the resolver's accept-set migrates as a unit
3524    /// on any future axis addition.
3525    ///
3526    /// First `Option<Copy-composite-T>`-return accessor on the M3
3527    /// mesh-slot family — closes the last un-lifted per-`:politicas`
3528    /// scalar-value axis. Peer of the sibling per-`:politicas`
3529    /// [`MeshPolicy::timeout`] (7073d0f) / [`MeshPolicy::retries`]
3530    /// (bdfb399) / [`MeshPolicy::mtls_required`] (c0110f1)
3531    /// `Option<Copy-T>` accessors on the primitive-Copy axes — same
3532    /// "one typed dispatch on the substrate primitive, thin
3533    /// projections at each consumer" discipline extended onto the
3534    /// peer per-`:politicas` composite-Copy shape (`RateLimit` is
3535    /// `#[derive(Copy)]`; peer of [`CircuitBreaker`] which lives
3536    /// behind [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
3537    /// sub-accessors rather than a top-level accessor because
3538    /// consumers reach for the axes not the aggregate). Named
3539    /// `rate_limit()` to match the storage field's name; the
3540    /// accessor's identity maps onto the canonical MESH-COMPOSITION
3541    /// §III.2 vocabulary the slot's docstring already carries.
3542    #[must_use]
3543    pub const fn rate_limit(&self) -> Option<RateLimit> {
3544        self.rate_limit
3545    }
3546
3547    /// Substrate-canonical per-`:politicas` `:circuit-breaker`
3548    /// Envoy-`outlier_detection`-mesh consecutive-failure-ejection-
3549    /// declaration scalar accessor every consumer of the Aplicacao's
3550    /// per-`:politicas` breaker declaration keys off — returns the
3551    /// author-declared `:politicas :circuit-breaker` typed
3552    /// [`CircuitBreaker`] verbatim as an `Option<CircuitBreaker>`,
3553    /// copied out of the typed slot's own `Option<CircuitBreaker>`
3554    /// storage ([`CircuitBreaker`] is `Copy`, so the accessor returns
3555    /// by value; no borrow of `&self` past the call). `None` when the
3556    /// slot is absent (the "cluster default applies — typically 'no
3557    /// per-Aplicacao breaker declaration, gateway-class per-listener
3558    /// default applies'" arm the future caixa-mesh
3559    /// `outlier_detection_overlay` emitter MESH-COMPOSITION §III.2 #3
3560    /// names — [`MeshPolicy::is_empty`]'s `circuit_breaker().is_none()`
3561    /// arm reads this predicate too, so an authored-but-unset
3562    /// `:politicas (:circuit-breaker ())` round-trips to a rendered
3563    /// `CiliumClusterwideEnvoyConfig` structurally identical to one
3564    /// that omits the slot).
3565    ///
3566    /// The `:politicas :circuit-breaker` slot carries the
3567    /// "per-Aplicacao consecutive-transient-failure trip declaration"
3568    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
3569    /// `Option<CircuitBreaker>` accept-set (per-`:max-failures`
3570    /// zero-floor rejected through
3571    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
3572    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]; per-`:window` zero-floor
3573    /// rejected through [`AplicacaoError::PolicyBreakerZeroWindow`],
3574    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`],
3575    /// canonical-form pinned through
3576    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`]) maps onto
3577    /// the Envoy `outlier_detection.{consecutive_5xx, interval}`
3578    /// bijection the future `CiliumClusterwideEnvoyConfig`
3579    /// per-`:politicas` overlay emits. Every downstream consumer that
3580    /// reads the breaker declaration keys off this scalar (the
3581    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
3582    /// off to decide "emit :politicas overlay" vs "skip entirely", the
3583    /// [`AplicacaoSpec::validate_politicas`] per-sub-struct-axis gate
3584    /// that brackets `cb.max_failures()` against
3585    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`] and `cb.window()` against
3586    /// [`POLICY_BREAKER_WINDOW_MAX`] via
3587    /// [`crate::render::require_positive_canonical_bounded_duration`],
3588    /// the future M4 per-Aplicacao Envoy reconciler materialization
3589    /// pass, the future per-`:contratos`-edge breaker override the
3590    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3591    ///
3592    /// Prior to this lift the `.circuit_breaker` field was accessed
3593    /// inline at two sites — [`MeshPolicy::is_empty`]'s
3594    /// `self.circuit_breaker.is_none()` arm and the
3595    /// `validate_politicas` gate's `if let Some(cb) = &p.circuit_breaker`
3596    /// bind — two open-coded field-accesses that expressed no
3597    /// compile-time link back to the typed slot. A future extension of
3598    /// the `:politicas :circuit-breaker` axis to a richer author
3599    /// surface — a per-`:contratos`-edge breaker override the operator
3600    /// pins through a future `:contratos :circuit-breaker` slot the
3601    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-cluster
3602    /// breaker-default overlay the M4 CR materializer resolves per-CR,
3603    /// a promotion of the plain `(max_failures, window)` scalar pair to
3604    /// a richer `{max_failures, window, base_ejection_time, max_ejection_percent}`
3605    /// sub-block once Envoy's `outlier_detection` grows the peer
3606    /// ejection-percentage / ejection-time axes — would have had to be
3607    /// threaded through both open-coded copies in lockstep or the
3608    /// emptiness predicate and the validate gate would silently
3609    /// disagree on which breaker declaration a given [`MeshPolicy`]
3610    /// resolves to (a `:politicas` block whose only axis is a
3611    /// `Some :circuit-breaker` would satisfy `is_empty() == false` while
3612    /// the validate path silently read a drifted other value, or vice
3613    /// versa: an author's `(:circuit-breaker (:max-failures 5 :window
3614    /// "60s"))` would omit the value-shape gate while the emptiness
3615    /// predicate still classified the policy as non-empty). Lifting
3616    /// the resolution to a typed method on the substrate primitive
3617    /// means every downstream consumer of the Aplicacao's
3618    /// per-`:politicas` breaker surface reaches for exactly one typed
3619    /// dispatch — the resolver's accept-set migrates as a unit on any
3620    /// future axis addition.
3621    ///
3622    /// Second `Option<Copy-composite-T>`-return accessor on the M3
3623    /// mesh-slot family (sibling of the peer per-`:politicas`
3624    /// [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>` accessor
3625    /// on the same composite-Copy shape, and of the sibling per-
3626    /// `:politicas` [`MeshPolicy::timeout`] 7073d0f
3627    /// `Option<Duration>` / [`MeshPolicy::retries`] bdfb399
3628    /// `Option<u32>` / [`MeshPolicy::mtls_required`] c0110f1
3629    /// `Option<bool>` accessors on the sibling primitive-Copy axes —
3630    /// same "one typed dispatch on the substrate primitive, thin
3631    /// projections at each consumer" discipline extended onto the last
3632    /// unlifted per-`:politicas` scalar-value axis (the composite-Copy
3633    /// `Option<CircuitBreaker>` arm). Named `circuit_breaker()` to
3634    /// match the storage field's name; the accessor's identity maps
3635    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3636    /// docstring already carries. Closes the last unlifted
3637    /// [`MeshPolicy`] accessor axis so every downstream per-`:politicas`
3638    /// reader now routes through a typed dispatch on the substrate
3639    /// primitive.
3640    #[must_use]
3641    pub const fn circuit_breaker(&self) -> Option<CircuitBreaker> {
3642        self.circuit_breaker
3643    }
3644}
3645
3646#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
3647#[serde(rename_all = "camelCase")]
3648pub struct CircuitBreaker {
3649    pub max_failures: u32,
3650    #[serde(with = "supervisor::duration_codec_required")]
3651    pub window: Duration,
3652}
3653
3654impl CircuitBreaker {
3655    /// Substrate-canonical per-`:politicas :circuit-breaker`
3656    /// `:max-failures` Envoy-outlier-detection trip-threshold scalar
3657    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3658    /// breaker trip-count keys off — returns the author-declared
3659    /// `:politicas :circuit-breaker :max-failures` typed `u32` verbatim,
3660    /// copied out of the typed slot's own `u32` storage (`u32` is `Copy`,
3661    /// so the accessor returns by value; no borrow of `&self` past the
3662    /// call). Non-optional (the surrounding `Option<CircuitBreaker>` is
3663    /// the "slot present?" projection at the parent [`MeshPolicy::circuit_breaker`]
3664    /// axis; a `CircuitBreaker` past pattern-match is definitionally
3665    /// present, and its `:max-failures` field carries the trip count as a
3666    /// required-axis scalar).
3667    ///
3668    /// The `:politicas :circuit-breaker :max-failures` axis carries the
3669    /// "consecutive-transient-failure trip threshold" contract
3670    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's `u32` accept-set
3671    /// (zero-floor rejected through
3672    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
3673    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]) maps onto the Envoy
3674    /// `outlier_detection.consecutive_5xx` per-cluster ejection-threshold
3675    /// scalar (equivalently the future `CiliumClusterwideEnvoyConfig`
3676    /// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 acknowledges).
3677    /// Every downstream consumer that reads the trip threshold keys off
3678    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3679    /// cap bracket at caixa-core/src/aplicacao.rs:4022 that gates on the
3680    /// canonical `require_positive_bounded_u32` helper, the future M4
3681    /// per-Aplicacao Envoy config reconciler materialization pass, the
3682    /// future per-`:contratos`-edge breaker-override overlay the
3683    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3684    ///
3685    /// Prior to this lift the `.max_failures` field was accessed inline
3686    /// at one production site — [`AplicacaoSpec::validate_politicas`]'s
3687    /// `require_positive_bounded_u32(cb.max_failures, …)` call — one
3688    /// open-coded field-access that expressed no compile-time link back
3689    /// to the typed sub-struct axis. A future extension of the
3690    /// `:max-failures` axis to a richer author surface — a
3691    /// per-`:contratos`-edge breaker override the operator pins through a
3692    /// future `:contratos :max-failures` slot the MESH-COMPOSITION §III.2
3693    /// #3 roadmap acknowledges, a per-cluster max-failures-default
3694    /// overlay the M4 CR materializer resolves per-CR, a promotion of the
3695    /// plain `u32` trip count to a richer
3696    /// `{consecutive_5xx, consecutive_gateway_failure, consecutive_local_origin_failure}`
3697    /// tuple once Envoy's `outlier_detection` block's peer axes come into
3698    /// scope, a per-Envoy-cluster minimum-request-volume gate before the
3699    /// count arms — would have had to be threaded through every open-
3700    /// coded copy in lockstep or the validate gate and the future M4
3701    /// emit path would silently disagree on which trip threshold a given
3702    /// [`CircuitBreaker`] resolves to (an author's `:max-failures 5`
3703    /// would satisfy validate while the emit path silently read a drifted
3704    /// other value, or vice versa: a validated typed slot would land at
3705    /// the emit boundary as a no-op breaker whose trip threshold is
3706    /// structurally never reached). Lifting the resolution to a typed
3707    /// method on the substrate primitive means every downstream consumer
3708    /// of the Aplicacao's per-`:politicas :circuit-breaker`
3709    /// trip-threshold surface reaches for exactly one typed dispatch —
3710    /// the resolver's accept-set migrates as a unit on any future axis
3711    /// addition.
3712    ///
3713    /// First sub-struct scalar accessor on the M3 mesh-slot family
3714    /// (opens the "per-`CircuitBreaker` / per-`RateLimit` required-axis
3715    /// scalar" projection pattern the sibling `CircuitBreaker::window` /
3716    /// `RateLimit::rate` / `RateLimit::window` future lifts fold on —
3717    /// closes the last unlifted per-`:politicas` scalar-value axis after
3718    /// the c0110f1 / bdfb399 / 7073d0f trajectory closed every scalar-
3719    /// shaped axis on the parent [`MeshPolicy`] optional-slot surface).
3720    /// Same "one typed dispatch on the substrate primitive, thin
3721    /// projections at each consumer" discipline the peer
3722    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
3723    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
3724    /// [`Membro::versao_requirement`] (a40b0e3),
3725    /// [`Entrada::destination`] (6db982c) accessors carry on their
3726    /// respective per-mesh-slot-atom scalar-value axes, extended onto the
3727    /// per-sub-struct required-`u32` axis. Named `max_failures()` to
3728    /// match the storage field's name; the accessor's identity maps onto
3729    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3730    /// docstring already carries.
3731    #[must_use]
3732    pub const fn max_failures(&self) -> u32 {
3733        self.max_failures
3734    }
3735
3736    /// Substrate-canonical per-`:politicas :circuit-breaker` `:window`
3737    /// Envoy-outlier-detection rolling-observation-interval scalar
3738    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3739    /// breaker rolling-window duration keys off — returns the
3740    /// author-declared `:politicas :circuit-breaker :window` typed
3741    /// `Duration` verbatim, copied out of the typed slot's own
3742    /// `Duration` storage (`Duration` is `Copy`, so the accessor returns
3743    /// by value; no borrow of `&self` past the call). Non-optional (the
3744    /// surrounding `Option<CircuitBreaker>` is the "slot present?"
3745    /// projection at the parent [`MeshPolicy::circuit_breaker`] axis; a
3746    /// `CircuitBreaker` past pattern-match is definitionally present,
3747    /// and its `:window` field carries the rolling-observation interval
3748    /// as a required-axis scalar).
3749    ///
3750    /// The `:politicas :circuit-breaker :window` axis carries the
3751    /// "consecutive-transient-failure rolling-observation interval"
3752    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
3753    /// `Duration` accept-set (zero-floor rejected through
3754    /// [`AplicacaoError::PolicyBreakerZeroWindow`], sub-millisecond
3755    /// residue rejected through
3756    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`],
3757    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`]) maps onto the
3758    /// Envoy `outlier_detection.interval` per-cluster
3759    /// ejection-observation-interval scalar (equivalently the future
3760    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3761    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3762    /// consumer that reads the rolling-observation interval keys off
3763    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3764    /// integer-millisecond canonical-form + cap bracket at
3765    /// caixa-core/src/aplicacao.rs:4121 that gates on the canonical
3766    /// [`crate::render::require_positive_canonical_bounded_duration`]
3767    /// helper, the future M4 per-Aplicacao Envoy config reconciler
3768    /// materialization pass, the future per-`:contratos`-edge
3769    /// breaker-override overlay the MESH-COMPOSITION §III.2 #3 roadmap
3770    /// acknowledges).
3771    ///
3772    /// Prior to this lift the `.window` field was accessed inline at
3773    /// one production site — [`AplicacaoSpec::validate_politicas`]'s
3774    /// `require_positive_canonical_bounded_duration(cb.window, …)`
3775    /// call — one open-coded field-access that expressed no compile-
3776    /// time link back to the typed sub-struct axis. A future extension
3777    /// of the `:window` axis to a richer author surface — a
3778    /// per-`:contratos`-edge window override the operator pins through
3779    /// a future `:contratos :window` slot the MESH-COMPOSITION §III.2
3780    /// #3 roadmap acknowledges, a per-cluster window-default overlay
3781    /// the M4 CR materializer resolves per-CR, a promotion of the plain
3782    /// `Duration` observation interval to a richer
3783    /// `{interval, base_ejection_time, max_ejection_percent}` tuple
3784    /// once Envoy's `outlier_detection` block's peer axes come into
3785    /// scope, a per-Envoy-cluster minimum-request-volume gate before
3786    /// the window arms — would have had to be threaded through every
3787    /// open-coded copy in lockstep or the validate gate and the future
3788    /// M4 emit path would silently disagree on which observation
3789    /// interval a given [`CircuitBreaker`] resolves to (an author's
3790    /// `:window "60s"` would satisfy validate while the emit path
3791    /// silently read a drifted other value, or vice versa: a validated
3792    /// typed slot would land at the emit boundary as a breaker whose
3793    /// observation window is structurally so wide that no realistic
3794    /// failure-rate shape can trip it). Lifting the resolution to a
3795    /// typed method on the substrate primitive means every downstream
3796    /// consumer of the Aplicacao's per-`:politicas :circuit-breaker`
3797    /// observation-window surface reaches for exactly one typed
3798    /// dispatch — the resolver's accept-set migrates as a unit on any
3799    /// future axis addition.
3800    ///
3801    /// Second sub-struct scalar accessor on the M3 mesh-slot family —
3802    /// sibling in shape to the just-landed [`CircuitBreaker::max_failures`]
3803    /// (3a74062) required-`u32` accessor on the peer per-`CircuitBreaker`
3804    /// required-axis, extended onto the per-sub-struct required-`Duration`
3805    /// axis; closes the last unlifted per-`CircuitBreaker` scalar-value
3806    /// axis. Same "one typed dispatch on the substrate primitive, thin
3807    /// projections at each consumer" discipline the peer
3808    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
3809    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
3810    /// [`Membro::versao_requirement`] (a40b0e3),
3811    /// [`Entrada::destination`] (6db982c) accessors carry on their
3812    /// respective per-mesh-slot-atom scalar-value axes, extended onto
3813    /// the per-sub-struct required-`Duration` axis. Named `window()` to
3814    /// match the storage field's name; the accessor's identity maps onto
3815    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3816    /// docstring already carries.
3817    #[must_use]
3818    pub const fn window(&self) -> Duration {
3819        self.window
3820    }
3821}
3822
3823#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3824pub struct RateLimit {
3825    /// Requests per window.
3826    pub rate: u32,
3827    /// Window duration.
3828    pub window: Duration,
3829}
3830
3831impl RateLimit {
3832    /// Substrate-canonical per-`:politicas :rate-limit` `:rate`
3833    /// Envoy-local-rate-limit-mesh token-bucket capacity scalar accessor
3834    /// every consumer of the Aplicacao's per-`:contratos`-edge
3835    /// rate-limit-bucket capacity keys off — returns the author-declared
3836    /// `:politicas :rate-limit` typed `u32` verbatim, copied out of the
3837    /// typed slot's own `u32` storage (`u32` is `Copy`, so the accessor
3838    /// returns by value; no borrow of `&self` past the call). Non-optional
3839    /// (the surrounding `Option<RateLimit>` is the "slot present?"
3840    /// projection at the parent [`MeshPolicy::rate_limit`] axis; a
3841    /// `RateLimit` past pattern-match is definitionally present, and its
3842    /// `:rate` field carries the token-bucket capacity as a required-axis
3843    /// scalar).
3844    ///
3845    /// The `:politicas :rate-limit` `:rate` axis carries the
3846    /// "token-bucket capacity" contract (MESH-COMPOSITION §III.2 #3) —
3847    /// the typed slot's `u32` accept-set (zero-floor rejected through
3848    /// [`AplicacaoError::PolicyRateLimitZero`], upper-bounded by
3849    /// [`POLICY_RATE_LIMIT_MAX`]) maps onto the Envoy
3850    /// `local_rate_limit.token_bucket.max_tokens` per-cluster
3851    /// token-bucket-capacity scalar (equivalently the future
3852    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3853    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3854    /// consumer that reads the token-bucket capacity keys off this
3855    /// scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3856    /// cap bracket that gates on the canonical
3857    /// [`crate::render::require_positive_bounded_u32`] helper, the
3858    /// [`rate_limit_codec::render`] `Duration → unit` projection that
3859    /// emits the `<n>/<s|m|h>` author surface, the future M4
3860    /// per-Aplicacao Envoy config reconciler materialization pass, the
3861    /// future per-`:contratos`-edge rate-limit-override overlay the
3862    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3863    ///
3864    /// Prior to this lift the `.rate` field was accessed inline at three
3865    /// production sites — [`AplicacaoSpec::validate_politicas`]'s
3866    /// `require_positive_bounded_u32(rl.rate, …)` call, and the two
3867    /// [`rate_limit_codec::render`] format-arm arms (canonical-window
3868    /// `format!("{}/{unit}", rl.rate)` and non-canonical-window
3869    /// `format!("{}/{}s", rl.rate, …)` fallback). Three open-coded
3870    /// field-accesses that expressed no compile-time link back to the
3871    /// typed sub-struct axis. A future extension of the `:rate` axis
3872    /// to a richer author surface — a per-`:contratos`-edge rate
3873    /// override the operator pins through a future `:contratos :rate`
3874    /// slot the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a
3875    /// per-cluster rate-default overlay the M4 CR materializer resolves
3876    /// per-CR, a promotion of the plain `u32` token capacity to a
3877    /// richer `{max_tokens, tokens_per_fill}` tuple once Envoy's
3878    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
3879    /// axis comes into scope, a per-Envoy-cluster descriptor-key gate
3880    /// before the token arms — would have had to be threaded through
3881    /// every open-coded copy in lockstep or the validate gate, the
3882    /// codec's render path, and the future M4 emit path would silently
3883    /// disagree on which token capacity a given [`RateLimit`] resolves
3884    /// to (an author's `:rate-limit "100/s"` would satisfy validate
3885    /// while the render / emit paths silently read a drifted other
3886    /// value, or vice versa: a validated typed slot would land at the
3887    /// emit boundary as a no-op limiter whose token capacity is
3888    /// structurally so high that no realistic per-edge traffic shape
3889    /// can drain it). Lifting the resolution to a typed method on the
3890    /// substrate primitive means every downstream consumer of the
3891    /// Aplicacao's per-`:politicas :rate-limit` token-capacity surface
3892    /// reaches for exactly one typed dispatch — the resolver's
3893    /// accept-set migrates as a unit on any future axis addition.
3894    ///
3895    /// First sub-struct scalar accessor on the `RateLimit` axis — sibling
3896    /// in shape to the peer per-`CircuitBreaker`
3897    /// [`CircuitBreaker::max_failures`] (3a74062) required-`u32` accessor
3898    /// on the peer per-sub-struct required-axis, extended onto the
3899    /// per-`RateLimit` required-`u32` axis; opens the "per-`RateLimit`
3900    /// required-axis scalar" projection pattern the sibling
3901    /// [`RateLimit::window`] future lift folds on. Same "one typed
3902    /// dispatch on the substrate primitive, thin projections at each
3903    /// consumer" discipline the peer [`WitContract::source`] /
3904    /// [`WitContract::destination`] (7f0fd43), [`WitContract::world_ref`]
3905    /// (0804823), [`Membro::nome`] (4a32abf),
3906    /// [`Membro::versao_requirement`] (a40b0e3),
3907    /// [`Entrada::destination`] (6db982c),
3908    /// [`CircuitBreaker::max_failures`] (3a74062),
3909    /// [`CircuitBreaker::window`] (373957f) accessors carry on their
3910    /// respective per-mesh-slot-atom scalar-value axes. Named `rate()`
3911    /// to match the storage field's name; the accessor's identity maps
3912    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3913    /// docstring already carries.
3914    #[must_use]
3915    pub const fn rate(&self) -> u32 {
3916        self.rate
3917    }
3918
3919    /// Substrate-canonical per-`:politicas :rate-limit` `:window`
3920    /// Envoy-local-rate-limit-mesh token-bucket refill-period scalar
3921    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3922    /// rate-limit-bucket refill period keys off — returns the
3923    /// author-declared `:politicas :rate-limit` typed `Duration`
3924    /// verbatim, copied out of the typed slot's own `Duration` storage
3925    /// (`Duration` is `Copy`, so the accessor returns by value; no
3926    /// borrow of `&self` past the call). Non-optional (the surrounding
3927    /// `Option<RateLimit>` is the "slot present?" projection at the
3928    /// parent [`MeshPolicy::rate_limit`] axis; a `RateLimit` past
3929    /// pattern-match is definitionally present, and its `:window`
3930    /// field carries the token-bucket refill period as a required-axis
3931    /// scalar).
3932    ///
3933    /// The `:politicas :rate-limit` `:window` axis carries the
3934    /// "token-bucket refill period" contract (MESH-COMPOSITION §III.2 #3)
3935    /// — the typed slot's `Duration` accept-set (constrained to the
3936    /// three canonical windows `{1s, 60s, 3600s}` the
3937    /// [`RATE_LIMIT_UNIT_TABLE`] lifts, rejected off-set through
3938    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]) maps
3939    /// onto the Envoy `local_rate_limit.token_bucket.fill_interval`
3940    /// per-cluster token-bucket-refill-period scalar (equivalently the
3941    /// future `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3942    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3943    /// consumer that reads the token-bucket refill period keys off
3944    /// this scalar (the [`AplicacaoSpec::validate_politicas`]
3945    /// canonical-window gate that keys off
3946    /// [`is_canonical_rate_limit_window`], the
3947    /// [`rate_limit_codec::render`] `Duration → unit` projection that
3948    /// emits the `<n>/<s|m|h>` author surface — canonical arm via
3949    /// [`rate_limit_window_unit`] and non-canonical fallback via
3950    /// `.as_secs()`, the future M4 per-Aplicacao Envoy config
3951    /// reconciler materialization pass, the future per-`:contratos`-
3952    /// edge rate-limit-override overlay the MESH-COMPOSITION §III.2 #3
3953    /// roadmap acknowledges).
3954    ///
3955    /// Prior to this lift the `.window` field was accessed inline at
3956    /// three production sites — [`AplicacaoSpec::validate_politicas`]'s
3957    /// `is_canonical_rate_limit_window(rl.window)` shape-gate call
3958    /// plus the sibling [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]
3959    /// error-payload construction on refusal, and the two
3960    /// [`rate_limit_codec::render`] arms
3961    /// (canonical-window `rate_limit_window_unit(rl.window)` dispatch
3962    /// and non-canonical-window `rl.window.as_secs()` fallback). Three
3963    /// open-coded field-accesses that expressed no compile-time link
3964    /// back to the typed sub-struct axis. A future extension of the
3965    /// `:window` axis to a richer author surface — a per-`:contratos`-
3966    /// edge window override the operator pins through a future
3967    /// `:contratos :window` slot the MESH-COMPOSITION §III.2 #3 roadmap
3968    /// acknowledges, a per-cluster window-default overlay the M4 CR
3969    /// materializer resolves per-CR, a promotion of the plain
3970    /// `Duration` refill period to a richer
3971    /// `{fill_interval, tokens_per_fill}` tuple once Envoy's
3972    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
3973    /// axis comes into scope, an addition of a `"d"` day suffix once
3974    /// Envoy's `rate_limit_action` grows daily-bucket support — would
3975    /// have had to be threaded through every open-coded copy in
3976    /// lockstep or the validate gate, the codec's render path, and
3977    /// the future M4 emit path would silently disagree on which
3978    /// refill period a given [`RateLimit`] resolves to (an author's
3979    /// `:rate-limit "100/s"` would satisfy validate while the render
3980    /// / emit paths silently read a drifted other value, or vice
3981    /// versa: a validated typed slot would land at the emit boundary
3982    /// as a limiter whose refill period is structurally so long that
3983    /// no realistic per-edge traffic shape stays inside the token
3984    /// budget). Lifting the resolution to a typed method on the
3985    /// substrate primitive means every downstream consumer of the
3986    /// Aplicacao's per-`:politicas :rate-limit` refill-period surface
3987    /// reaches for exactly one typed dispatch — the resolver's
3988    /// accept-set migrates as a unit on any future axis addition.
3989    ///
3990    /// Second sub-struct scalar accessor on the `RateLimit` axis —
3991    /// sibling in shape to the just-landed [`RateLimit::rate`]
3992    /// (7f81a60) required-`u32` accessor on the peer per-`RateLimit`
3993    /// required-axis, extended onto the per-sub-struct
3994    /// required-`Duration` axis; closes the last unlifted
3995    /// per-`RateLimit` scalar-value axis (the M3 mesh-slot family's
3996    /// per-sub-struct accessor coverage is now complete across both
3997    /// `CircuitBreaker` and `RateLimit`). Same "one typed dispatch on
3998    /// the substrate primitive, thin projections at each consumer"
3999    /// discipline the peer [`CircuitBreaker::max_failures`] (3a74062),
4000    /// [`CircuitBreaker::window`] (373957f), [`RateLimit::rate`]
4001    /// (7f81a60), [`WitContract::source`] / [`WitContract::destination`]
4002    /// (7f0fd43), [`WitContract::world_ref`] (0804823),
4003    /// [`Membro::nome`] (4a32abf),
4004    /// [`Membro::versao_requirement`] (a40b0e3),
4005    /// [`Entrada::destination`] (6db982c) accessors carry on their
4006    /// respective per-mesh-slot-atom scalar-value axes. Named
4007    /// `window()` to match the storage field's name; the accessor's
4008    /// identity maps onto the canonical MESH-COMPOSITION §III.2
4009    /// vocabulary the slot's docstring already carries.
4010    #[must_use]
4011    pub const fn window(&self) -> Duration {
4012        self.window
4013    }
4014
4015    /// Recognize this rate-limit's `:window` as a canonical
4016    /// [`RateLimitUnit`] arm — `Some(RateLimitUnit)` when the window
4017    /// exactly matches one of the three closed-set arm-Durations
4018    /// (`1s` / `60s` / `3600s`), `None` when the window carries a
4019    /// non-canonical magnitude the codec's round-trip would break on
4020    /// (sub-second residue, or a second-magnitude outside the set
4021    /// [`RateLimitUnit::ALL`] enumerates).
4022    ///
4023    /// Every validated [`RateLimit`] past [`AplicacaoSpec::validate_politicas`]
4024    /// returns `Some` here — the validate gate's
4025    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`] arm
4026    /// rejects every window this accessor returns `None` on. Downstream
4027    /// consumers past validate (the codec's [`rate_limit_codec::render`]
4028    /// path, the future M4 per-Aplicacao Envoy config reconciler's
4029    /// materialization pass, the future per-`:contratos`-edge rate-limit-
4030    /// override overlay the MESH-COMPOSITION §III.2 #3 roadmap
4031    /// acknowledges) that read the typed unit off a validated slot can
4032    /// pattern-match on the returned `Some` without re-checking
4033    /// canonicality at the consumer layer — the typed enum surface is
4034    /// the load-bearing carrier of the canonicality invariant.
4035    ///
4036    /// Preferred over the free [`is_canonical_rate_limit_window`]
4037    /// module-private helper at any call site that has the typed
4038    /// [`RateLimit`] in hand (the codec's `render` arm at
4039    /// [`rate_limit_codec::render`], the validate gate's canonical-form
4040    /// arm in [`AplicacaoSpec::validate_politicas`], any future
4041    /// per-`:contratos` edge-override overlay resolver): those consumers
4042    /// reach for the typed enum without going through the
4043    /// `.window()` scalar-projection layer, and get the enum value
4044    /// directly (which the codec's render arm can then format via
4045    /// [`RateLimitUnit::as_suffix`] / [`std::fmt::Display`]). Same
4046    /// "typed sub-struct scalar accessor, one dispatch on the substrate
4047    /// primitive" discipline the sibling [`RateLimit::rate`] and
4048    /// [`RateLimit::window`] accessors carry on the peer per-sub-struct
4049    /// scalar-value axes, extended onto the per-`RateLimit` typed-unit
4050    /// projection axis (the third scalar accessor on the [`RateLimit`]
4051    /// axis, first typed-enum-return projection).
4052    ///
4053    /// `pub const fn` — the typed-`RateLimit`-projection dispatch onto
4054    /// the canonical [`RateLimitUnit`] arm now carries the same
4055    /// `const`-eval-surface posture the sibling `pub const fn`
4056    /// [`Self::rate`] / [`Self::window`] scalar-projection accessors on
4057    /// this typed sub-struct already carry, composing through the
4058    /// peer-lifted `pub const fn` [`RateLimitUnit::from_window`]
4059    /// reverse-resolver in `const` context. Any downstream substrate-
4060    /// side `const`-context consumer of the typed unit (a module-scope
4061    /// `const _:() = assert!(matches!(rl.canonical_unit(), Some(RateLimitUnit::Second)))`
4062    /// invariant pin on a typed fixture, a future M4 admission-webhook
4063    /// `const fn` per-`:politicas :rate-limit :window` canonical-arm
4064    /// resolver over a typed [`RateLimit`], any future `const fn`
4065    /// per-`:contratos`-edge rate-limit-override overlay resolver over
4066    /// the substrate primitive) now reaches the same typed dispatch on
4067    /// the substrate primitive at const-eval time as at runtime.
4068    ///
4069    /// Pinned load-bearing at the substrate-primitive level by
4070    /// [`tests::rate_limit_canonical_unit_accessor_is_const_fn`] (const-
4071    /// eval-surface pin via `const fn` wrapper).
4072    #[must_use]
4073    pub const fn canonical_unit(&self) -> Option<RateLimitUnit> {
4074        RateLimitUnit::from_window(self.window)
4075    }
4076}
4077
4078/// Typed closed-set enum for the three canonical `:politicas :rate-limit`
4079/// `:window` units — `Second` / `Minute` / `Hour` — the `rate_limit_codec`
4080/// round-trips losslessly (`"<n>/s"` / `"<n>/m"` / `"<n>/h"`).
4081///
4082/// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer of
4083/// the `:politicas :rate-limit` unit surface reads from
4084/// ([`rate_limit_codec::parse`]'s `unit → Duration` dispatch,
4085/// [`rate_limit_codec::render`]'s `Duration → unit` projection, the
4086/// [`is_canonical_rate_limit_window`] predicate the
4087/// [`AplicacaoSpec::validate_politicas`] gate keys off, the future M4
4088/// per-Aplicacao Envoy config reconciler's `local_rate_limit.token_bucket.fill_interval`
4089/// projection) now lives inside this typed enum's `match self` arms — a
4090/// future rate-limit-unit addition (a `"d"` day suffix once Envoy's
4091/// `rate_limit_action` grows daily-bucket support) is one new variant
4092/// plus the exhaustiveness arms on the four methods, so every consumer
4093/// picks it up by compile-time construction rather than a runtime
4094/// table-scan miss.
4095///
4096/// The prior `RATE_LIMIT_UNIT_TABLE: &[(&str, u64)]` slice-of-tuples was
4097/// scanned via `find_map` at every projection call — an untyped runtime
4098/// walk that carried no compile-time link between the parse arm's
4099/// accepted suffixes, the render arm's emitted suffixes, and the
4100/// validate gate's accepted windows. A future rate-limit-unit addition
4101/// that landed one row without threading through the other consumers
4102/// (or a copy-paste flip that collapsed two rows onto one suffix) would
4103/// silently split the accepted-set across the three consumers — the
4104/// parse arm accepts `"d"` and rejects `"s"`, the render arm emits `"h"`
4105/// for a 24h window that parse can't round-trip, the validate gate
4106/// misses one canonical window. Lifting the pairs onto a typed
4107/// closed-set enum with exhaustive `match` arms makes any such
4108/// half-landed extension a caixa-core build error (the compiler enforces
4109/// arm coverage on every method), not a silent per-consumer drift
4110/// surfacing at apply time. Same "closed-set typed-enum discriminator"
4111/// discipline the sibling [`PlacementStrategy`] (cc8f749),
4112/// [`crate::supervisor::RestartStrategy`],
4113/// [`crate::supervisor::RestartPolicy`],
4114/// [`crate::upgrade::UpgradeInstruction`], and [`crate::CaixaKind`]
4115/// closed-set typed enums carry on their respective closed-set axes —
4116/// extended onto the seventh closed-set typed-enum discriminator axis
4117/// on the caixa typed surface (the `:politicas :rate-limit :window`
4118/// canonical-unit axis).
4119#[derive(
4120    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
4121)]
4122pub enum RateLimitUnit {
4123    /// 1-second window — canonical author-surface suffix `"s"`
4124    /// (`"<n>/s"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
4125    /// with a 1s magnitude.
4126    Second,
4127    /// 1-minute window — canonical author-surface suffix `"m"`
4128    /// (`"<n>/m"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
4129    /// with a 60s magnitude.
4130    Minute,
4131    /// 1-hour window — canonical author-surface suffix `"h"`
4132    /// (`"<n>/h"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
4133    /// with a 3600s magnitude.
4134    Hour,
4135}
4136
4137impl RateLimitUnit {
4138    /// Exhaustive iteration surface for every consumer that reads the
4139    /// full canonical-unit set (the byte-parity witness against the
4140    /// prior `RATE_LIMIT_UNIT_TABLE` shape, the future M4 admission
4141    /// webhook's accepted-suffix listing in its rejection body, any
4142    /// future round-trip fuzz harness). A future variant addition to
4143    /// [`RateLimitUnit`] extends this slice as a single edit and every
4144    /// consumer picks up the new entry by construction — the compiler-
4145    /// checked exhaustiveness on the sibling method `match` arms is the
4146    /// build-time guarantee that no arm forgets to grow.
4147    pub const ALL: &'static [Self] = &[Self::Second, Self::Minute, Self::Hour];
4148
4149    /// Canonical author-surface suffix — the `"s"` / `"m"` / `"h"` byte-
4150    /// string every `<n>/<unit>` rate-limit shape carries after its
4151    /// `/` separator. The single source of truth the codec's parse and
4152    /// render arms both dispatch on: the parse arm matches an incoming
4153    /// suffix against every [`RateLimitUnit::ALL`] entry's `as_suffix`
4154    /// output; the render arm emits the entry's `as_suffix` verbatim
4155    /// after the rate magnitude.
4156    #[must_use]
4157    pub const fn as_suffix(self) -> &'static str {
4158        match self {
4159            Self::Second => "s",
4160            Self::Minute => "m",
4161            Self::Hour => "h",
4162        }
4163    }
4164
4165    /// Canonical `Duration` for this unit — the token-bucket refill
4166    /// period the [`RateLimit::window`] axis carries when the surrounding
4167    /// slot's `:rate-limit` author surface named this unit.
4168    #[must_use]
4169    pub const fn window(self) -> Duration {
4170        Duration::from_secs(match self {
4171            Self::Second => 1,
4172            Self::Minute => 60,
4173            Self::Hour => 3_600,
4174        })
4175    }
4176
4177    /// Parse the `<n>/<unit>`-shaped suffix into the typed enum, or
4178    /// `None` when `suffix` is outside the closed-set arm-string set
4179    /// [`Self::as_suffix`] emits. The single `str → Self` projection
4180    /// [`rate_limit_codec::parse`] consumes.
4181    #[must_use]
4182    pub fn from_suffix(suffix: &str) -> Option<Self> {
4183        Self::ALL.iter().copied().find(|u| u.as_suffix() == suffix)
4184    }
4185
4186    /// Recognize a canonical rate-limit `Duration` as one of the three
4187    /// arms, or `None` when `window` carries sub-second residue or a
4188    /// second-magnitude outside the closed-set arm-window set
4189    /// [`Self::window`] emits. The single `Duration → Self` projection
4190    /// [`rate_limit_codec::render`] + [`is_canonical_rate_limit_window`]
4191    /// both consume.
4192    ///
4193    /// `pub const fn` — the reverse `Duration → Self` projection now
4194    /// carries the same `const`-eval-surface posture the sibling
4195    /// `pub const fn` [`Self::as_suffix`] / [`Self::window`] scalar-
4196    /// projection accessors on this closed-set typed enum already
4197    /// carry, and the paired `pub const fn` [`RateLimit::canonical_unit`]
4198    /// typed-`RateLimit`-projection sibling composes through in `const`
4199    /// context. Routes byte-for-byte through the peer `pub const fn`
4200    /// [`Self::window`] canonical-`Duration` projection so any future
4201    /// arm-magnitude edit on the sibling accessor reaches this reverse
4202    /// resolver by construction — the `s == Self::<Arm>.window().as_secs()`
4203    /// per-arm probes each dispatch through one `pub const fn` on the
4204    /// substrate primitive rather than a hand-authored per-arm second-
4205    /// magnitude literal that would silently drift on any future
4206    /// [`Self::window`] arm-magnitude edit.
4207    ///
4208    /// Prior to the `const` lift the body dispatched through
4209    /// `Self::ALL.iter().copied().find(|u| u.window() == window)` — an
4210    /// iterator-driven linear scan whose iterator methods
4211    /// (`.iter()` / `.copied()` / `.find()`) and `Duration`-side
4212    /// `PartialEq` dispatch each carry non-`const` bounds on stable
4213    /// Rust 1.94, so any downstream substrate-side `const`-context
4214    /// consumer of the reverse resolver (a module-scope
4215    /// `const _:() = assert!(RateLimitUnit::from_window(<canonical>).is_some())`
4216    /// invariant pin on a typed fixture, a future M4
4217    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
4218    /// webhook `const fn` per-`:politicas` canonical-window floor over a
4219    /// typed [`RateLimit`] scalar, any future `const fn`
4220    /// per-`:contratos`-edge rate-limit-override overlay resolver over
4221    /// the substrate primitive that wants to fan on the canonical unit
4222    /// at compile time) surfaced as a downstream E0015 far from the
4223    /// resolver's own declaration. The `pub const fn` posture closes
4224    /// the drift structurally at caixa-core build time.
4225    ///
4226    /// Pinned load-bearing at the substrate-primitive level by
4227    /// [`tests::rate_limit_unit_from_window_accessor_is_const_fn`] (const-
4228    /// eval-surface pin via `const fn` wrapper) and
4229    /// [`tests::rate_limit_unit_from_window_composes_through_window_accessor`]
4230    /// (composition-witness pin against the peer `Self::window` scalar
4231    /// dispatch).
4232    #[must_use]
4233    pub const fn from_window(window: Duration) -> Option<Self> {
4234        if window.subsec_nanos() != 0 {
4235            return None;
4236        }
4237        // Route through the peer `pub const fn` [`Self::window`]
4238        // canonical-`Duration` projection so any future arm-magnitude
4239        // edit on the sibling accessor reaches this reverse resolver by
4240        // construction — the per-arm `secs` comparison keys off
4241        // `Duration::as_secs` (`pub const fn`), not a hand-authored
4242        // per-arm second-magnitude literal that would silently drift.
4243        let secs = window.as_secs();
4244        if secs == Self::Second.window().as_secs() {
4245            Some(Self::Second)
4246        } else if secs == Self::Minute.window().as_secs() {
4247            Some(Self::Minute)
4248        } else if secs == Self::Hour.window().as_secs() {
4249            Some(Self::Hour)
4250        } else {
4251            None
4252        }
4253    }
4254
4255    /// Canonical rate-limit `Duration` for a unit suffix, or `None` when
4256    /// `suffix` is outside the closed-set arm-string set [`Self::as_suffix`]
4257    /// emits. Composes [`Self::from_suffix`] with [`Self::window`] — the
4258    /// single `&str → Duration` projection [`rate_limit_codec::parse`]
4259    /// consumes.
4260    ///
4261    /// The peer `Duration → &'static str` axis folded onto the substrate
4262    /// primitive [`RateLimit::canonical_unit`] typed accessor once both
4263    /// production consumers ([`rate_limit_codec::render`] and
4264    /// [`AplicacaoSpec::validate_politicas`]'s canonical-window gate)
4265    /// migrated (61421a6): the free helper's `Duration → &str` projection
4266    /// is now the two-step composition
4267    /// `rl.canonical_unit().map(RateLimitUnit::as_suffix)` every consumer
4268    /// reads through the typed accessor. This lift closes the peer
4269    /// `&str → Duration` axis by folding the vestigial module-private
4270    /// `rate_limit_window_from_unit` delegate onto this associated method
4271    /// — the codec's parse arm and every future wire-side consumer of the
4272    /// `&str → Duration` projection (a future admission-webhook that
4273    /// reads a `:rate-limit` shape off a CR spec's `raw string` value
4274    /// before it's promoted to a validated typed slot, a future
4275    /// `feira lint` shape-probe that reads the author-surface bytes
4276    /// verbatim) now reach for exactly one typed dispatch on the
4277    /// substrate primitive.
4278    ///
4279    /// Same "closed-set typed-enum discriminator with canonical
4280    /// projections per axis" discipline the sibling [`Self::as_suffix`]
4281    /// / [`Self::window`] / [`Self::from_suffix`] / [`Self::from_window`]
4282    /// methods carry — this associated method closes the fifth (and last
4283    /// unlifted) projection axis on the arm-table, so the closed-set enum
4284    /// now owns every `str ↔ Duration ↔ Self` typed dispatch every
4285    /// consumer of the `:politicas :rate-limit :window` axis reaches
4286    /// through. A future rate-limit-unit addition (a `"d"` day suffix
4287    /// once Envoy's `rate_limit_action` grows daily-bucket support, a
4288    /// `"ms"` sub-second window once high-throughput per-edge policies
4289    /// come into scope per MESH-COMPOSITION §III.2 #3) is one new
4290    /// variant plus one arm per method — the compiler enforces
4291    /// exhaustiveness on every consumer's `match self` arms and picks
4292    /// the new unit up by construction across all five projections.
4293    #[must_use]
4294    pub fn window_from_suffix(suffix: &str) -> Option<Duration> {
4295        Self::from_suffix(suffix).map(Self::window)
4296    }
4297}
4298
4299/// Route [`std::fmt::Display`] through [`RateLimitUnit::as_suffix`], so
4300/// every consumer that formats a canonical rate-limit unit as user-
4301/// facing text (future M4 admission-webhook rejection bodies naming
4302/// the accepted-suffix set, future `feira app graph` per-`:politicas`
4303/// unit column) lands on the same `"s"` / `"m"` / `"h"` byte-string the
4304/// codec's parse arm accepts and the render arm emits. Same
4305/// as_str-through-Display convergence discipline the sibling
4306/// [`PlacementStrategy`], [`crate::CaixaKind`],
4307/// [`crate::supervisor::RestartStrategy`], and
4308/// [`crate::supervisor::RestartPolicy`] closed-set typed enums carry.
4309impl std::fmt::Display for RateLimitUnit {
4310    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4311        f.write_str(self.as_suffix())
4312    }
4313}
4314
4315/// Upper-bound ceiling on the `:politicas :timeout` axis — every
4316/// validated [`MeshPolicy::timeout`] past
4317/// [`AplicacaoSpec::validate_politicas`] lies in `1ms..=POLICY_TIMEOUT_MAX`
4318/// (inclusive on both ends, integer-millisecond magnitudes by the
4319/// canonical-form gate immediately preceding).
4320///
4321/// The typed field is `Option<Duration>` (the zero-floor arm
4322/// [`AplicacaoError::PolicyTimeoutZero`] already rejects
4323/// `Duration::ZERO`, and the canonical-form arm
4324/// [`AplicacaoError::PolicyTimeoutNotCanonical`] already rejects
4325/// sub-millisecond residue), so a programmatic struct literal
4326/// (`MeshPolicy { timeout: Some(Duration::from_secs(86_400)), .. }` —
4327/// 24h) and the equivalent author-surface form
4328/// (`(:politicas (:timeout "24h"))` — the codec emits `"h"` for any
4329/// integer-hour magnitude) both round-trip cleanly through serde — a
4330/// structurally unbounded `Duration` ceiling. A `:timeout` value far
4331/// above the documented production-playbook band (Envoy default `15s`,
4332/// Istio per-route typical `≤ 30s`, AWS App Mesh `httpRouteTimeout`
4333/// schema typical `≤ 60s`, Linkerd `request_timeout` typical `10s`,
4334/// Kubernetes ingress-nginx `proxy_read_timeout` default `60s` capped
4335/// at `~3600s`) silently degenerates the mesh-policy contract: the
4336/// per-call deadline is structurally so long that no realistic
4337/// synchronous-`:contratos` traversal can reach it, so the typed slot
4338/// becomes a no-op carried on every emitted Envoy / Cilium L7 timeout
4339/// overlay — the MESH-COMPOSITION §V CSE invariant "no infinite
4340/// blocking" degenerates to a nominal-only contract on the
4341/// synchronous-call path. Pairs with the [`POLICY_RETRIES_MAX`] cap on
4342/// the sibling `:politicas :retries` axis and the
4343/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap on the sibling
4344/// `:politicas :circuit-breaker :max-failures` axis — all three close
4345/// the "structurally unbounded ceiling on a typed `:politicas` axis"
4346/// footgun the prior zero-floor-and-canonical-form-only checks left
4347/// open.
4348///
4349/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
4350/// shared duration codec emits (`"<n>h"` for any integer-hour
4351/// magnitude) — every value in the canonical authoring form's
4352/// `<integer><unit>` grammar at or below this cap renders to a clean
4353/// canonical string. The cap sits an order of magnitude above every
4354/// documented production-playbook recommendation band (Envoy default
4355/// `15s`, Istio production `≤ 30s`, Linkerd production `≤ 10s`, AWS
4356/// App Mesh production `≤ 60s`) and at the Kubernetes ingress-nginx
4357/// configured maximum (`proxy_read_timeout` typical max `3600s`),
4358/// below the clearly-pathological "effectively no timeout" floor
4359/// (`24h`, `7d`, `Duration::MAX`): a value the author can plausibly
4360/// want for a long-running synchronous workflow, but a hard wall above
4361/// which the mesh-level deadline is structurally a non-deadline.
4362/// Lifted as a typed `pub const` so the bound has exactly one source
4363/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4364/// materializer's admission webhook and the caixa-mesh-side
4365/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
4366/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
4367/// other typed upper bound in this crate carries
4368/// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
4369/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4370/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4371/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4372pub const POLICY_TIMEOUT_MAX: Duration = Duration::from_secs(3600);
4373
4374/// Upper-bound ceiling on the `:politicas :retries` axis — every
4375/// validated [`MeshPolicy::retries`] past
4376/// [`AplicacaoSpec::validate_politicas`] lies in `1..=POLICY_RETRIES_MAX`.
4377///
4378/// The typed slot is `Option<u32>` (`None` = no retries on transient
4379/// failure; `Some(0)` already rejected by the
4380/// [`AplicacaoError::PolicyRetriesZero`] zero-floor arm), so a
4381/// programmatic struct literal (`MeshPolicy { retries: Some(100_000),
4382/// .. }`) and the equivalent author-surface form
4383/// (`(:politicas (:retries 100000))`) both round-trip cleanly through
4384/// serde / the codec — a structurally unbounded `u32` ceiling. The
4385/// runtime substrate that consumes the value (Envoy's
4386/// `retry_policy.num_retries`, the `CiliumClusterwideEnvoyConfig`
4387/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 names, AWS
4388/// App Mesh's `gRPCRouteRetryPolicy.maxRetries` whose schema-side
4389/// admission cap is 10) translates a four-billion-retry policy into a
4390/// thundering-herd amplification vector on transient failure — the
4391/// caller's one request fans out to `retries` server-side calls per
4392/// edge per traversal, multiplying load by `(retries+1)^depth` across
4393/// the synchronous-`:contratos` subgraph. The MESH-COMPOSITION §V CSE
4394/// invariant "no infinite blocking" pairs with a no-runaway-amplification
4395/// invariant on the retry axis; both belong at the typed-slot layer.
4396///
4397/// The `10` ceiling matches AWS App Mesh's explicit hard cap (the only
4398/// upstream mesh-policy schema that documents one) and sits above the
4399/// Envoy / Istio practical-recommendation band (`num_retries ≤ 5` in
4400/// every documented production playbook): a value the author can
4401/// plausibly want, but a hard wall above which the policy is
4402/// structurally a footgun. Lifted as a typed `pub const` so the bound
4403/// has exactly one source of truth — a future axis reaching for the
4404/// same value (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4405/// materializer's admission webhook, the caixa-mesh-side
4406/// `CiliumClusterwideEnvoyConfig` overlay's per-edge cap) reads from
4407/// one place. Same shape every other typed upper bound in this crate
4408/// carries ([`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4409/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4410/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
4411/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4412pub const POLICY_RETRIES_MAX: u32 = 10;
4413
4414/// Upper-bound ceiling on the `:politicas :circuit-breaker :max-failures`
4415/// axis — every validated [`CircuitBreaker::max_failures`] past
4416/// [`AplicacaoSpec::validate_politicas`] lies in
4417/// `1..=POLICY_BREAKER_MAX_FAILURES_MAX`.
4418///
4419/// The typed field is `u32` (the zero-floor arm
4420/// [`AplicacaoError::PolicyBreakerZeroFailures`] already rejects
4421/// `0` — a breaker that trips on the first call), so a programmatic
4422/// struct literal (`CircuitBreaker { max_failures: u32::MAX, .. }`)
4423/// and the equivalent author-surface form
4424/// (`(:circuit-breaker (:max-failures 4294967295))`) both round-trip
4425/// cleanly through serde — a structurally unbounded `u32` ceiling. A
4426/// `max_failures` value far above the documented production-playbook
4427/// band (Hystrix `circuitBreaker.requestVolumeThreshold` default 20,
4428/// Istio `outlierDetection.consecutive5xxErrors` default 5, Envoy
4429/// `outlier_detection.consecutive_5xx` default 5, Polly / Resilience4j
4430/// typical 5–50) silently disables the breaker's protection role:
4431/// the threshold is structurally so high that no realistic
4432/// failures-per-`:window` traffic shape can reach it, so the breaker
4433/// never trips and the typed slot becomes a no-op carried on every
4434/// emitted Envoy / Cilium L7 overlay. Pairs with the
4435/// [`POLICY_RETRIES_MAX`] cap on the sibling `:politicas :retries`
4436/// axis — both close the "structurally unbounded `u32` ceiling on a
4437/// typed policy axis" footgun the prior zero-floor-only checks left
4438/// open.
4439///
4440/// The `1000` ceiling sits an order of magnitude above every
4441/// documented upstream production-playbook recommendation band (the
4442/// highest is Hystrix's 20-default `requestVolumeThreshold`, the
4443/// Istio / Envoy / Polly / Resilience4j ones all sit ≤ 50) and below
4444/// the clearly-pathological "effectively no protection"
4445/// floor (`10_000`, `100_000`, `u32::MAX`): a value the author can
4446/// plausibly want at hyperscale, but a hard wall above which the
4447/// policy is structurally a no-op. Lifted as a typed `pub const` so
4448/// the bound has exactly one source of truth — the future M4
4449/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
4450/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
4451/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
4452/// one place. Same shape every other typed upper bound in this crate
4453/// carries ([`POLICY_RETRIES_MAX`],
4454/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4455/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4456/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4457pub const POLICY_BREAKER_MAX_FAILURES_MAX: u32 = 1000;
4458
4459/// Upper-bound ceiling on the `:politicas :circuit-breaker :window` axis —
4460/// every validated [`CircuitBreaker::window`] past
4461/// [`AplicacaoSpec::validate_politicas`] lies in
4462/// `1ms..=POLICY_BREAKER_WINDOW_MAX` (inclusive on both ends,
4463/// integer-millisecond magnitudes by the canonical-form gate
4464/// immediately preceding).
4465///
4466/// The typed field is `Duration` (the zero-floor arm
4467/// [`AplicacaoError::PolicyBreakerZeroWindow`] already rejects
4468/// `Duration::ZERO`, and the canonical-form arm
4469/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`] already rejects
4470/// sub-millisecond residue), so a programmatic struct literal
4471/// (`CircuitBreaker { window: Duration::from_secs(86_400), .. }` — 24h)
4472/// and the equivalent author-surface form
4473/// (`(:circuit-breaker (:window "24h"))` — the codec emits `"h"` for any
4474/// integer-hour magnitude) both round-trip cleanly through serde — a
4475/// structurally unbounded `Duration` ceiling. A `:window` value far
4476/// above the documented production-playbook band (Hystrix
4477/// `metrics.rollingStats.timeInMilliseconds` default `10s`,
4478/// resilience4j `slidingWindowSize` time-based typical `10s..=60s`,
4479/// Istio `outlierDetection.interval` default `10s`, Envoy
4480/// `outlier_detection.interval` default `10s`, AWS App Mesh
4481/// circuit-breaker time-window typical `30s..=300s`) degenerates the
4482/// breaker's role: a rolling-window failure counter whose window is
4483/// hours long is operationally a lifetime counter, the breaker's
4484/// "recent failures" memory is structurally so long that transient
4485/// failures are never forgotten, and the typed slot becomes a no-op
4486/// trigger that trips once and stays tripped for the lifetime of the
4487/// component carried on every emitted Envoy / Cilium L7 overlay.
4488///
4489/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
4490/// shared duration codec emits (`"<n>h"` for any integer-hour
4491/// magnitude) — every value in the canonical authoring form's
4492/// `<integer><unit>` grammar at or below this cap renders to a clean
4493/// canonical string — and matches the sibling [`POLICY_TIMEOUT_MAX`]
4494/// cap on the first typed-`Duration` `:politicas` axis: the two
4495/// duration-typed `:politicas` axes now share a single uniform top
4496/// edge so the next typed-slot wiring (the future caixa-mesh
4497/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay, the M4
4498/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-policy
4499/// admission webhook) reaches for either field knowing the value is
4500/// in `1ms..=1h` without re-validating at the renderer layer. The cap
4501/// sits two orders of magnitude above every documented upstream
4502/// production-playbook recommendation band (Hystrix / resilience4j /
4503/// Istio / Envoy all default to 10s; AWS App Mesh maxes out at ~5m)
4504/// and below the clearly-pathological "rolling window degenerates to
4505/// lifetime counter" floor (`24h`, `7d`, `Duration::MAX`): a value the
4506/// author can plausibly want for a very-low-traffic long-tail
4507/// failure-detection window, but a hard wall above which the breaker's
4508/// rolling-window contract is structurally a lifetime-counter contract.
4509/// Lifted as a typed `pub const` so the bound has exactly one source
4510/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4511/// materializer's admission webhook and the caixa-mesh-side
4512/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
4513/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
4514/// other typed upper bound in this crate carries
4515/// ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
4516/// [`POLICY_BREAKER_MAX_FAILURES_MAX`],
4517/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4518/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4519/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4520pub const POLICY_BREAKER_WINDOW_MAX: Duration = Duration::from_secs(3600);
4521
4522/// Upper-bound ceiling on the `:politicas :rate-limit` rate axis —
4523/// every validated [`RateLimit::rate`] past
4524/// [`AplicacaoSpec::validate_politicas`] lies in
4525/// `1..=POLICY_RATE_LIMIT_MAX`.
4526///
4527/// The typed field is `u32` (the zero-floor arm
4528/// [`AplicacaoError::PolicyRateLimitZero`] already rejects `0` — a
4529/// zero-rate limit denies every request, the canonical "I forgot
4530/// that 0 means deny-everything" footgun), so a programmatic struct
4531/// literal (`RateLimit { rate: u32::MAX, window: Duration::from_secs(1) }`)
4532/// and the equivalent author-surface form (`(:rate-limit "4294967295/s")`
4533/// — the `rate_limit_codec` parses any `u32`-shaped magnitude) both
4534/// round-trip cleanly through serde — a structurally unbounded `u32`
4535/// ceiling. The runtime substrate consuming the value (Envoy's
4536/// `local_rate_limit.token_bucket.max_tokens`, the future
4537/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
4538/// MESH-COMPOSITION §III.2 #3 names) translates a four-billion-token
4539/// rate-limit into a no-op rate-limiter: the bucket capacity is
4540/// structurally so high no realistic per-edge traffic shape can
4541/// drain it, the limiter never trips, and the typed slot becomes a
4542/// "rate-limit declared, no enforcement" footgun — the canonical
4543/// declared-but-inert shape every other `:politicas` cap arm
4544/// closes ([`POLICY_RETRIES_MAX`] thundering-herd amplification,
4545/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] no-op-breaker, etc.).
4546///
4547/// The `1_000_000` (1M) ceiling sits two-to-three orders of magnitude
4548/// above every documented upstream production-playbook recommendation
4549/// band (Envoy `local_rate_limit` typical `10..=10_000` RPS, Istio
4550/// `RateLimitFilter` typical `10..=10_000` RPS, Cloudflare WAF
4551/// rate-rule Free / Pro `10_000` req/min, AWS API Gateway account
4552/// default `10_000` RPS, Kong typical `100..=10_000`, NGINX
4553/// `limit_req_zone` typical `1..=1_000` RPS) and below the
4554/// clearly-pathological "paste-from-binary blob" floor (`100_000_000`,
4555/// `u32::MAX`): a value the author can plausibly want at hyperscale
4556/// (Cloudflare Enterprise rate-plans run to ~6M/min ≈ 1M/h on the
4557/// /h-window arm), but a hard wall above which the policy is
4558/// structurally a no-op carried verbatim on every emitted Envoy /
4559/// Cilium L7 overlay. The cap brackets all three canonical windows
4560/// the [`rate_limit_codec`] accepts: at `1M/s` (absurd hyperscale
4561/// ceiling, ~1M RPS per edge), at `1M/m` (~16.7k RPS, the
4562/// hyperscale-tier WAF band), at `1M/h` (~277 RPS, the common
4563/// per-endpoint API band). Lifted as a typed `pub const` so the bound
4564/// has exactly one source of truth — the future M4
4565/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
4566/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
4567/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
4568/// one place. Same shape every other typed upper bound in this crate
4569/// carries ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
4570/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
4571/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4572/// [`crate::LIMITS_WALL_CLOCK_MAX`],
4573/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4574/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4575pub const POLICY_RATE_LIMIT_MAX: u32 = 1_000_000;
4576
4577// `:entrada :host` total-length and per-label cap axes route through
4578// the lifted [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] (253) and
4579// [`crate::render::DNS_1123_LABEL_MAX_LEN`] (63) canonical bounds. The
4580// pair of aplicacao-private aliases the previous `validate_entrada_host`
4581// arms consumed (`ENTRADA_HOST_MAX_LEN = 253`, `ENTRADA_HOST_LABEL_MAX_LEN
4582// = 63`) were structurally the same K8s Gateway API v1 Hostname
4583// admission-schema bounds — the total-length cap on the OpenAPI
4584// `Hostname` type and the per-`.`-separated-label DNS-1123 cap on the
4585// same regex — that the peer axes at the caixa-core::render level pin,
4586// so hoisting both readers onto the shared lifted constants closes the
4587// third-occurrence duplication threshold structurally: the M4
4588// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-host / per-
4589// label validator, the future per-`Certificate` SAN emitter, and every
4590// other per-Gateway-API-Hostname landing site reach the same one place
4591// as the `:entrada :host` gate does — no per-axis alias drift surface
4592// between them, by construction.
4593
4594/// Max byte length for an Akka-cluster-sharding `:placement :shard-key`
4595/// extractor expression — the upper bound `validate_placement_shard_key`
4596/// enforces on every well-shaped shard-key past validate. The realistic
4597/// shard-key forms in the wild (`tenantId`, `customerId`, `$tenantId`,
4598/// `metadata.tenantId`, `${tenant}`, `$.user.id`) all sit well under 64
4599/// bytes; the 63-byte cap mirrors the DNS-1123 label cap on the peer
4600/// `:placement :affinity` / `:placement :clusters` identifier-shaped
4601/// axes and surfaces the canonical "paste-from-doc multi-line blob landed
4602/// in `:shard-key`" footgun at validate time rather than at the future
4603/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass.
4604const PLACEMENT_SHARD_KEY_MAX_LEN: usize = 63;
4605
4606/// Reject `:membros :caixa` values the K8s apiserver would refuse at
4607/// admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
4608/// that maps the shared parser-shaped reason into the
4609/// [`AplicacaoError::MembroCaixaInvalid`] variant, so the diagnostic
4610/// is self-locating (the offending `caixa:` is named verbatim) and
4611/// the author can grep their caixa.lisp for `:caixa "<name>"` and
4612/// fix it in one edit. Same diagnostic shape as
4613/// [`AplicacaoError::EntradaHostInvalid`] (c7d05ec) and
4614/// [`AplicacaoError::MembroVersaoInvalid`] (9888b13).
4615fn validate_membro_caixa(caixa: &str) -> Result<(), AplicacaoError> {
4616    // Empty is already gated by `MembroCaixaEmpty` at the call site;
4617    // re-checking here keeps the predicate usable from any future
4618    // call site (the M4 CR materializer) without an empty-check
4619    // footgun. The shared
4620    // [`crate::render::require_valid_dns_1123_label`] helper brackets
4621    // the empty-first + shape cascade every peer name axis
4622    // (`:placement :clusters`, `:placement :affinity`, `:contratos
4623    // :de`/`:para`, `:entrada :para`, `:children :caixa`, `:nome`,
4624    // `:upgrade-from :module`) routes through, so drift between the
4625    // eight axes' accepted DNS-1123-label sets is structurally
4626    // impossible.
4627    crate::render::require_valid_dns_1123_label(
4628        caixa,
4629        || AplicacaoError::MembroCaixaEmpty,
4630        |reason| AplicacaoError::membro_caixa_invalid(caixa, reason),
4631    )
4632}
4633
4634/// Reject `:placement :clusters` entries the K8s apiserver would refuse
4635/// at admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
4636/// that maps the shared parser-shaped reason into the
4637/// [`AplicacaoError::PlacementClusterInvalid`] variant.
4638///
4639/// Cluster names land in DNS-1123-label territory across every consumer:
4640/// the K8s context name keying `kubeconfig`, the `clusters[]` filter
4641/// the `lareira-fleet-programs` aggregator applies to scope programs to
4642/// their owning cluster (caixa-mesh's `placement.clusters` overlay,
4643/// 4d91c0b), the namespace prefix the future cross-cluster fan-out
4644/// emits per entry, and the `cluster.x-k8s.io/v1beta1/Cluster.metadata.name`
4645/// cluster identity the M4 CR materializer round-trips. Each apiserver-
4646/// side schema enforces the DNS-1123 label rule on admission; a
4647/// structurally invalid cluster name (`"Rio"`, `"my_cluster"`,
4648/// `"team.rio"`, `"-rio"`, `"rio-"`, the >63-byte UUID-shaped
4649/// mistaken-identity slug) silently passes the prior empty-/duplicate-
4650/// only gate and the failure surfaces as a no-match at filter time —
4651/// the workload doesn't land in the named cluster, with no diagnostic
4652/// naming the offending `:clusters` entry. Lifting the gate to caixa-
4653/// build time mirrors the `:membros :caixa` value-shape trajectory
4654/// (3f9d7a0) on the peer name axis.
4655///
4656/// The diagnostic carries the offending `cluster:` verbatim plus a
4657/// parser-shaped `reason:` naming the specific violation, so the
4658/// author can grep their caixa.lisp for `:clusters` and fix it in
4659/// one edit. Same diagnostic shape as
4660/// [`AplicacaoError::MembroCaixaInvalid`] (3f9d7a0).
4661fn validate_placement_cluster(cluster: &str) -> Result<(), AplicacaoError> {
4662    // Empty is already gated by `PlacementClusterEmpty` at the call
4663    // site; re-checking here keeps the predicate usable from any
4664    // future call site (the M4 CR materializer's per-cluster validator)
4665    // without an empty-check footgun. Routes through the shared
4666    // [`crate::render::require_valid_dns_1123_label`] gate the peer
4667    // name axes each land on.
4668    crate::render::require_valid_dns_1123_label(
4669        cluster,
4670        || AplicacaoError::PlacementClusterEmpty,
4671        |reason| AplicacaoError::placement_cluster_invalid(cluster, reason),
4672    )
4673}
4674
4675/// Reject `:placement :affinity` hints whose shape can never legitimately
4676/// land in any downstream selector or label-keyed routing axis. Thin
4677/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
4678/// shared parser-shaped reason into the
4679/// [`AplicacaoError::PlacementAffinityInvalid`] variant, so the
4680/// diagnostic is self-locating (the offending `:affinity` is named
4681/// verbatim) and the author can grep their caixa.lisp for
4682/// `:affinity "<hint>"` and fix it in one edit.
4683///
4684/// The `:affinity` slot carries a placement-engine hint — canonical
4685/// examples in the M3 surface are `"data-locality"`, `"low-latency"`,
4686/// `"anti-affinity"` — that flows verbatim into the M3 Adaptive
4687/// compression overlay and the future M4 placement-engine's per-hint
4688/// routing axis. Each downstream consumer (caixa-mesh's
4689/// `placement.affinity` overlay at caixa-mesh/src/lib.rs:126, the
4690/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4691/// `spec.placement.affinity` admission rule, the future M4 per-hint
4692/// node-affinity / pod-affinity rule generator keying off the same
4693/// value as a K8s `app.pleme.io/affinity-hint=<value>` label
4694/// selector) requires the value to be a DNS-1123 label — K8s label
4695/// values are bounded by `[a-z0-9A-Z_.-]{,63}` with a stricter
4696/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?` floor in every identity-keyed
4697/// admission rule the apiserver enforces.
4698///
4699/// Until this gate landed an `:affinity "DataLocality"` (the canonical
4700/// TitleCase-from-an-ADR typo), `:affinity "data_locality"` (the
4701/// Python-module-name leak), `:affinity "data.locality"` (the
4702/// namespace-dot-on-a-label confusion), `:affinity "-data-locality"` /
4703/// `:affinity "data-locality-"` (boundary-hyphen violation),
4704/// `:affinity "data locality"` (paste-from-doc whitespace),
4705/// `:affinity "data-localité"` (un-Punycode-encoded IDN), or the
4706/// 64-byte over-cap slug silently passed the empty-only check and the
4707/// failure surfaced as a no-match at the M3 Adaptive compression
4708/// overlay's filter time (`placement.affinity` carried a malformed
4709/// value, no node matched, the workload landed on the default
4710/// heuristic) — the canonical "declared-but-inert" footgun mirroring
4711/// the empty-:affinity / empty-shard-key / zero-:politicas /
4712/// empty-:contratos-target gates already close on every other
4713/// declare-but-no-opinion axis. Lifting the rejection to a build-time
4714/// gate closes the fifth typed slot on the Aplicacao surface to land
4715/// on the canonical DNS-1123 label floor (after the four Servico-name
4716/// reference axes: `:membros :caixa` 3f9d7a0, `:placement :clusters`
4717/// 6c8c00b, `:contratos :de`/`:para` 8d5af6b, `:entrada :para`
4718/// b0e8748).
4719///
4720/// Same diagnostic shape as [`AplicacaoError::PlacementClusterInvalid`]
4721/// (6c8c00b) on the sibling `:placement :clusters` axis — both axes'
4722/// validated values are guaranteed-accepted by the apiserver without
4723/// re-validation at any downstream renderer or admission layer.
4724fn validate_placement_affinity(affinity: &str) -> Result<(), AplicacaoError> {
4725    // Empty is gated separately at the call site for a self-locating
4726    // diagnostic; re-checking here keeps the predicate usable from any
4727    // future call site (the M4 CR materializer's per-affinity
4728    // validator) without an empty-check footgun. Routes through the
4729    // shared [`crate::render::require_valid_dns_1123_label`] gate the
4730    // peer name axes each land on.
4731    crate::render::require_valid_dns_1123_label(
4732        affinity,
4733        || AplicacaoError::PlacementAffinityEmpty,
4734        |reason| AplicacaoError::placement_affinity_invalid(affinity, reason),
4735    )
4736}
4737
4738/// Reject `:placement :shard-key` extractor expressions whose shape can
4739/// never legitimately drive the future M4 Akka-style cluster-sharding
4740/// reconciler's hash-extractor pass. Maps the per-byte / length checks
4741/// into the [`AplicacaoError::ShardKeyInvalid`] variant, so the
4742/// diagnostic is self-locating (the offending `:shard-key` value is
4743/// named verbatim alongside the parser-shaped reason) and the author can
4744/// grep their caixa.lisp for `:shard-key "<expr>"` and fix it in one
4745/// edit.
4746///
4747/// The `:shard-key` slot is the Akka-cluster-sharding `ExtractEntityId`
4748/// axis (MESH-COMPOSITION §II.4) — a single-token entity-id extractor
4749/// expression naming the message property to hash on. The realistic
4750/// shapes in the wild (`tenantId` / `customerId` / `userId` — bare
4751/// property name; `$tenantId` — Akka entity-id placeholder;
4752/// `metadata.tenantId` / `$.user.id` — JSONPath-style nested reference;
4753/// `${tenant}` — interpolation-style template) all sit in the printable
4754/// ASCII subset; the realistic *non-shapes* (a paste-from-doc
4755/// multi-line blob landing in `:shard-key`, an embedded space from a
4756/// paste-from-aligned-doc, a trailing newline from a paste-from-shell
4757/// heredoc, a non-ASCII byte from a paste-from-Unicode-doc, the
4758/// `:shard-key "tenant Id"` typo) silently passed the prior empty-only
4759/// check and the failure surfaces at the future M4 reconciler's hash
4760/// pass as a runtime extractor-evaluation error far from the source
4761/// `caixa.lisp`, with no field naming which member's `:shard-key`
4762/// carried the offending value.
4763///
4764/// The contract — the printable ASCII single-token intersection-floor
4765/// every Akka-style entity-id extractor implementation admits:
4766///
4767///   - 1..=[`PLACEMENT_SHARD_KEY_MAX_LEN`] (63) bytes — same cap as the
4768///     peer DNS-1123-label-shaped `:placement :affinity` /
4769///     `:placement :clusters` identifier axes; realistic shard-keys sit
4770///     well under 32 bytes, the cap surfaces paste-from-doc multi-line
4771///     blob footguns at validate time;
4772///   - every byte in the printable ASCII range `0x21..=0x7E` —
4773///     rejects whitespace (space, tab, CR, LF — `"$tenant Id"` /
4774///     `"$tenantId\n"` from paste-from-aligned-doc /
4775///     paste-from-shell-heredoc), control characters (`\x00..\x1F`,
4776///     `\x7F` — the canonical "embedded null from a copy-paste-binary
4777///     footgun"), and non-ASCII bytes (`"$tenàntId"` —
4778///     un-Punycode-encoded IDN that round-trips inconsistently across
4779///     NFC/NFD normalization).
4780///
4781/// The accepted set is broader than the DNS-1123 label floor the peer
4782/// `:placement :clusters` / `:placement :affinity` axes use because the
4783/// `:shard-key` value is not a K8s `metadata.name` / label-selector
4784/// landing site; it's an extractor expression the future Akka-style
4785/// reconciler reads as a property reference. The realistic forms
4786/// (`$tenantId`, `metadata.tenantId`, `${tenant}`, `$.user.id`) carry
4787/// `$` / `.` / `{` / `}` characters that the DNS-1123 grammar forbids
4788/// but every Akka-style entity-id extractor parses. The
4789/// printable-ASCII-token floor accepts every shape any such extractor
4790/// would accept while rejecting the cross-implementation footguns
4791/// (whitespace breaks token boundaries; non-ASCII round-trips
4792/// inconsistently across YAML emitters and NFC/NFD normalization;
4793/// control characters silently corrupt the next read).
4794///
4795/// Until this gate landed `validate_placement` only refused the
4796/// `Some("")` empty arm via [`AplicacaoError::ShardedKeyEmpty`]; a
4797/// structurally invalid `:shard-key` (`":shard-key \" $tenantId\""` —
4798/// leading space from paste-from-aligned-doc, `":shard-key \"$tenant
4799/// Id\""` — embedded space, `":shard-key \"$tenantId\\n\""` — trailing
4800/// newline from paste-from-shell-heredoc, `":shard-key \"$tenàntId\""`
4801/// — un-Punycode-encoded IDN, `":shard-key \"$tenantId\\x01\""` —
4802/// control character from paste-from-binary, the 64-byte over-cap
4803/// paste-from-doc multi-line slug) silently passed validate. The future
4804/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass
4805/// would then surface the malformed value either as a runtime
4806/// extractor-evaluation error (whitespace breaks the extractor's token
4807/// boundary, no match) or as a silently-different shard assignment
4808/// across YAML emitters (non-ASCII normalizes differently between the
4809/// caixa-mesh-side YAML emitter and the in-cluster reconciler's YAML
4810/// parser, the same entity ID maps to two distinct shards on a
4811/// re-render). Lifting the shape gate to caixa-build time makes the
4812/// extractor-floor invariant a structural property of every validated
4813/// `Placement`: every `Sharded` placement past `validate_placement` has
4814/// a `:shard-key` the future M4 reconciler can hash without
4815/// re-validating at the runtime layer.
4816///
4817/// Mirrors the [`AplicacaoError::ContratoSlotInvalid`] /
4818/// [`AplicacaoError::ContratoSubjectInvalid`] /
4819/// [`AplicacaoError::ContratoEndpointInvalid`] payload-axis shape gates
4820/// on the peer `:contratos` payload axes — each lifts the
4821/// runtime-side parser's intersection-floor to a caixa-build-time gate,
4822/// closing the canonical "this passed validate but the runtime parser
4823/// rejected it" surprise.
4824fn validate_placement_shard_key(key: &str) -> Result<(), AplicacaoError> {
4825    // Empty is gated separately at the call site via the more
4826    // self-locating [`AplicacaoError::ShardedKeyEmpty`] diagnostic;
4827    // re-checking here keeps the predicate usable from any future call
4828    // site (the M4 CR materializer's per-shard-key validator) without
4829    // an empty-check footgun.
4830    if key.is_empty() {
4831        return Err(AplicacaoError::ShardedKeyEmpty);
4832    }
4833    if key.len() > PLACEMENT_SHARD_KEY_MAX_LEN {
4834        return Err(AplicacaoError::shard_key_invalid(
4835            key,
4836            format!(
4837                "exceeds :shard-key max length of {PLACEMENT_SHARD_KEY_MAX_LEN} bytes \
4838                 (got {} bytes; realistic Akka-style entity-id extractor expressions \
4839                 — `tenantId`, `$tenantId`, `metadata.tenantId`, `${{tenant}}` — sit \
4840                 well under 32 bytes, this length suggests a paste-from-doc \
4841                 multi-line blob landed in `:shard-key` instead of a single-token \
4842                 extractor expression)",
4843                key.len()
4844            ),
4845        ));
4846    }
4847    for &b in key.as_bytes() {
4848        if (0x21..=0x7E).contains(&b) {
4849            continue;
4850        }
4851        let reason = if b == b' ' {
4852            "contains a space (Akka-style entity-id extractor expressions are \
4853             single-token references like `tenantId` / `$tenantId` / `metadata.tenantId`; \
4854             whitespace breaks the extractor's token boundary at the runtime layer, \
4855             and the paste-from-aligned-doc / paste-from-CSV footgun silently lands \
4856             a multi-token blob in one `:shard-key` slot)"
4857                .to_string()
4858        } else if b == b'\t' {
4859            "contains a tab character (paste-from-aligned-doc footgun; the \
4860             Akka-style entity-id extractor reads `:shard-key` as a single-token \
4861             reference, embedded whitespace breaks the token boundary at the \
4862             runtime hash-extractor pass)"
4863                .to_string()
4864        } else if b == b'\n' || b == b'\r' {
4865            format!(
4866                "contains line terminator 0x{b:02x} (paste-from-shell-heredoc / \
4867                 paste-from-multiline-doc footgun; the Akka-style entity-id \
4868                 extractor reads `:shard-key` as a single-token reference, embedded \
4869                 newlines either truncate the value at the YAML emitter layer or \
4870                 break the token boundary at the runtime hash-extractor pass)"
4871            )
4872        } else if b < 0x20 || b == 0x7F {
4873            format!(
4874                "contains control character 0x{b:02x} (the canonical \
4875                 paste-from-binary / paste-from-screen-cleared-terminal footgun; \
4876                 control characters silently corrupt round-trip serialization \
4877                 across YAML emitters and break the runtime hash-extractor's \
4878                 single-token parser)"
4879            )
4880        } else {
4881            format!(
4882                "contains non-ASCII byte 0x{b:02x} (the canonical \
4883                 paste-from-Unicode-doc footgun; non-ASCII bytes round-trip \
4884                 inconsistently across NFC/NFD normalization on APFS / ext4 / \
4885                 across YAML emitter implementations — the same entity ID can \
4886                 silently map to two distinct shards on a re-render. Use a \
4887                 printable-ASCII extractor expression like `tenantId`, \
4888                 `$tenantId`, or `metadata.tenantId`)"
4889            )
4890        };
4891        return Err(AplicacaoError::shard_key_invalid(key, reason));
4892    }
4893    Ok(())
4894}
4895
4896/// Reject `:contratos :de` / `:contratos :para` values whose shape
4897/// can never legitimately match a validated `:membros :caixa`. Thin
4898/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
4899/// shared parser-shaped reason into the
4900/// [`AplicacaoError::ContratoCaixaInvalid`] variant, so the per-edge
4901/// diagnostic is self-locating (which slot — `:de` or `:para` — and
4902/// the offending value verbatim) and the author can grep their
4903/// caixa.lisp for `:de "<name>"` / `:para "<name>"` and fix it in
4904/// one edit.
4905///
4906/// Until this gate landed an empty or DNS-1123-malformed `:de` /
4907/// `:para` (`:de ""`, `:de "Cart"` the canonical TitleCase-from-an-ADR
4908/// typo, `:de "my_cart"` the Python-module-name leak, `:de "team.cart"`
4909/// the namespace-dot-on-a-label confusion, `:de "-cart"` / `:de "cart-"`
4910/// the boundary-hyphen violation, the 64-byte over-cap slug, `:de "café"`
4911/// un-Punycode-encoded IDN) silently passed the per-axis check and
4912/// surfaced as [`AplicacaoError::ContratoMemberMissing`] at the
4913/// membership lookup — diagnostic-framed as "this caixa is not in
4914/// `:membros`" when the root cause is "this `:de` value is not a
4915/// well-shaped Servico-name identifier and could never legitimately
4916/// match any validated member". Because every `:membros :caixa` is
4917/// shape-validated through [`validate_membro_caixa`] (3f9d7a0), the
4918/// `names` HashSet structurally never contains an empty / malformed
4919/// string, so the membership lookup arm misframes every empty /
4920/// malformed input. Lifting the shape arm ahead of the lookup
4921/// preserves the legitimate `ContratoMemberMissing` arm (a
4922/// well-shaped `:de` that simply isn't in `:membros` — a phantom
4923/// reference) while routing every structurally-impossible-to-match
4924/// input through the narrower self-locating shape diagnostic.
4925///
4926/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
4927/// (3f9d7a0) and [`AplicacaoError::PlacementClusterInvalid`]
4928/// (6c8c00b) — the third Aplicacao-level Servico-name reference axis
4929/// to land on the canonical [`crate::render::is_dns_1123_label`]
4930/// floor. The `slot: &'static str` field carries the kebab-case
4931/// `:de` / `:para` tag verbatim, mirroring [`BehaviorSpec::validate`]'s
4932/// per-callback-slot diagnostic shape and the
4933/// [`ManifestError::CodePathDuplicate`] (e113ace) / [`DepError::DepIsSelf`]
4934/// (85f102c) cross-list-tag pattern.
4935fn validate_contrato_caixa(slot: &'static str, caixa: &str) -> Result<(), AplicacaoError> {
4936    // Routes through the shared
4937    // [`crate::render::require_valid_dns_1123_label`] gate the peer
4938    // name axes each land on. The `slot: &'static str` field flows
4939    // through both error variants so the diagnostic names which
4940    // per-edge axis (`:de` vs `:para`) the offending value came from.
4941    crate::render::require_valid_dns_1123_label(
4942        caixa,
4943        || AplicacaoError::ContratoCaixaEmpty { slot },
4944        |reason| AplicacaoError::ContratoCaixaInvalid {
4945            slot,
4946            caixa: caixa.to_string(),
4947            reason,
4948        },
4949    )
4950}
4951
4952/// Reject `:entrada :para` values whose shape can never legitimately
4953/// match a validated `:membros :caixa`. Thin wrapper around
4954/// [`crate::render::is_dns_1123_label`] that maps the shared parser-
4955/// shaped reason into the [`AplicacaoError::EntradaParaInvalid`]
4956/// variant, so the diagnostic is self-locating (the offending
4957/// `:entrada :para` value is named verbatim) and the author can grep
4958/// their caixa.lisp for `:para "<name>"` and fix it in one edit.
4959///
4960/// Until this gate landed an empty or DNS-1123-malformed `:entrada
4961/// :para` (`:para ""`, `:para "Cart"` the canonical TitleCase-from-an-
4962/// ADR typo, `:para "my_cart"` the Python-module-name leak,
4963/// `:para "team.cart"` the namespace-dot-on-a-label confusion,
4964/// `:para "-cart"` / `:para "cart-"` the boundary-hyphen violation,
4965/// the 64-byte over-cap slug, `:para "café"` un-Punycode-encoded IDN)
4966/// silently passed the per-axis check and surfaced as
4967/// [`AplicacaoError::EntradaMemberMissing`] at the membership lookup
4968/// — diagnostic-framed as "this caixa is not in `:membros`" when the
4969/// root cause is "this `:entrada :para` value is not a well-shaped
4970/// Servico-name identifier and could never legitimately match any
4971/// validated member". Because every `:membros :caixa` is shape-
4972/// validated through [`validate_membro_caixa`] (3f9d7a0), the `names`
4973/// `HashSet` structurally never contains an empty / malformed string,
4974/// so the membership lookup arm misframes every empty / malformed
4975/// input. Lifting the shape arm ahead of the lookup preserves the
4976/// legitimate `EntradaMemberMissing` arm (a well-shaped `:para` that
4977/// simply isn't in `:membros` — a phantom reference) while routing
4978/// every structurally-impossible-to-match input through the narrower
4979/// self-locating shape diagnostic.
4980///
4981/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
4982/// (3f9d7a0), [`AplicacaoError::PlacementClusterInvalid`] (6c8c00b),
4983/// and [`AplicacaoError::ContratoCaixaInvalid`] (8d5af6b) — the
4984/// fourth and last Aplicacao-level Servico-name reference axis to
4985/// land on the canonical [`crate::render::is_dns_1123_label`] floor.
4986/// No `slot: &'static str` field because there is only one axis
4987/// (`:entrada :para`), unlike the dual-axis `:contratos :de`/`:para`;
4988/// the simpler shape mirrors [`validate_membro_caixa`] and
4989/// [`validate_placement_cluster`].
4990fn validate_entrada_para(para: &str) -> Result<(), AplicacaoError> {
4991    // Empty is gated separately at the call site for a self-locating
4992    // diagnostic; re-checking here keeps the predicate usable from any
4993    // future call site (the M4 CR materializer's per-`:entrada`
4994    // validator) without an empty-check footgun. Routes through the
4995    // shared [`crate::render::require_valid_dns_1123_label`] gate the
4996    // peer name axes each land on.
4997    crate::render::require_valid_dns_1123_label(
4998        para,
4999        || AplicacaoError::EntradaParaEmpty,
5000        |reason| AplicacaoError::entrada_para_invalid(para, reason),
5001    )
5002}
5003
5004/// Reject `:entrada :host` values the K8s Gateway API v1 apiserver
5005/// would refuse at admission time. The contract — exactly the regex
5006/// the Gateway API CRD's OpenAPI schema enforces on `Listener.hostname`
5007/// and `HTTPRoute.spec.hostnames[]`,
5008/// `^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
5009/// (max length 253; per-label max length 63):
5010///
5011///   - lowercase RFC 1123 DNS subdomain (`[a-z0-9-]` only; no
5012///     uppercase, no underscore, no Unicode/IDN — IDN must be
5013///     pre-encoded as Punycode `xn--…` by the author);
5014///   - exactly one optional leading wildcard label (`*.`); a wildcard
5015///     in any non-leading label position is rejected;
5016///   - each `.`-separated label is 1..=63 bytes, with non-hyphen
5017///     alphanumeric at both boundaries (no `-foo`, no `foo-`);
5018///   - total length 1..=253 bytes;
5019///   - no IPv4 literal (Gateway API forbids IP literals);
5020///   - no scheme (`https://`, `http://`), no port (`:8080`), no
5021///     whitespace, no path (`/`).
5022///
5023/// Lifted as a typed gate (rather than an inline cascade in
5024/// `validate()`) so the contract lives in one place — every future
5025/// per-host axis (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5026/// materializer's host validator, the future per-`:entrada` SAN
5027/// emission for cert-manager Certificates, the multi-`:entrada`
5028/// host-collision gate when M4 lands `:entrada` as a `Vec`) reaches
5029/// for the same predicate, not its own. Same compounding shape as
5030/// `is_canonical_rate_limit_window` (808017c) and
5031/// [`WitTarget::label`] (previously the free `contrato_target_label`
5032/// helper, 5dbcfaf; lifted onto the typed [`WitTarget`] enum so the
5033/// per-variant label match is compiler-checked-exhaustive).
5034///
5035/// The diagnostic carries the offending `host:` verbatim plus a
5036/// parser-shaped `reason:` naming the specific violation, so the
5037/// author can grep their caixa.lisp for `:host "<host>"` and fix it
5038/// in one edit. Same diagnostic shape as `MembroVersaoInvalid`
5039/// (9888b13).
5040fn validate_entrada_host(host: &str) -> Result<(), AplicacaoError> {
5041    // Empty is already gated by `EmptyEntradaHost` at the call site;
5042    // re-checking here keeps the predicate usable from any future
5043    // call site (M4 CR materializer) without an empty-check footgun.
5044    if host.is_empty() {
5045        return Err(AplicacaoError::EmptyEntradaHost);
5046    }
5047    if host.len() > crate::render::GATEWAY_API_HOSTNAME_MAX_LEN {
5048        return Err(AplicacaoError::entrada_host_invalid(
5049            host,
5050            format!(
5051                "exceeds Gateway API v1 Hostname max length of {cap} bytes \
5052                 (got {} bytes; the K8s apiserver rejects longer hostnames at admission time)",
5053                host.len(),
5054                cap = crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
5055            ),
5056        ));
5057    }
5058    if host.contains("://") {
5059        return Err(AplicacaoError::entrada_host_invalid(
5060            host,
5061            "must not carry a scheme (drop the `https://` or `http://` prefix; \
5062             Gateway API takes the bare hostname)",
5063        ));
5064    }
5065    if host.contains('/') {
5066        return Err(AplicacaoError::entrada_host_invalid(
5067            host,
5068            "must not carry a path (drop the `/…` suffix; Gateway API path \
5069             matching is in `:entrada :paths`)",
5070        ));
5071    }
5072    // After the `://` scheme-prefix and `/` path arms have ruled out the
5073    // two `:`-bearing shapes the Gateway API actively rejects with
5074    // location-shaped diagnostics, any remaining `:` in the host body is
5075    // either the canonical "I put the port in the `:host` slot"
5076    // authoring footgun (`"checkout.quero.cloud:8080"` — the `:port`
5077    // slot lives one axis away on the same `:entrada` block) or an
5078    // unbracketed IPv6 literal (`"2001:db8::1"`) which Gateway API v1
5079    // Hostname forbids identically to the IPv4-literal arm below. Both
5080    // shapes silently fell through the `://` and `/` arms before this
5081    // lift and surfaced as a deep `label "<rest>:<port>" contains
5082    // invalid character ':'` diagnostic from the per-byte loop near the
5083    // bottom of this predicate, which named the offending byte but not
5084    // the canonical authoring fix — for the port case the author has to
5085    // know the `:entrada` block carries a separate `:port u16` slot
5086    // (`caixa-core/src/aplicacao.rs:1667`, `default_port = 8080`) and
5087    // move the value over; for the IPv6 case the author has to know
5088    // Gateway API v1 forbids IP literals across the board. The contract
5089    // doc-comment above already promises "no port (`:8080`)" verbatim
5090    // in the rejected-shape enumeration but the predicate's
5091    // implementation refused the `:` only as a side-effect of the
5092    // per-label `[a-z0-9-]` character-class loop; this arm brings the
5093    // implementation in line with the documented contract by surfacing
5094    // the canonical fix at the top-level shape gate, peer with how the
5095    // `://` arm names the scheme prefix and the `/` arm names the
5096    // `:entrada :paths` axis. Same compounding trajectory the recent
5097    // `is_gateway_api_http_path` (6a17961) per-byte tightening followed
5098    // — the typed slot's rejected set matches the apiserver's rejected
5099    // set, structurally, with a self-locating diagnostic at the
5100    // offending axis instead of a deep parser-shape leak.
5101    if host.contains(':') {
5102        return Err(AplicacaoError::entrada_host_invalid(
5103            host,
5104            "must not contain `:` (the port belongs in the `:entrada :port` \
5105             slot — a separate `u16` axis on the same `:entrada` block, \
5106             defaulting to 8080 — not in the host body; drop the `:<port>` \
5107             suffix and author the bare hostname. If you intended an IPv6 \
5108             literal (`2001:db8::1` / `::1` / `fe80::1`), Gateway API v1 \
5109             Hostname forbids IP literals identically to the IPv4-literal \
5110             arm — use a DNS name)",
5111        ));
5112    }
5113    // Routed through the lifted [`crate::render::find_ascii_whitespace_byte`]
5114    // predicate — the same single source of truth every peer
5115    // ASCII-whitespace scan in caixa-core flows through: the four
5116    // typed-magnitude codec sites (`limits::parse_byte_size` backing
5117    // `:limits :memory`, `limits::parse_duration` backing `:limits
5118    // :wall-clock`, `limits::parse_millicores` backing `:limits :cpu`,
5119    // `aplicacao::rate_limit_codec::parse` backing `:politicas
5120    // :rate-limit`) and the shared duration codec
5121    // (`supervisor::duration_codec::parse`) backing `:supervisor
5122    // :restart-window` / `:politicas :timeout` / `:politicas
5123    // :circuit-breaker :window`. This landing closes the last string-typed
5124    // slot in caixa-core still calling `.bytes().any(|b|
5125    // b.is_ascii_whitespace())` inline — every ASCII-whitespace scan
5126    // across every typed slot now shares one predicate, so a future
5127    // stricter classification (BOM `\u{FEFF}` / ZWSP `\u{200B}` / ZWJ
5128    // `\u{200D}` — the "invisible but not `char::is_whitespace`" class
5129    // deliberately excluded from the peer non-ASCII predicate) can
5130    // extend at this shared site in one edit rather than seven
5131    // independent scans diverging over time. Naming the offending byte
5132    // in the diagnostic (`0x20` space / `0x09` tab / `0x0a` LF / `0x0c`
5133    // FF / `0x0d` CR) matches the substrate-wide "the diagnostic carries
5134    // the offending byte verbatim" discipline every peer codec site
5135    // already carries (`limits.rs:722` / `limits.rs:784` / `limits.rs:845`
5136    // / `supervisor.rs:823` / `aplicacao.rs:1640`).
5137    if let Some(b) = crate::render::find_ascii_whitespace_byte(host) {
5138        return Err(AplicacaoError::entrada_host_invalid(
5139            host,
5140            format!(
5141                "contains ASCII whitespace byte 0x{b:02x} (Gateway API v1 \
5142                 Hostname is a single-token DNS name — leading, trailing, \
5143                 or embedded whitespace breaks the K8s apiserver's Hostname \
5144                 regex at admission time; the paste-from-aligned-doc / \
5145                 paste-from-shell-history / paste-from-CSV footgun silently \
5146                 lands a multi-token blob in `:entrada :host`. Strip every \
5147                 whitespace byte and author the bare hostname — space \
5148                 `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d` all \
5149                 refuse identically)"
5150            ),
5151        ));
5152    }
5153    // Peer of the ASCII-whitespace scan above: route the non-ASCII
5154    // subset of Unicode `White_Space` through the shared
5155    // [`crate::render::find_non_ascii_whitespace_char`] predicate — the
5156    // single source of truth every peer non-ASCII-whitespace scan in
5157    // caixa-core flows through: `limits::parse_byte_size` (`:limits
5158    // :memory`), `limits::parse_duration` (`:limits :wall-clock`),
5159    // `limits::parse_millicores` (`:limits :cpu`),
5160    // `aplicacao::rate_limit_codec::parse` (`:politicas :rate-limit`),
5161    // and `supervisor::duration_codec::parse` (`:supervisor
5162    // :restart-window` / `:politicas :timeout` / `:politicas
5163    // :circuit-breaker :window`). Before this arm, a NBSP-prefixed host
5164    // (`"\u{00A0}checkout.quero.cloud"` — paste-from-typography), a
5165    // LINE-SEPARATOR-suffixed host (`"checkout.quero.cloud\u{2028}"` —
5166    // paste-from-web-doc), or an EM-SPACE-split host
5167    // (`"checkout.\u{2003}quero.cloud"` — paste-from-typography)
5168    // survived this predicate's ASCII byte-scan (none of the UTF-8
5169    // bytes of `\u{00A0}` / `\u{2028}` / `\u{2003}` match
5170    // `u8::is_ascii_whitespace`), then landed on the per-label
5171    // `bytes[0].is_ascii_alphanumeric()` arm near the bottom of this
5172    // predicate with the generic `label "…" must start and end with an
5173    // alphanumeric` diagnostic — a "far from source at build-time"
5174    // leak that names the label-shape violation but not the
5175    // paste-from-typography origin the author actually needs to fix.
5176    // Peer with the four codec sites the 1b75b38 landing pinned: the
5177    // typed slot's diagnostic axis names the offending codepoint
5178    // (`U+XXXX`) verbatim rather than laundering the value through a
5179    // downstream label-shape arm, so the author can grep their
5180    // caixa.lisp for the invisible codepoint at the surfaced position
5181    // rather than eyeball a multi-byte host for embedded NBSP / LINE
5182    // SEPARATOR / EM-SPACE. Same "single lifted source of truth"
5183    // discipline the peer ASCII-whitespace arm (720ac3b) carries:
5184    // drift between any two typed-slot sites' non-ASCII-whitespace
5185    // rejection set becomes a single-edit fix at the shared predicate
5186    // rather than N independent inline scans diverging over time, and
5187    // a future stricter classification (BOM `\u{FEFF}` / ZWSP
5188    // `\u{200B}` / ZWJ `\u{200D}` — the "invisible but not
5189    // `char::is_whitespace`" class the peer non-ASCII predicate's
5190    // doc-comment names as the follow-up trajectory) extends at the
5191    // shared predicate in one edit rather than seven.
5192    if let Some(ch) = crate::render::find_non_ascii_whitespace_char(host) {
5193        return Err(AplicacaoError::entrada_host_invalid(
5194            host,
5195            format!(
5196                "contains non-ASCII Unicode whitespace character {ch:?} \
5197                 (U+{codepoint:04X}) — Gateway API v1 Hostname is a \
5198                 single-token DNS name limited to `[a-z0-9-]` labels; \
5199                 the paste-from-typography footgun silently lands an \
5200                 invisible codepoint (NBSP `U+00A0`, LINE SEPARATOR \
5201                 `U+2028`, EM-SPACE `U+2003`, IDEOGRAPHIC SPACE \
5202                 `U+3000`, and every other member of the Unicode \
5203                 `White_Space` property outside the ASCII byte range) \
5204                 in `:entrada :host`, which the K8s apiserver's \
5205                 Hostname regex refuses at admission time far from the \
5206                 caixa.lisp source line. Strip every non-ASCII \
5207                 whitespace character and author the bare hostname \
5208                 with only ASCII bytes (write \"checkout.quero.cloud\" \
5209                 verbatim)",
5210                codepoint = ch as u32,
5211            ),
5212        ));
5213    }
5214
5215    // Strip the optional single leading wildcard label *before* the
5216    // trailing-dot check so the bare `"*."` form surfaces the more
5217    // self-locating "wildcard without domain" diagnostic instead of
5218    // the generic "trailing dot" one.
5219    let (had_wildcard, rest) = match host.strip_prefix("*.") {
5220        Some(r) => (true, r),
5221        None => (false, host),
5222    };
5223    if had_wildcard && rest.is_empty() {
5224        return Err(AplicacaoError::entrada_host_invalid(
5225            host,
5226            "wildcard `*.` must be followed by a domain (e.g. `*.example.com`)",
5227        ));
5228    }
5229    if rest.contains('*') {
5230        return Err(AplicacaoError::entrada_host_invalid(
5231            host,
5232            "wildcard `*` is allowed only as the first label (`*.example.com`); \
5233             no inner or trailing `*` labels",
5234        ));
5235    }
5236    if rest.ends_with('.') {
5237        return Err(AplicacaoError::entrada_host_invalid(
5238            host,
5239            "must not have a trailing `.` (Gateway API hostnames are not \
5240             fully-qualified with a root dot; the apiserver regex rejects \
5241             trailing dots)",
5242        ));
5243    }
5244
5245    // Reject pure IPv4 literals: four dot-separated labels, every
5246    // label all-ASCII-digits. Gateway API v1 explicitly forbids IP
5247    // literals as Hostnames.
5248    let labels: Vec<&str> = rest.split('.').collect();
5249    if labels.len() == 4
5250        && labels
5251            .iter()
5252            .all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_digit()))
5253    {
5254        return Err(AplicacaoError::entrada_host_invalid(
5255            host,
5256            "must not be an IPv4 literal (Gateway API v1 Hostname forbids IP \
5257             literals; use a DNS name)",
5258        ));
5259    }
5260
5261    // Per-label shape: 1..=63 bytes, lowercase ASCII alphanumeric +
5262    // hyphen, with non-hyphen at both boundaries.
5263    for label in &labels {
5264        if label.is_empty() {
5265            return Err(AplicacaoError::entrada_host_invalid(
5266                host,
5267                "has an empty label (consecutive `..` or a leading `.`)",
5268            ));
5269        }
5270        if label.len() > crate::render::DNS_1123_LABEL_MAX_LEN {
5271            return Err(AplicacaoError::entrada_host_invalid(
5272                host,
5273                format!(
5274                    "label {label:?} exceeds DNS-1123 label max length of \
5275                     {cap} bytes (got {} bytes)",
5276                    label.len(),
5277                    cap = crate::render::DNS_1123_LABEL_MAX_LEN,
5278                ),
5279            ));
5280        }
5281        let bytes = label.as_bytes();
5282        if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
5283            return Err(AplicacaoError::entrada_host_invalid(
5284                host,
5285                format!(
5286                    "label {label:?} must start and end with an alphanumeric \
5287                     (no leading or trailing `-`)"
5288                ),
5289            ));
5290        }
5291        for &b in bytes {
5292            let valid = b.is_ascii_digit() || b.is_ascii_lowercase() || b == b'-';
5293            if !valid {
5294                let msg = if b.is_ascii_uppercase() {
5295                    format!(
5296                        "label {label:?} contains uppercase character {ch:?} \
5297                         (Gateway API hostnames are lowercase-only; use {lower:?})",
5298                        ch = b as char,
5299                        lower = label.to_ascii_lowercase()
5300                    )
5301                } else if b == b'_' {
5302                    format!(
5303                        "label {label:?} contains `_` (Gateway API hostnames \
5304                         allow only `[a-z0-9-]`; use `-` instead)"
5305                    )
5306                } else {
5307                    format!(
5308                        "label {label:?} contains invalid character {ch:?} \
5309                         (Gateway API hostnames allow only `[a-z0-9-]`)",
5310                        ch = b as char
5311                    )
5312                };
5313                return Err(AplicacaoError::entrada_host_invalid(host, msg));
5314            }
5315        }
5316    }
5317    Ok(())
5318}
5319
5320/// Reject `:entrada :paths` entries the K8s Gateway API v1 apiserver
5321/// would refuse at admission time. Thin wrapper around
5322/// [`crate::render::is_gateway_api_http_path`] that maps the shared
5323/// parser-shaped reason into the [`AplicacaoError::EntradaPathInvalid`]
5324/// variant, preserving the more self-locating
5325/// [`AplicacaoError::EntradaPathEmpty`] /
5326/// [`AplicacaoError::EntradaPathNotAbsolute`] diagnostics when the
5327/// path fails those narrower invariants first.
5328///
5329/// The contract is the canonical HTTP-path grammar — `1..=
5330/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`] (1024) bytes,
5331/// leading `/`, no consecutive `/`, no `.`/`..` segments, no `?`/`#`/
5332/// whitespace/control/non-ASCII bytes — shared with the
5333/// `:contratos :endpoint` axis through the lifted predicate so drift
5334/// between either landing site and the K8s apiserver-side
5335/// HTTPPathMatch.value OpenAPI schema is a build error visible at
5336/// the predicate, not a per-renderer "this passed validate but failed
5337/// admission" surprise. The diagnostic carries the offending `path:`
5338/// verbatim plus a parser-shaped `reason:` naming the specific
5339/// violation, so the author can grep their caixa.lisp for `:paths`
5340/// and fix it in one edit. Same diagnostic shape as
5341/// [`AplicacaoError::ContratoEndpointInvalid`] on the peer HTTP-path
5342/// axis.
5343fn validate_entrada_path(path: &str) -> Result<(), AplicacaoError> {
5344    // Empty and missing-leading-`/` are already gated at the call
5345    // site by `EntradaPathEmpty` and `EntradaPathNotAbsolute`; re-
5346    // checking here keeps the per-axis narrower diagnostics in force
5347    // when the predicate is reached directly (and `is_gateway_api_http_path`
5348    // itself defends against `bytes[0]`-style indexing on empty
5349    // input).
5350    if path.is_empty() {
5351        return Err(AplicacaoError::EntradaPathEmpty);
5352    }
5353    if !path.starts_with('/') {
5354        return Err(AplicacaoError::entrada_path_not_absolute(path));
5355    }
5356    crate::render::is_gateway_api_http_path(path)
5357        .map_err(|reason| AplicacaoError::entrada_path_invalid(path, reason))
5358}
5359
5360mod rate_limit_codec {
5361    // `Duration` is no longer named here — the codec routes through
5362    // the substrate primitive [`super::RateLimitUnit::window_from_suffix`]
5363    // (parse arm, `&str → Duration`) and [`super::RateLimit::canonical_unit`]
5364    // (render arm, `Duration → RateLimitUnit`) typed dispatches that carry
5365    // the canonical `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection on the
5366    // closed-set enum's arm-table rather than through vestigial free-helper
5367    // delegates.
5368    use super::{RateLimit, RateLimitUnit};
5369    use serde::{Deserializer, Serializer};
5370
5371    pub fn serialize<S: Serializer>(v: &Option<RateLimit>, s: S) -> Result<S::Ok, S::Error> {
5372        // Route through the canonical [`crate::render::serialize_option_via_str`]
5373        // — the substrate-side single-owner primitive for the forward
5374        // arm of the typed-magnitude codec family. See its docstring
5375        // for the full sibling roster.
5376        crate::render::serialize_option_via_str(v, s, render)
5377    }
5378
5379    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RateLimit>, D::Error> {
5380        // Route through the canonical [`crate::render::deserialize_option_via_str`]
5381        // — the substrate-side single-owner primitive for the reverse
5382        // arm of the typed-magnitude codec family. See its docstring
5383        // for the full sibling roster.
5384        crate::render::deserialize_option_via_str(d, parse)
5385    }
5386
5387    fn parse(s: &str) -> Result<RateLimit, String> {
5388        // Paired whitespace-rejection arm — same canonical-form
5389        // render-determinism discipline as the peer
5390        // `limits::parse_byte_size` / `limits::parse_duration` /
5391        // `limits::parse_millicores` /
5392        // `supervisor::duration_codec::parse` sites: the ASCII
5393        // byte-scan closes the WhatWG-conformant whitespace bytes
5394        // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
5395        // `char::is_whitespace` scan closes the strictly-complementary
5396        // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
5397        // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
5398        // codepoints) that `str::trim` at parse entry silently strips.
5399        // Either drift class would round-trip through `render` to a
5400        // *different* canonical form on next emit — breaking the
5401        // THEORY.md Part V render-determinism contract on
5402        // `:politicas :rate-limit`.
5403        //
5404        // Routed through the lifted [`crate::render::reject_whitespace`]
5405        // primitive — the substrate-side single-owner paired-arm gate
5406        // every typed-magnitude codec in caixa-core shares.
5407        crate::render::reject_whitespace::<String, _, _>(
5408            s,
5409            |b| {
5410                format!(
5411                    "rate-limit: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
5412                 authoring form for `:politicas :rate-limit` is `<integer>/<s|m|h>` (e.g. \
5413                 `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) with no whitespace bytes \
5414                 anywhere. A whitespace-carrying shape (`\" 100/s\"`, `\"100/s \"`, \
5415                 `\"100 /s\"`, `\"100/ s\"`, `\"100 / s\"`, `\"100/s\\n\"`, `\"\\t100/s\"`) \
5416                 round-trips through `render` to a *different* canonical form (`\"100/s\"`) \
5417                 on first serialize — breaking the THEORY.md Part V render-determinism \
5418                 contract every typed slot carries. Strip every whitespace byte (write \
5419                 `\"100/s\"` verbatim)"
5420                )
5421            },
5422            |ch| {
5423                format!(
5424                    "rate-limit: value {s:?} contains non-ASCII Unicode whitespace character \
5425                 {ch:?} (U+{cp:04X}) — the canonical authoring form for `:politicas \
5426                 :rate-limit` is `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, \
5427                 `\"10000/h\"`) with no whitespace characters anywhere (ASCII or Unicode). \
5428                 A non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}100/s\"`, \
5429                 `\"100/s\\u{{2028}}\"`, `\"100\\u{{2003}}/s\"`) survives the ASCII \
5430                 byte-scan but `str::trim` (which uses `char::is_whitespace` — the \
5431                 Unicode `White_Space` property, strictly wider than the ASCII byte set) \
5432                 silently strips it at parse entry, and the value round-trips through \
5433                 `render` to a *different* canonical form (`\"100/s\"`) on first \
5434                 serialize — breaking the THEORY.md Part V render-determinism contract \
5435                 every typed slot carries. Strip every non-ASCII whitespace character \
5436                 (write `\"100/s\"` verbatim with only ASCII bytes)",
5437                    cp = ch as u32
5438                )
5439            },
5440        )?;
5441        let s = s.trim();
5442        let (rate_str, unit) = s
5443            .split_once('/')
5444            .ok_or_else(|| format!("rate-limit must be `<n>/<unit>`, got {s:?}"))?;
5445        let rate_trim = rate_str.trim();
5446        // The canonical authoring form for `:politicas :rate-limit` is
5447        // `<integer>/<s|m|h>` — every magnitude [`render`] emits is a
5448        // non-negative integer with no decimal point and no leading
5449        // sign, so the parser's accepted set must match for
5450        // serialize/deserialize to round-trip without canonical-form
5451        // drift. Until this gate landed the parser accepted any
5452        // `u32::from_str`-shaped magnitude — and current Rust
5453        // `u32::from_str` permissively accepts a leading `+` (`"+100"`
5454        // → 100), so `"+100/s"` parsed to `RateLimit { 100, 1s }` and
5455        // serde silently round-tripped to `"100/s"` on the next emit
5456        // (a *different* canonical string) — breaking the THEORY.md
5457        // Part V render-determinism contract on the fifth typed-codec
5458        // surface in caixa-core (peer with the four duration codecs the
5459        // 1c55a2a / 818dd38 / d1fd67b / 737a676 / d53c922 trajectory
5460        // already covered: `supervisor::duration_codec` backing three
5461        // typed-duration slots, `limits::parse_duration` backing
5462        // `:limits :wall-clock`, `limits::parse_byte_size` backing
5463        // `:limits :memory`). The fractional / decimal-shaped sibling
5464        // (`"1.5/s"`, `"1.0/s"`, `"0.5/m"`) lands on `u32::from_str`'s
5465        // existing rejection arm, but the diagnostic is value-laundered
5466        // (the bare `"rate-limit rate \"1.5\" not a u32"` wording
5467        // doesn't name the canonical-form remediation or the round-trip
5468        // drift the next emit would produce); this gate lifts the
5469        // fractional arm onto the same canonical-form diagnostic the
5470        // peer codecs carry.
5471        //
5472        // Strict canonical form: every byte of the magnitude is an
5473        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
5474        // inputs the gate distinguishes "non-canonical-but-numeric"
5475        // (parses as f64 or i64 — surfaced with a self-locating
5476        // diagnostic naming the canonical authoring form and the
5477        // round-trip drift the rejected shape would produce on first
5478        // serialize) from "garbage" (parses as neither — surfaced with
5479        // the existing narrower `"not a u32"` wording so its
5480        // diagnostic shape remains stable for the parser-shape footgun
5481        // case).
5482        //
5483        // Routed through the lifted
5484        // [`crate::render::is_digit_only_magnitude`] predicate — the
5485        // same source of truth the four peer typed-magnitude codec
5486        // sites share.
5487        let digit_only = crate::render::is_digit_only_magnitude(rate_trim);
5488        if !digit_only {
5489            let numeric = rate_trim.parse::<f64>().is_ok() || rate_trim.parse::<i64>().is_ok();
5490            if numeric {
5491                return Err(format!(
5492                    "rate-limit: rate {rate_trim:?} is not a non-negative integer — the \
5493                     canonical authoring form for `:politicas :rate-limit` is \
5494                     `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
5495                     with no decimal point and no leading `+` / `-` sign. A fractional / \
5496                     signed magnitude (`\"1.5/s\"`, `\"+100/s\"`, `\"-1/s\"`) round-trips \
5497                     through `render` to a *different* canonical form (`\"1/s\"`, \
5498                     `\"100/s\"`, parser-reject) on first serialize — breaking the \
5499                     THEORY.md Part V render-determinism contract every typed slot \
5500                     carries. Pick an integer rate that fits the desired window \
5501                     (write `\"6000/m\"` instead of `\"1.66/s\"`)"
5502                ));
5503            }
5504            return Err(format!("rate-limit rate {rate_str:?} not a u32"));
5505        }
5506        // Leading-zero arm — peer with the prior `"+100/s"` arm above
5507        // (4eeae98's predecessor) on the same canonical-form
5508        // render-determinism axis. The digit-only gate accepts
5509        // `"0100/s"`, `"00/s"`, `"007/h"` as `u32::from_str` parses
5510        // them losslessly (= 100, 0, 7), but `render` emits the
5511        // leading-zero-stripped form (`"100/s"`, `"0/s"`, `"7/h"`) —
5512        // a *different* canonical string on the next emit, breaking
5513        // the THEORY.md Part V render-determinism contract the same
5514        // way `"+100/s"` did before the leading-`+` arm landed. The
5515        // single-byte magnitude `"0"` itself round-trips losslessly
5516        // through `render` (`render(0)` emits `"0/s"`) — the
5517        // downstream [`AplicacaoError::PolicyRateLimitZero`] gate is
5518        // what refuses rate-zero authoring, so `"0/s"` stays in the
5519        // accepted set at this codec layer and the diagnostic
5520        // partitioning between canonical-form drift (this arm) and
5521        // semantic-zero (the downstream gate) remains stable.
5522        // Peer with the future leading-zero arms on the three peer
5523        // typed-magnitude codecs the trajectory acknowledges:
5524        // `supervisor::duration_codec`, `limits::parse_duration`,
5525        // `limits::parse_byte_size` — each carries the same
5526        // canonical-form-drift class today; this gate lands the
5527        // discipline on the fourth typed-magnitude codec in
5528        // caixa-core first because the peer `"+100/s"` arm above is
5529        // the closest predecessor on the trajectory.
5530        //
5531        // Routed through the lifted
5532        // [`crate::render::is_leading_zero_padded_magnitude`]
5533        // predicate — the same source of truth the four peer
5534        // typed-magnitude codec sites share.
5535        if crate::render::is_leading_zero_padded_magnitude(rate_trim) {
5536            return Err(format!(
5537                "rate-limit: rate {rate_trim:?} has a non-canonical leading zero — the \
5538                 canonical authoring form for `:politicas :rate-limit` is \
5539                 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
5540                 with no leading-zero padding on the magnitude. A leading-zero magnitude \
5541                 (`\"0100/s\"`, `\"00/s\"`, `\"007/h\"`) round-trips through `render` to \
5542                 a *different* canonical form (`\"100/s\"`, `\"0/s\"`, `\"7/h\"`) on \
5543                 first serialize — breaking the THEORY.md Part V render-determinism \
5544                 contract every typed slot carries. Strip the leading zeros (write \
5545                 `\"100/s\"` instead of `\"0100/s\"`)"
5546            ));
5547        }
5548        // The digit-only gate guarantees every byte is `[0-9]`, and
5549        // the leading-zero arm above guarantees the magnitude is
5550        // either the single byte `"0"` or starts with `[1-9]`, so
5551        // the only way `u32::from_str` can fail here is overflow
5552        // (the magnitude exceeds `u32::MAX`). Surface that with an
5553        // overflow-shaped wording so the diagnostic names the
5554        // offending magnitude verbatim rather than collapsing onto
5555        // the non-canonical arm. Same shape
5556        // `supervisor::duration_codec` (1c55a2a) carries on the peer
5557        // duration-codec axis.
5558        let rate: u32 = rate_trim.parse::<u32>().map_err(|_| {
5559            format!("rate-limit rate {rate_trim:?} (digit-only magnitude overflows u32)")
5560        })?;
5561        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives on
5562        // the closed-set typed enum [`super::RateLimitUnit`]; this parse
5563        // arm reads the `&str → Duration` projection through the
5564        // substrate primitive [`super::RateLimitUnit::window_from_suffix`]
5565        // (a two-step typed dispatch composing [`super::RateLimitUnit::from_suffix`]
5566        // with [`super::RateLimitUnit::window`]) rather than the vestigial
5567        // module-private `rate_limit_window_from_unit` free helper the
5568        // predecessor 61421a6 left as the last unlifted delegate on this
5569        // axis. One typed dispatch on the substrate primitive instead of
5570        // one runtime call through the free-helper delegate; the sole
5571        // production consumer of the `&str → Duration` axis (this parse
5572        // arm) now reaches for exactly one typed method on the closed-set
5573        // enum, sibling to the codec's render arm's
5574        // [`super::RateLimit::canonical_unit`] dispatch on the paired
5575        // `Duration → RateLimitUnit` axis and to the validate gate's
5576        // [`super::RateLimit::canonical_unit`] shape-probe on the
5577        // canonical-window axis. A future rate-limit-unit addition (a
5578        // `"d"` day suffix once Envoy's `rate_limit_action` grows
5579        // daily-bucket support, a `"ms"` sub-second window once
5580        // high-throughput per-edge policies come into scope per
5581        // MESH-COMPOSITION §III.2 #3) is one variant + one arm per method
5582        // on the closed-set enum, and the compiler enforces exhaustiveness
5583        // on every consumer's `match self` arms — this parse arm's
5584        // accepted-suffix set, the render arm's emitted-suffix set, the
5585        // validate gate's canonical-window set, and every future
5586        // per-`:contratos`-edge rate-limit-override overlay all pick it up
5587        // by construction.
5588        let unit = unit.trim();
5589        let window = RateLimitUnit::window_from_suffix(unit)
5590            .ok_or_else(|| format!("unknown rate-limit window unit {unit:?}"))?;
5591        Ok(RateLimit { rate, window })
5592    }
5593
5594    fn render(rl: RateLimit) -> String {
5595        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
5596        // module scope on the closed-set typed enum [`super::RateLimitUnit`];
5597        // this render arm reads the `Duration → RateLimitUnit` projection
5598        // through the substrate primitive [`super::RateLimit::canonical_unit`]
5599        // (returns `None` on every non-canonical window — the sub-second /
5600        // non-`{1, 60, 3600}` shapes the validate gate rejects), then
5601        // formats the returned typed enum through its
5602        // [`std::fmt::Display`] impl (which routes through
5603        // [`super::RateLimitUnit::as_suffix`]). Two typed dispatches on
5604        // the substrate primitive instead of one runtime `find_map`
5605        // walk through the free-helper delegate chain
5606        // [`super::rate_limit_window_unit`] (the vestigial free helper's
5607        // sole production consumer was this arm; every other consumer of
5608        // the `Duration → unit` axis — the validate gate below and the
5609        // future M4 per-Aplicacao Envoy config reconciler — now reads
5610        // the same typed method).
5611        //
5612        // A future rate-limit-unit addition (a `"d"` day suffix once
5613        // Envoy's `rate_limit_action` grows daily-bucket support) is
5614        // one variant + one arm per method on the closed-set enum, and
5615        // the compiler enforces exhaustiveness on every consumer's
5616        // `match self` arms — the codec's `parse` accepted-suffix set,
5617        // this render arm's emitted-suffix set, the validate gate's
5618        // canonical-window set, and every future per-`:contratos`-edge
5619        // rate-limit-override overlay all pick it up by construction.
5620        if let Some(unit) = rl.canonical_unit() {
5621            format!("{}/{unit}", rl.rate())
5622        } else {
5623            // Defensive fallback for non-canonical windows. Note:
5624            // [`AplicacaoSpec::validate_politicas`] rejects any
5625            // non-canonical `:rate-limit :window` via
5626            // [`AplicacaoError::PolicyRateLimitWindowNotCanonical`], so
5627            // a validated `RateLimit` never reaches this branch. The
5628            // emitted `<n>/<k>s` form is *not* round-trippable through
5629            // [`parse`] (which accepts only the closed-set
5630            // [`super::RateLimitUnit`] suffixes, not `<k>s` with an
5631            // explicit count) — the validate gate is what makes the
5632            // round-trip a structural property; this branch exists only
5633            // so a programmatic non-validated serialize doesn't panic.
5634            format!("{}/{}s", rl.rate(), rl.window().as_secs())
5635        }
5636    }
5637}
5638
5639// ── placement strategy ───────────────────────────────────────────────
5640
5641/// How the Aplicacao distributes across clusters. Three options:
5642///
5643/// - `SingleNode` — one cluster runs the app at a time; takeover on
5644///   death (Erlang/OTP distributed-app semantics).
5645/// - `Replicated` — every named cluster runs an instance (active-active).
5646/// - `Sharded` — entities distribute by hash key across clusters
5647///   (Akka cluster sharding).
5648#[derive(
5649    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
5650)]
5651pub enum PlacementStrategy {
5652    SingleNode,
5653    Replicated,
5654    Sharded,
5655}
5656
5657/// Substrate-canonical M3-mesh-shaped per-`:placement :estrategia`
5658/// distribution-strategy default for the `:placement :estrategia` axis —
5659/// the [`PlacementStrategy::Replicated`] active-active-across-every-named-
5660/// cluster arm (MESH-COMPOSITION §II.2), extracted as a typed `pub const`
5661/// so every substrate-side consumer that resolves "what
5662/// [`PlacementStrategy`] variant does an author-omitted `:placement
5663/// :estrategia` slot degrade onto?" reaches for exactly one substrate-
5664/// primitive [`PlacementStrategy`].
5665///
5666/// The `:placement :estrategia` default axis has three production
5667/// consumers on the substrate side today: the [`Default for
5668/// PlacementStrategy`] impl's return arm, the [`Default for Placement`]
5669/// impl's struct-literal `estrategia` field, and the serde-side
5670/// `#[serde(default)]` on [`Placement::estrategia`] that resolves an
5671/// author-omitted `:placement :estrategia` scalar through the [`Default
5672/// for PlacementStrategy`] impl. Prior to this lift the three folded onto
5673/// a raw `Self::Replicated` arm at the [`Default for PlacementStrategy`]
5674/// impl and implicit `PlacementStrategy::default()` routes at the sibling
5675/// consumers, with no compile-time link back to the paired
5676/// [`crate::manifest::Caixa::aplicacao_view`] fold's
5677/// `.unwrap_or_default()` `Option<Placement>` collapse arm — the fourth
5678/// production consumer that resolves an author-omitted `:placement` slot
5679/// (entirely omitted, not just the `:estrategia` scalar within a declared
5680/// `:placement` block) through [`Placement::default`] which then routes
5681/// through this same discriminator. A future coherent rebrand of the
5682/// `:placement :estrategia` default (a widening to `Sharded` once the
5683/// substrate discovers hash-keyed distribution as the more common
5684/// production shape, a tightening to `SingleNode` for stateful Erlang/OTP
5685/// distributed-app-takeover semantics MESH-COMPOSITION §II.1 already
5686/// names, a per-cluster overlay the operator pins through a future
5687/// `:placement-overrides` slot) would have had to migrate a lifted
5688/// discriminator on one path and open-coded discriminators on the peers
5689/// in lockstep or the four consumers would silently drift out of
5690/// pairing. Lifting the resolution rule to a typed `pub const` on the
5691/// substrate primitive means the M3-mesh-canonical `:placement
5692/// :estrategia` default migrates as one unit on any future axis change.
5693///
5694/// The [`PlacementStrategy::Replicated`] value pins MESH-COMPOSITION
5695/// §II.2's active-active-across-every-named-cluster arm — the closest
5696/// canonical M3 production reference the substrate carries, matching the
5697/// caixa-mesh default axis every M3 renderer already keys off (a
5698/// `programs.yaml` fan-out that emits one `HelmRelease` per cluster is
5699/// the canonical shape a `:membros`+`:contratos`-declared Aplicacao lands on
5700/// under the substrate's fleet-programs aggregator without an explicit
5701/// `:placement :estrategia` override). The two alternatives the closed
5702/// [`PlacementStrategy::ALL`] accept-set carries
5703/// ([`PlacementStrategy::SingleNode`] — Erlang/OTP distributed-app
5704/// takeover, MESH-COMPOSITION §II.1; [`PlacementStrategy::Sharded`] —
5705/// Akka-style hash-keyed distribution across clusters,
5706/// MESH-COMPOSITION §II.4) express deliberate takeover / hash-keyed
5707/// postures an author declares explicitly, never a posture an omitted
5708/// slot should silently assume.
5709///
5710/// Lifted as a typed `pub const` so the M3-mesh-canonical default has
5711/// exactly one source of truth on the `:placement :estrategia` axis, on
5712/// the same substrate-primitive lift discipline the sibling M2
5713/// per-supervisor default set carries
5714/// ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`],
5715/// [`crate::supervisor::SUPERVISOR_MAX_RESTARTS_DEFAULT`],
5716/// [`crate::supervisor::SUPERVISOR_RESTART_WINDOW_DEFAULT`],
5717/// [`crate::supervisor::SUPERVISOR_CHILD_RESTART_DEFAULT`]) and the peer
5718/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes
5719/// ([`crate::render::DEFAULT_NAMESPACE`],
5720/// [`crate::render::DEFAULT_LIBRARY_NAME`],
5721/// [`crate::render::DEFAULT_SERVICO_PORT`]). The first typed default on
5722/// the M3 mesh-primitive-defining slot family to converge onto the
5723/// substrate-primitive-lift discipline the M2 supervisor-slot family
5724/// already carries end-to-end.
5725pub const PLACEMENT_ESTRATEGIA_DEFAULT: PlacementStrategy = PlacementStrategy::Replicated;
5726
5727impl Default for PlacementStrategy {
5728    fn default() -> Self {
5729        // Route the [`Default for PlacementStrategy`] impl through the
5730        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
5731        // `pub const` rather than a raw `Self::Replicated` arm — one
5732        // source of truth for the M3-mesh-canonical active-active-
5733        // across-every-named-cluster `:placement :estrategia` default
5734        // (MESH-COMPOSITION §II.2), on the same substrate-primitive
5735        // lift discipline the sibling M2 per-supervisor default set
5736        // ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`] +
5737        // paired halves) carries end-to-end. Pinned by
5738        // `placement_strategy_default_routes_through_lifted_default`.
5739        PLACEMENT_ESTRATEGIA_DEFAULT
5740    }
5741}
5742
5743impl PlacementStrategy {
5744    /// Exhaustive iteration surface for every consumer that reads the
5745    /// full closed-set (the future M4 admission-webhook's accepted-
5746    /// strategy listing in its rejection body, a future `feira app
5747    /// placement --list` CLI-side surfacing of the accepted arm-set,
5748    /// any future round-trip fuzz harness). A future variant addition
5749    /// (an `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint
5750    /// names as a trajectory item) extends this slice as a single edit
5751    /// and every consumer picks up the new entry by construction — the
5752    /// compiler-checked exhaustiveness on the sibling method `match`
5753    /// arms is the build-time guarantee that no arm forgets to grow.
5754    /// Same shape as the sibling closed-set typed enums'
5755    /// [`RateLimitUnit::ALL`] (6bce03d) and
5756    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
5757    /// surfaces — the third closed-set typed enum on the caixa surface
5758    /// to converge onto the same discipline.
5759    pub const ALL: &'static [Self] = &[Self::SingleNode, Self::Replicated, Self::Sharded];
5760
5761    /// Canonical camelCase-schema discriminator scalar this variant
5762    /// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
5763    /// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
5764    /// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5765    /// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
5766    /// every substrate consumer that dispatches on the strategy (the
5767    /// `lareira-fleet-programs` aggregator, the future `app-operator`
5768    /// reconciler, the M3 Adaptive compression pass) reads the same
5769    /// byte-string the `Serialize` derive emits — the pin test in
5770    /// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
5771    /// asserts the two paths agree.
5772    #[must_use]
5773    pub const fn as_str(self) -> &'static str {
5774        match self {
5775            Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
5776            Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
5777            Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
5778        }
5779    }
5780
5781    /// Substrate-canonical reverse projection on the `:placement
5782    /// :estrategia` closed-set axis — parses the camelCase-schema
5783    /// discriminator scalar back to the typed variant, or `None` when
5784    /// `s` is outside the closed-set arm-string set [`Self::as_str`]
5785    /// emits. Dispatches on the same lifted
5786    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
5787    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5788    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] constants the
5789    /// [`Self::as_str`] emitter walks, so the parse and emit halves of
5790    /// the round-trip migrate through one caixa-core edit on any future
5791    /// arm addition (an `Anycast` mesh-anycast arm the MESH-COMPOSITION
5792    /// §II.5 hint names as a trajectory item lands one variant + one
5793    /// arm per method and the compiler enforces exhaustiveness on every
5794    /// consumer's `match self` arms).
5795    ///
5796    /// Prior to this lift the substrate carried only the forward
5797    /// `Self → &str` projection (the [`Self::as_str`] emitter, the
5798    /// [`std::fmt::Display`] impl routed through it, the `Serialize`
5799    /// derive that emits the same byte-string under
5800    /// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]) — every non-serde
5801    /// consumer that wanted to parse a wire-form strategy scalar had to
5802    /// re-inline a three-arm `match s { "SingleNode" => …, "Replicated"
5803    /// => …, "Sharded" => …, _ => … }` cascade that expressed no
5804    /// compile-time link back to the typed variant's canonical lifted
5805    /// constant. A future variant rename or a per-arm serde-attribute
5806    /// drift would silently split the wire byte-string one non-serde
5807    /// consumer parsed from the one the emitter wrote, with the
5808    /// failure surfacing at parse time far from the rebrand commit.
5809    ///
5810    /// Same closed-set-reverse-projection discipline the sibling
5811    /// [`crate::CaixaKind::from_wire`] (2aa6d23) and
5812    /// [`RateLimitUnit::from_suffix`] typed enums carry on the peer
5813    /// wire-side `str → Self` axes — extended onto the M3 mesh-primitive-
5814    /// defining `:placement :estrategia` closed-set axis, the third
5815    /// substrate-side closed-set typed enum to converge on the two-way
5816    /// `str ↔ Self` round-trip. Method-named `from_wire` (not `from_str`)
5817    /// to match the peer [`crate::CaixaKind::from_wire`] shape verbatim
5818    /// and side-step the [`std::str::FromStr`]-collision clippy
5819    /// (`clippy::should_implement_trait`) the plain `from_str` name
5820    /// carries; a future explicit [`std::str::FromStr`] impl can layer
5821    /// on top by delegating to this canonical arm-dispatch method.
5822    ///
5823    /// Returns `Option<Self>` (rather than `Result<Self, _>`) to match
5824    /// the sibling [`crate::CaixaKind::from_wire`] shape: the caller
5825    /// picks the diagnostic form appropriate for its use site — a
5826    /// future `feira app placement --set` CLI-side arg-parse that wants
5827    /// an `"unknown strategy: {s} (accepted: SingleNode, Replicated,
5828    /// Sharded)"` diagnostic builds one on top by iterating
5829    /// [`Self::ALL`], while the future M4 admission-webhook's rejection
5830    /// path folds `None` onto its per-CR structured refusal body.
5831    #[must_use]
5832    pub fn from_wire(s: &str) -> Option<Self> {
5833        match s {
5834            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE => Some(Self::SingleNode),
5835            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED => Some(Self::Replicated),
5836            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED => Some(Self::Sharded),
5837            _ => None,
5838        }
5839    }
5840
5841    /// Substrate-canonical per-arm predicate naming the cross-slot
5842    /// `:placement :estrategia` ↔ `:placement :shard-key` invariant on the
5843    /// closed-set typed [`PlacementStrategy`] enum: `true` iff the strategy
5844    /// consumes the paired [`Placement::shard_key`] axis (and therefore
5845    /// requires — and is the only strategy that permits — a non-empty
5846    /// `:shard-key` on the paired slot). Today the accept-set is the
5847    /// singleton `{Sharded}` — `Sharded` is the sole Akka-style
5848    /// hash-keyed distribution arm (MESH-COMPOSITION §II.4) that keys off a
5849    /// per-entity extractor expression; `SingleNode` (Erlang/OTP
5850    /// distributed-app takeover — §II.1) and `Replicated` (active-active
5851    /// across every named cluster) have no hash-keyed routing axis to
5852    /// consume the slot and refuse a declared-but-inert `:shard-key`
5853    /// through [`AplicacaoError::ShardKeyOnNonSharded`].
5854    ///
5855    /// Every validated [`Placement`] past [`AplicacaoSpec::validate_placement`]
5856    /// satisfies `placement.shard_key().is_some() ==
5857    /// placement.estrategia().requires_shard_key()` by construction — the
5858    /// cross-slot partition the pin
5859    /// [`tests::validate_placement_admits_paired_shape_iff_strategy_requires_shard_key`]
5860    /// locks load-bearing, so every downstream consumer that reaches for
5861    /// the paired shape (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
5862    /// CR materializer's per-CR shard-key resolver, the future
5863    /// [`feira app graph --shard-key`] per-Aplicacao column, the future
5864    /// per-cluster Akka-style cluster-sharding reconciler's per-entity
5865    /// hash-routing gate, the M5 adaptive-placement engine's per-strategy
5866    /// shard-key requirement probe, a future author-facing tatara-lisp
5867    /// linter that flags `(:placement (:estrategia Replicated :shard-key
5868    /// "tenantId"))` shapes before `feira lint` reaches
5869    /// [`AplicacaoSpec::validate`]) can reach for one typed dispatch on
5870    /// the substrate primitive — the predicate names *the cross-slot
5871    /// invariant*, not the arm identity.
5872    ///
5873    /// Prior to this lift the "does this strategy consume `:shard-key`"
5874    /// classification lived under the `gen_platform::IsVariant`-derived
5875    /// [`Self::is_sharded`] predicate at three fixture-builder sites in
5876    /// this crate (the [`tests::placement_strategy_variants_round_trip`]
5877    /// per-variant `Placement`-builder's `if s.is_sharded() { Some("$key"…)
5878    /// } else { None }` cascade, the
5879    /// [`tests::estrategia_returns_placement_estrategia_verbatim_across_permutations`]
5880    /// per-variant `Placement`-builder's `estrategia.is_sharded().then(||
5881    /// "tenantId".to_string())` cascade, and the
5882    /// [`tests::validate_placement_reads_through_lifted_estrategia_accessor`]
5883    /// per-variant spec-mutator's identical `.is_sharded().then(…)`
5884    /// cascade). Each site conflated two semantically distinct questions:
5885    /// "is the variant `Sharded`?" (arm-identity, what
5886    /// [`Self::is_sharded`] answers) and "does the variant consume
5887    /// `:shard-key`?" (cross-slot-invariant, what this predicate answers).
5888    /// The two questions land on the same three-way answer under today's
5889    /// closed accept-set (both trip on the singleton `{Sharded}`), but a
5890    /// future arm addition that consumed `:shard-key` under a different
5891    /// name (a hypothetical `Anycast` mesh-anycast arm the MESH-COMPOSITION
5892    /// §II.5 roadmap-hint names that hash-partitions across the cluster
5893    /// pool by client-IP hash rather than an author-declared extractor
5894    /// expression, a hypothetical `WeightedShard` variant that carries a
5895    /// shard-key + per-cluster weight table under a promoted M5
5896    /// adaptive-placement engine) or an addition that did *not* consume
5897    /// `:shard-key` on a semantically Sharded-shaped arm would silently
5898    /// split the two questions. Any consumer that read
5899    /// `.is_sharded().then(…)` for the shard-key requirement gate would
5900    /// silently misclassify the new arm as non-consuming — a fixture
5901    /// builder would omit `:shard-key` where the new arm required one and
5902    /// [`AplicacaoSpec::validate_placement`] would refuse the fixture with
5903    /// [`AplicacaoError::ShardedWithoutKey`] far from the arm-addition
5904    /// commit, a future M4 CR materializer would fall through the
5905    /// `.is_sharded()`-only branch to the non-shard-key resolver arm and
5906    /// silently emit an empty extractor at the Akka reconciler layer.
5907    ///
5908    /// Lifting the classification as a substrate-primitive method on the
5909    /// closed-set typed enum names the cross-slot invariant on the
5910    /// primitive that owns the partition: every future arm addition
5911    /// declares its `:shard-key` consumption in one place (this predicate's
5912    /// `match self` arm-set), and every downstream consumer that reaches
5913    /// for the paired shape reads through one typed dispatch. Same
5914    /// discipline as the sibling [`WitContract::is_capability`] (7b97d26)
5915    /// per-arm predicate on the pre-projection WIT-shape axis and the
5916    /// [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
5917    /// paired predicate on the post-projection typed-view axis — a
5918    /// per-arm semantic-classification predicate paired with the
5919    /// arm-identity predicate the derive already emits, closing the drift
5920    /// footgun on the cross-slot invariant axis.
5921    ///
5922    /// Method-named `requires_shard_key` (not `has_shard_key`, not
5923    /// `is_shard_keyed`, not `takes_shard_key`) because the cross-slot
5924    /// invariant reads as "this strategy *requires* the paired
5925    /// `:shard-key` axis" — the `SingleNode`/`Replicated` arms *refuse*
5926    /// the axis through [`AplicacaoError::ShardKeyOnNonSharded`], not
5927    /// merely omit it. The `has_*` framing would read as an accessor
5928    /// (returning the presence of an already-carried value) rather than a
5929    /// requirement (naming the invariant the paired slot must satisfy).
5930    /// Returns `bool` (not `Option<()>` or a marker-type witness), same
5931    /// shape as the sibling [`WitContract::is_capability`] /
5932    /// [`Self::is_sharded`] per-arm boolean predicates on the closed-set
5933    /// arm-family, so every consumer reaches for `.requires_shard_key()`
5934    /// as a drop-in replacement for the `.is_sharded()` conflated read
5935    /// without a return-shape migration.
5936    #[must_use]
5937    pub const fn requires_shard_key(self) -> bool {
5938        match self {
5939            Self::Sharded => true,
5940            Self::SingleNode | Self::Replicated => false,
5941        }
5942    }
5943}
5944
5945// Compile-time pins on the [`PlacementStrategy::requires_shard_key`]
5946// cross-slot-invariant per-arm predicate: the module-scope const-eval
5947// assertions below trip at caixa-core build time (not test time) if a
5948// future edit rewires the predicate's arm-set away from the singleton
5949// `{Sharded}` accept-set MESH-COMPOSITION §II.4 pins. The
5950// [`tests::placement_strategy_requires_shard_key_partitions_the_arm_set`]
5951// runtime pin covers the same truth-table with a more descriptive
5952// diagnostic on failure; these const-eval items add a build-time failure
5953// surface strictly stronger than the runtime pin (a downstream renderer's
5954// `const`-context reader that composed against a rebound predicate would
5955// still surface here before the test suite even ran) and side-step the
5956// `clippy::assertions_on_constants` lint the runtime `assert!(CONST)` pin
5957// would otherwise accumulate on the caixa-core module baseline.
5958const _: () = assert!(!PlacementStrategy::SingleNode.requires_shard_key());
5959const _: () = assert!(!PlacementStrategy::Replicated.requires_shard_key());
5960const _: () = assert!(PlacementStrategy::Sharded.requires_shard_key());
5961
5962/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
5963/// the pretty-printed byte-string every consumer that formats the strategy
5964/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
5965/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
5966/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
5967/// per-Aplicacao strategy line, the future M4 CR materializer's per-
5968/// admission-webhook rejection body) reaches for the same lifted
5969/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
5970/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5971/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
5972/// `Serialize` derive already emits under
5973/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
5974/// [`PlacementStrategy::as_str`] helper already returns.
5975///
5976/// Until this lift landed the sibling OTP-shape typed enums —
5977/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
5978/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
5979/// so [`std::fmt::Display`] routes through the same discriminant string
5980/// the wire format emits) — carried a stable [`std::fmt::Display`]
5981/// surface but [`PlacementStrategy`] did not; every consumer reaching
5982/// for a strategy byte-string past the wire format had to pick between
5983/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
5984/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
5985/// derive), any two of which a future variant rename or
5986/// `#[serde(rename_all = "kebab-case")]` attribute would silently
5987/// desynchronize — with the failure surfacing as a downstream renderer /
5988/// operator's per-strategy dispatch reading one spelling while the wire
5989/// format emitted another, far from the source rebrand commit and with
5990/// no field naming the drift. Routing `Display` through
5991/// [`PlacementStrategy::as_str`] makes the three paths
5992/// (`Debug` for structural inspection, `Display` for user-facing text,
5993/// `Serialize` for the wire format) converge on the same lifted
5994/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
5995/// the diagnostic byte-string, and the pretty-printed byte-string move
5996/// as a single unit through one canonical declaration each, by
5997/// construction. Same trajectory as [`PlacementStrategy::as_str`]
5998/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
5999/// closes the third path.
6000///
6001/// Pin tests
6002/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
6003/// and
6004/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
6005/// assert the three paths agree byte-for-byte on every variant, so a
6006/// future variant rename or per-arm serde attribute drift is a build
6007/// error visible at caixa-core test time, not a silent per-consumer
6008/// dispatch miss at apply / reconcile time.
6009impl std::fmt::Display for PlacementStrategy {
6010    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6011        f.write_str(self.as_str())
6012    }
6013}
6014
6015/// Where the Aplicacao runs.
6016#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
6017#[serde(rename_all = "camelCase")]
6018pub struct Placement {
6019    /// Distribution strategy.
6020    #[serde(default)]
6021    pub estrategia: PlacementStrategy,
6022
6023    /// Named clusters that host this Aplicacao. Required for
6024    /// `Replicated` and `SingleNode`; for `Sharded` declares the
6025    /// shard pool.
6026    #[serde(default)]
6027    pub clusters: Vec<String>,
6028
6029    /// Optional hint to the placement engine: `"data-locality"`,
6030    /// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
6031    #[serde(default, skip_serializing_if = "Option::is_none")]
6032    pub affinity: Option<String>,
6033
6034    /// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
6035    #[serde(default, skip_serializing_if = "Option::is_none")]
6036    pub shard_key: Option<String>,
6037}
6038
6039impl Placement {
6040    /// Substrate-canonical per-`:placement` Akka-cluster-sharding
6041    /// `:shard-key` extractor-expression scalar accessor every consumer
6042    /// of the Aplicacao's hash-keyed distribution routing keys off —
6043    /// returns the author-declared `:placement :shard-key` byte-string
6044    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
6045    /// own `Option<String>` storage; `None` when the slot is absent
6046    /// (the canonical shape under `:estrategia Replicated` /
6047    /// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
6048    /// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
6049    /// partition — `validate` refuses any `Placement` past this call
6050    /// that lands `Some` on a non-`Sharded` strategy or `None` on
6051    /// `Sharded`).
6052    ///
6053    /// The `:placement :shard-key` slot carries the Akka-style
6054    /// cluster-sharding entity-id extractor expression
6055    /// (MESH-COMPOSITION §II.4) — validated by
6056    /// [`validate_placement_shard_key`] to be a non-empty printable-
6057    /// ASCII single-token reference (`tenantId`, `$tenantId`,
6058    /// `metadata.tenantId`, `${tenant}` — the canonical shapes the
6059    /// future M4 Akka-style cluster-sharding reconciler hashes without
6060    /// re-validating at the runtime layer), and every downstream
6061    /// consumer that reads the key keys off this scalar (the
6062    /// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
6063    /// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
6064    /// declared-but-inert refusal diagnostic, the caixa-mesh
6065    /// per-Aplicacao `placement.shardKey` emit path the substrate
6066    /// operator's per-entity hash-routing reader consumes, the future
6067    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6068    /// per-shard-key resolver).
6069    ///
6070    /// Prior to this lift the `.shard_key` field was accessed inline at
6071    /// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
6072    /// `Sharded` arm's `match &self.placement.shard_key { None => …,
6073    /// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
6074    /// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
6075    /// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
6076    /// — two open-coded field-accesses that expressed no compile-time
6077    /// link back to the typed slot. A future extension of the
6078    /// `:placement :shard-key` axis to a richer author surface — a
6079    /// per-cluster override the operator pins through a future
6080    /// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
6081    /// §II.4 roadmap acknowledges, a per-tenant extractor-expression
6082    /// alias table the M4 CR materializer resolves per-CR, a
6083    /// per-Aplicacao dynamic `:shard-key` derivation the future
6084    /// adaptive placement engine computes from `:affinity` weights —
6085    /// would have had to be threaded through both open-coded copies in
6086    /// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
6087    /// arm refusal would silently disagree on which extractor
6088    /// expression a given Placement resolves to. Lifting the resolution
6089    /// rule to a typed method on the substrate primitive means every
6090    /// downstream consumer of the Aplicacao's per-`:placement`
6091    /// hash-key surface reaches for exactly one typed dispatch — the
6092    /// resolver's accept-set migrates as a unit on any future axis
6093    /// addition.
6094    ///
6095    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
6096    /// [`WitContract::destination`] / [`WitContract::world_ref`]
6097    /// (7f0fd43, 0804823) scalar accessors, per-`:membros`
6098    /// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
6099    /// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
6100    /// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
6101    /// typed dispatch on the substrate primitive, thin projections at
6102    /// each consumer" discipline extended onto the per-`:placement`
6103    /// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
6104    /// First `Option<&str>`-return accessor on the M3 mesh-slot family
6105    /// — opens the "optional per-slot scalar" projection pattern the
6106    /// sibling per-`:placement` `:affinity`, per-`:politicas`
6107    /// `:rate-limit` future lifts fold on. Named `shard_key()` to
6108    /// match the storage field's name; the accessor's identity name
6109    /// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
6110    /// slot's docstring already carries.
6111    #[must_use]
6112    pub const fn shard_key(&self) -> Option<&str> {
6113        match &self.shard_key {
6114            Some(s) => Some(s.as_str()),
6115            None => None,
6116        }
6117    }
6118
6119    /// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
6120    /// compression-hint scalar accessor every weighting-consumer of the
6121    /// Aplicacao's per-hint routing surface keys off — returns the
6122    /// author-declared `:placement :affinity` byte-string verbatim as
6123    /// an `Option<&str>`, borrowed from the typed slot's own
6124    /// `Option<String>` storage; `None` when the slot is absent (the
6125    /// canonical shape of an Aplicacao that leaves the compression
6126    /// weighting up to the placement engine's cluster-default arm — no
6127    /// author-authored `data-locality` / `low-latency` / etc. hint
6128    /// biases the routing).
6129    ///
6130    /// The `:placement :affinity` slot carries the M3 Adaptive-
6131    /// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
6132    /// by [`validate_placement_affinity`] to be a DNS-1123 label
6133    /// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
6134    /// K8s-conformant label-selector shape every apiserver-side pod-
6135    /// affinity / node-affinity materializer already gates on
6136    /// admission), and every downstream consumer that reads the hint
6137    /// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
6138    /// per-hint value-shape gate, the caixa-mesh per-Aplicacao
6139    /// `placement.affinity` overlay emit path the substrate operator's
6140    /// per-hint weighting-consumer reads, the future M4
6141    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
6142    /// pod-affinity / node-affinity selector resolver).
6143    ///
6144    /// Prior to this lift the `.affinity` field was accessed inline at
6145    /// the sole caixa-core site — the
6146    /// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
6147    /// `if let Some(a) = &self.placement.affinity { …
6148    /// validate_placement_affinity(a)? … }` cascade — one open-coded
6149    /// field-access that expressed no compile-time link back to the
6150    /// typed slot. A future extension of the `:placement :affinity`
6151    /// axis to a richer author surface — a per-cluster override the
6152    /// operator pins through a future `:placement :affinity-overrides`
6153    /// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
6154    /// tenant hint alias table the M4 CR materializer resolves per-CR,
6155    /// a per-Aplicacao dynamic `:affinity` derivation the future
6156    /// adaptive placement engine computes from `:clusters` topology —
6157    /// would have had to be threaded through the open-coded copy in
6158    /// lockstep with any future caixa-mesh / caixa-flux / M4 CR
6159    /// materializer reader that landed on the axis, or the per-hint
6160    /// value-shape gate and its downstream weighting consumers would
6161    /// silently disagree on which hint a given Placement resolves to.
6162    /// Lifting the resolution rule to a typed method on the substrate
6163    /// primitive means every downstream consumer of the Aplicacao's
6164    /// per-`:placement` compression-hint surface reaches for exactly
6165    /// one typed dispatch — the resolver's accept-set migrates as a
6166    /// unit on any future axis addition.
6167    ///
6168    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
6169    /// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
6170    /// optional-scalar axis — same "one typed dispatch on the substrate
6171    /// primitive, thin projections at each consumer" discipline extended
6172    /// onto the per-`:placement` M3-Adaptive-compression-hint
6173    /// `Option<String>` optional-scalar axis. Second `Option<&str>`-
6174    /// return accessor on the M3 mesh-slot family; closes the last
6175    /// un-lifted per-`:placement` `Option<String>` axis. Named
6176    /// `affinity()` to match the storage field's name; the accessor's
6177    /// identity name maps onto the canonical MESH-COMPOSITION §II.4
6178    /// vocabulary the slot's docstring already carries.
6179    #[must_use]
6180    pub const fn affinity(&self) -> Option<&str> {
6181        match &self.affinity {
6182            Some(s) => Some(s.as_str()),
6183            None => None,
6184        }
6185    }
6186
6187    /// Substrate-canonical per-`:placement` `:estrategia` distribution-
6188    /// strategy scalar accessor every consumer that dispatches on the
6189    /// Aplicacao's per-cluster distribution shape keys off — returns the
6190    /// author-declared `:placement :estrategia` variant verbatim as a
6191    /// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
6192    /// `PlacementStrategy` storage.
6193    ///
6194    /// The `:placement :estrategia` slot carries the closed-set
6195    /// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
6196    /// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
6197    /// `Replicated` — active-active across every named cluster; `Sharded`
6198    /// — Akka-style hash-keyed entity distribution across the cluster pool
6199    /// per §II.4) that every downstream consumer of the Aplicacao's
6200    /// per-cluster fan-out shape keys off. Validated by
6201    /// [`AplicacaoSpec::validate_placement`] to be paired coherently with
6202    /// the sibling `:shard-key` axis (`shard_key.is_some() ==
6203    /// matches!(estrategia, Sharded)` — the cross-slot partition the
6204    /// [`Placement::shard_key`] accessor's docstring pins), and every
6205    /// downstream consumer that reads the strategy keys off this scalar
6206    /// (the [`AplicacaoSpec::validate_placement`]
6207    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
6208    /// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
6209    /// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
6210    /// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
6211    /// declared-but-inert refusal's
6212    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
6213    /// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
6214    /// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
6215    /// emit path the substrate operator's per-strategy fan-out reader
6216    /// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
6217    /// materializer's per-strategy admission-webhook resolver).
6218    ///
6219    /// Prior to this lift the `.estrategia` field was accessed inline at
6220    /// four sites — the [`AplicacaoSpec::validate_placement`]
6221    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
6222    /// `estrategia: self.placement.estrategia`, the same method's
6223    /// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
6224    /// partition dispatch, the non-`Sharded`-arm
6225    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
6226    /// `estrategia: self.placement.estrategia`, and the `feira app graph`
6227    /// per-Aplicacao strategy print line at
6228    /// `println!("… {} …", spec.placement.estrategia, …)`
6229    /// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
6230    /// expressed no compile-time link back to the typed slot. A future
6231    /// extension of the `:placement :estrategia` axis to a richer author
6232    /// surface (a per-cluster override the operator pins through a future
6233    /// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
6234    /// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
6235    /// materializer resolves per-CR, a per-Aplicacao dynamic strategy
6236    /// derivation the future adaptive placement engine computes from
6237    /// `:affinity` + `:clusters` topology) would have had to be threaded
6238    /// through every open-coded copy in lockstep — one consumer reading
6239    /// the raw variant while a peer read the operator-resolved variant
6240    /// would silently split the `PlacementWithoutClusters` /
6241    /// `ShardKeyOnNonSharded` diagnostic quotes from the actual
6242    /// partition-dispatch input, a two-consumer split at the validator
6243    /// far from the source `caixa.lisp` with no field naming the
6244    /// strategy-drift root cause. Lifting the resolution rule to a typed
6245    /// method on the substrate primitive means every downstream consumer
6246    /// of the Aplicacao's per-`:placement` distribution-strategy surface
6247    /// reaches for exactly one typed dispatch — the resolver's accept-set
6248    /// migrates as a unit on any future axis addition.
6249    ///
6250    /// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
6251    /// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
6252    /// same "one typed dispatch on the substrate primitive, thin
6253    /// projections at each consumer" discipline extended onto the
6254    /// per-`:placement` distribution-strategy `Copy`-composite-enum
6255    /// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
6256    /// family; first `Copy`-return accessor on the M3 mesh-slot
6257    /// `Placement` type — companion to the sibling per-`:placement`
6258    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
6259    /// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
6260    /// optional-scalar axes, closing the last unlifted per-`:placement`
6261    /// scalar-value axis (the closed-set `PlacementStrategy`
6262    /// distribution-strategy discriminator) so every downstream
6263    /// per-`:placement` reader now routes through a typed dispatch on
6264    /// the substrate primitive. Named `estrategia()` to match the storage
6265    /// field's name; the accessor's identity name maps onto the
6266    /// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
6267    /// already carries. Declared `pub const fn` (matching the peer M3
6268    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
6269    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
6270    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
6271    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
6272    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
6273    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
6274    /// [`RateLimit`] — every one a `pub const fn`) so every future
6275    /// substrate-side `const`-context consumer of the resolved
6276    /// distribution-strategy variant (a `const _: () = assert!(…)`
6277    /// module-scope invariant pin on a per-fixture typed [`Placement`],
6278    /// a future M4 admission-webhook `const fn` resolver over a typed
6279    /// [`Placement`], any `const fn` composer that fans on the strategy
6280    /// at compile time) reaches through the same typed dispatch on the
6281    /// substrate primitive at const-eval time as at runtime. Pinned by
6282    /// [`placement_estrategia_accessor_is_const_fn`] which witnesses the
6283    /// const-eval posture at module scope via `const _:() = …` items so
6284    /// any future accidental downgrade to non-`const` trips at caixa-core
6285    /// build time.
6286    #[must_use]
6287    pub const fn estrategia(&self) -> PlacementStrategy {
6288        self.estrategia
6289    }
6290
6291    /// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
6292    /// per-cluster distribution-target slice accessor every consumer that
6293    /// walks the Aplicacao's declared cluster-pool keys off — returns the
6294    /// author-declared `:placement :clusters` `Vec<String>` verbatim as a
6295    /// `&[String]` slice-view, borrowed from the typed slot's own
6296    /// `Vec<String>` storage (a zero-copy slice-view over the same
6297    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
6298    /// through). Non-optional: the empty slice is the load-bearing
6299    /// pre-validation sentinel every downstream consumer of the paired
6300    /// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
6301    /// off — every strategy in the closed
6302    /// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
6303    /// requires a non-empty list (`SingleNode` / `Replicated` use the
6304    /// list as hosting / takeover candidates per Erlang/OTP distributed-
6305    /// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
6306    /// shard pool per Akka cluster-sharding convention, §II.4), so the
6307    /// `.is_empty()` probe is the shared pre-condition every
6308    /// [`AplicacaoSpec::validate_placement`] arm heads on.
6309    ///
6310    /// The `:placement :clusters` slot carries the K8s-conformant DNS-
6311    /// 1123-label per-cluster distribution-target list — the same
6312    /// set-not-multiset shape the sibling `:membros :caixa` /
6313    /// `:children :caixa` axes carry (`validate_placement`'s per-entry
6314    /// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
6315    /// pins the shape). Every downstream consumer that fans on the list
6316    /// keys off this slice (the [`AplicacaoSpec::validate_placement`]
6317    /// pre-flight `.is_empty()` probe that trips
6318    /// [`AplicacaoError::PlacementWithoutClusters`], the same method's
6319    /// per-cluster value-shape + duplicate-detection fan-out loop, the
6320    /// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
6321    /// that materializes the list verbatim onto every
6322    /// programs.yaml entry the substrate operator's per-cluster
6323    /// `placement.clusters | contains .Values.cluster` filter reads,
6324    /// the `feira app graph` per-Aplicacao cluster print line, the
6325    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6326    /// per-cluster admission-webhook fan-out, the future M5 adaptive-
6327    /// placement engine's cluster-topology reader).
6328    ///
6329    /// Prior to this lift the `.clusters` `Vec<String>` was accessed
6330    /// inline at three production sites — the
6331    /// [`AplicacaoSpec::validate_placement`] pre-flight
6332    /// `self.placement.clusters.is_empty()` refusal probe, the same
6333    /// method's per-cluster validate loop's
6334    /// `for c in &self.placement.clusters` traversal head, and the
6335    /// `feira app graph` per-Aplicacao print line's
6336    /// `spec.placement.clusters` `{:?}` formatter argument
6337    /// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
6338    /// that expressed no compile-time link back to the typed slot. A
6339    /// future extension of the `:placement :clusters` axis to a richer
6340    /// author surface (a per-tenant cluster-pool overlay the operator
6341    /// pins through a future `:placement :clusters-overrides` slot the
6342    /// MESH-COMPOSITION §V cross-cluster-federation roadmap
6343    /// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
6344    /// the future M5 adaptive-placement engine computes from
6345    /// `:affinity` weights + live cluster-topology probes, a promotion
6346    /// of the plain `Vec<String>` to a richer `{static, dynamic}`
6347    /// partition once the substrate operator's cluster-membership
6348    /// reconciler comes into typed scope) would have had to be threaded
6349    /// through all three open-coded copies in lockstep or one consumer
6350    /// would silently disagree with the peers on which cluster-pool a
6351    /// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
6352    /// reading the raw slot while the peer per-cluster validate loop
6353    /// read an operator-resolved slot would silently split the paired
6354    /// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
6355    /// `PlacementClusterDuplicate` refusal cascade's actual traversal
6356    /// input from the pre-flight input, a three-consumer split at the
6357    /// validator and formatter far from the source `caixa.lisp` with
6358    /// no field naming the cluster-pool-drift root cause. Lifting the
6359    /// resolution rule to a typed method on the substrate primitive
6360    /// means every downstream consumer of the Aplicacao's
6361    /// per-`:placement` cluster-pool surface reaches for exactly one
6362    /// typed dispatch — the resolver's accept-set migrates as a unit
6363    /// on any future axis addition.
6364    ///
6365    /// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
6366    /// slot — sibling to the seed M2
6367    /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
6368    /// slice-return accessor on the peer per-`:supervisor` static-
6369    /// child-list `Vec`-carry axis, extended onto the first M3 mesh-
6370    /// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
6371    /// primitive, thin projections at each consumer" discipline. The
6372    /// three peer `Vec`-carry axes still unlifted at the time of this
6373    /// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
6374    /// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
6375    /// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
6376    /// [`crate::UpgradeFromEntry::instructions`]
6377    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
6378    /// — inherit this accessor's discipline as future compounding runs
6379    /// migrate their consumers onto the shared slice-return shape.
6380    /// Fourth (and final) accessor on the M3 mesh-slot `Placement`
6381    /// type, sibling to the two `Option<&str>`-return
6382    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
6383    /// (74ec2d3) accessors and the `Copy`-return
6384    /// [`Placement::estrategia`] (921fe1b) accessor — closes the last
6385    /// unlifted per-`:placement` field axis (the `Vec<String>`
6386    /// distribution-target-list carrier) so every downstream
6387    /// per-`:placement` reader now routes through a typed dispatch on
6388    /// the substrate primitive. Named `clusters()` to match the storage
6389    /// field's name verbatim and the tatara-lisp author-surface term
6390    /// (`:clusters`) the field's own docstring already carries; the
6391    /// accessor's identity maps onto the canonical MESH-COMPOSITION
6392    /// §II.1 / §II.4 vocabulary the slot's docstring already reaches
6393    /// for. Returns `&[String]` (not `&Vec<String>`) because every
6394    /// downstream consumer of the cluster list treats it as a read-only
6395    /// sequence — the slice-view is the narrowest borrow that supports
6396    /// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
6397    /// `.len()`) without leaking the backing `Vec`'s
6398    /// grow/push/reserve surface that no consumer of the typed view
6399    /// reaches for (the storage-side `Vec` remains reachable through
6400    /// the `pub clusters` field for the mutation-carrying serde
6401    /// round-trip and per-test fixture-mutation paths).
6402    #[must_use]
6403    pub const fn clusters(&self) -> &[String] {
6404        self.clusters.as_slice()
6405    }
6406}
6407
6408impl Default for Placement {
6409    fn default() -> Self {
6410        Self {
6411            // Route the struct-literal `estrategia` default arm through
6412            // the substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`]
6413            // typed `pub const` rather than the transitively-derived
6414            // [`PlacementStrategy::default`] route — one source of truth
6415            // for the M3-mesh-canonical [`PlacementStrategy::Replicated`]
6416            // active-active-across-every-named-cluster arm
6417            // (MESH-COMPOSITION §II.2) that both this struct-literal
6418            // altitude and the sibling [`Default for PlacementStrategy`]
6419            // impl already key off through the same substrate primitive.
6420            // Pinned by
6421            // `placement_default_estrategia_routes_through_lifted_default`.
6422            estrategia: PLACEMENT_ESTRATEGIA_DEFAULT,
6423            clusters: Vec::new(),
6424            affinity: None,
6425            shard_key: None,
6426        }
6427    }
6428}
6429
6430// ── external entry point ─────────────────────────────────────────────
6431
6432/// External entry point — what an outside caller sees. Renders to a
6433/// Gateway / Ingress + a route to the named member Servico.
6434#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
6435#[serde(rename_all = "camelCase")]
6436pub struct Entrada {
6437    /// Public hostname (e.g. `"checkout.quero.cloud"`).
6438    pub host: String,
6439
6440    /// Member Servico the gateway routes to. Must be in `:membros`.
6441    pub para: String,
6442
6443    /// Optional path filter — if set, only matching paths route to
6444    /// this Aplicacao (the rest fall through to other route rules).
6445    #[serde(default)]
6446    pub paths: Vec<String>,
6447
6448    /// Default port on the destination Servico (the trigger.service.port).
6449    #[serde(default = "default_port")]
6450    pub port: u16,
6451}
6452
6453impl Entrada {
6454    /// Substrate-canonical per-`:entrada` URL-path fallback resolver
6455    /// every HTTPRoute-aware renderer keys off — returns the author-
6456    /// declared `:entrada :paths` list verbatim when non-empty, and the
6457    /// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
6458    /// all fallback otherwise (so an Aplicacao author who declares an
6459    /// external `:entrada` block but no per-path rule surface still
6460    /// gets a route whose sole `HTTPPathMatch` matches every incoming
6461    /// request under the paired
6462    /// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
6463    ///
6464    /// Prior to this lift the "if `:entrada :paths` is empty use the
6465    /// substrate catch-all; else return each declared path verbatim"
6466    /// cascade lived inline at
6467    /// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
6468    /// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
6469    /// per-Aplicacao HTTPRoute per-rule path-list emit site the
6470    /// substrate ships today, with no typed method on the substrate
6471    /// primitive that named the rule. A future path-resolution axis
6472    /// addition — a per-cluster `:entrada :default-path` override the
6473    /// operator pins through a future `:placement`-scoped slot, an
6474    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
6475    /// admission-webhook floor that materializes the catch-all before
6476    /// the CR lands, a future per-`:entrada :paths` overlay from a
6477    /// per-cluster policy the future `feira app deploy` pipeline
6478    /// consumes — would have to be threaded through every renderer's
6479    /// inline copy of the cascade in lockstep or one consumer would
6480    /// silently disagree with the peers on which path list a given
6481    /// `:entrada` block resolves to. Lifting the rule to a typed
6482    /// method on the substrate primitive means every downstream
6483    /// HTTPRoute-aware consumer (the M4 CR materializer, the future
6484    /// per-cluster overlay resolver, every future per-Aplicacao
6485    /// snapshot renderer) reaches for exactly one typed dispatch —
6486    /// the resolver's accept-set moves as a unit on any future axis
6487    /// addition.
6488    ///
6489    /// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
6490    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
6491    /// per-`:entrada` scalar-value axes — extends the "one typed
6492    /// dispatch on the substrate primitive, thin projections at each
6493    /// consumer" discipline onto the per-`:entrada` path-list
6494    /// resolution axis every HTTPRoute-aware renderer consumes. Same
6495    /// shape as the [`MeshPolicy::is_empty`] typed predicate on the
6496    /// sibling `:politicas` primitive — one typed method on the
6497    /// substrate primitive that names the cascade every renderer
6498    /// otherwise re-inlines.
6499    #[must_use]
6500    pub fn resolved_paths(&self) -> Vec<&str> {
6501        // Route the internal cascade-head + per-entry projection reads
6502        // through the lifted [`Self::paths`] slice accessor rather than
6503        // the raw `self.paths` field access — the substrate-primitive
6504        // per-`:entrada` path-list resolver's two internal reads now
6505        // key off the canonical raw-slot surface every downstream
6506        // per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
6507        // per-entry value-shape gate, `feira app graph`'s per-Aplicacao
6508        // entrada summary line's `{:?}` Debug print) routes through, so
6509        // any future rebrand on the typed slot's raw-slot reader lands
6510        // at exactly one place. Same two-consumer coherence discipline
6511        // the sibling `Placement::clusters` (a6e18d7) accessor pins on
6512        // the peer M3 mesh-slot `Vec<String>`-carry axis.
6513        if self.paths().is_empty() {
6514            vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
6515        } else {
6516            self.paths().iter().map(String::as_str).collect()
6517        }
6518    }
6519
6520    /// Substrate-canonical per-`:entrada` DNS-hostname singular
6521    /// accessor every Gateway-API `Listener.hostname` reader keys off
6522    /// — returns the author-declared `:entrada :host` byte-string
6523    /// verbatim as a `&str`, borrowed from the typed slot's own
6524    /// [`String`] storage.
6525    ///
6526    /// Named the "singular" half of the DNS-hostname resolver pair on
6527    /// the substrate primitive: the parent-Gateway per-listener
6528    /// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
6529    /// (`Listener.hostname: Option<PreciseHostname>` — at most one
6530    /// hostname per listener), and this accessor is the typed dispatch
6531    /// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
6532    /// reaches for. Its plural sibling [`Entrada::hostnames`] carries
6533    /// the per-HTTPRoute `spec.hostnames[]` list axis the same
6534    /// per-Aplicacao ingress-hostname surface projects onto.
6535    ///
6536    /// Prior to this lift the `entrada.host.clone()` byte-string was
6537    /// accessed inline at two `caixa-mesh` sites — the parent-Gateway
6538    /// per-listener singular `hostname:` axis
6539    /// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
6540    /// per-HTTPRoute plural `spec.hostnames[]` axis
6541    /// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
6542    /// consumers read the same `entrada.host` field but the two-site
6543    /// duplication expressed no compile-time contract that the singular
6544    /// Gateway-listener filter and the plural `HTTPRoute` filter list
6545    /// stay in lockstep on future extensions of the `:entrada` slot to
6546    /// a multi-hostname author surface (an `:entrada :alt-hosts` list
6547    /// overlay, a per-cluster SNI fan-out the operator pins through a
6548    /// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
6549    /// Aplicacao` CR materializer's per-listener virtual-host filter
6550    /// admission-webhook overlay). Any such extension would have to be
6551    /// threaded through every renderer's inline copy of the resolution
6552    /// in lockstep or the Gateway listener's `hostname:` filter would
6553    /// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
6554    /// — a Gateway-API-conformance divergence whose apply-time symptom
6555    /// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
6556    /// `NoMatchingParent` — the API server rejects the route because
6557    /// its `hostnames[]` filter doesn't intersect the parent listener's
6558    /// `hostname` filter) is far from the source `caixa.lisp` and never
6559    /// surfaces in the emitted YAML. Lifting the singular and plural
6560    /// resolvers to typed methods on the substrate primitive means
6561    /// every consumer of the Aplicacao's ingress-hostname surface
6562    /// reaches for exactly one typed dispatch, and the pair-invariant
6563    /// `hostnames() == vec![hostname()]` pinned by the sibling
6564    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
6565    /// keeps the two axes in lockstep by construction.
6566    ///
6567    /// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
6568    /// (1449891) path-list resolver on the per-HTTPRoute per-rule
6569    /// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
6570    /// the substrate primitive, thin projections at each consumer"
6571    /// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
6572    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
6573    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
6574    /// [`Entrada::resolved_paths`] lifts apply on the sibling per-
6575    /// `:entrada` scalar-value + list-value axes.
6576    #[must_use]
6577    pub const fn hostname(&self) -> &str {
6578        self.host.as_str()
6579    }
6580
6581    /// Substrate-canonical per-`:entrada` DNS-hostname plural
6582    /// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
6583    /// keys off — returns the singleton `[hostname()]` list under
6584    /// today's single-hostname-per-Aplicacao author surface, and the
6585    /// authoritative multi-hostname list under a future
6586    /// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
6587    ///
6588    /// Plural half of the DNS-hostname resolver pair — see the
6589    /// companion [`Entrada::hostname`] docstring for the two-consumer
6590    /// lift + pair-invariant discipline (`hostnames() ==
6591    /// vec![hostname()]`, pinned load-bearing by the sibling
6592    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
6593    /// test).
6594    ///
6595    /// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
6596    /// per-`:entrada` plural-list resolver on the per-HTTPRoute
6597    /// per-rule path-list axis — same `Vec<&str>` shape, same
6598    /// substrate-primitive-owns-the-resolver discipline extended to
6599    /// the per-HTTPRoute virtual-host filter-list axis.
6600    #[must_use]
6601    pub fn hostnames(&self) -> Vec<&str> {
6602        vec![self.hostname()]
6603    }
6604
6605    /// Substrate-canonical per-`:entrada` destination-Servico scalar
6606    /// accessor every Gateway-API `HTTPRoute` reader keys off — returns
6607    /// the author-declared `:entrada :para` byte-string verbatim as a
6608    /// `&str`, borrowed from the typed slot's own [`String`] storage.
6609    ///
6610    /// The `:entrada :para` slot names the single member Servico the
6611    /// external Gateway routes to (validated by
6612    /// [`AplicacaoSpec::validate`] to be a
6613    /// [`Membro::caixa`] the Aplicacao declares — a stray
6614    /// `:para` that doesn't name a member is
6615    /// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
6616    /// backend-attachment miss at cluster-apply time). Under today's
6617    /// single-destination author surface `:entrada :para` is the ingress
6618    /// apex Servico's canonical identity; under a hypothetical
6619    /// future multi-backend author surface (a `:entrada
6620    /// :split :backends` weighted-fan-out overlay for canary /
6621    /// blue-green traffic-split rollouts, per-path override for
6622    /// path-based per-Servico routing beyond the single-apex model,
6623    /// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6624    /// per-CR admission-webhook that promotes the scalar to a
6625    /// weighted list) this accessor is the substrate primitive's typed
6626    /// dispatch every downstream `HTTPRoute`-aware consumer routes
6627    /// through, so the resolution shape migrates as a unit on one
6628    /// caixa-core edit rather than a coordinated rewrite across every
6629    /// renderer's inline field-access.
6630    ///
6631    /// Prior to this lift the `entrada.para` byte-string was accessed
6632    /// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
6633    /// `metadata.name` composer's per-destination discriminator arg
6634    /// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
6635    /// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
6636    /// per-HTTPRoute per-rule `backendRefs[0].name` axis
6637    /// (`entrada.para.clone()`,
6638    /// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
6639    /// consumers read the same `entrada.para` field but the two-site
6640    /// duplication expressed no compile-time contract that the HTTPRoute
6641    /// name-discriminator and the per-rule backend name stay in
6642    /// lockstep on future extensions of the `:entrada` slot to a
6643    /// multi-destination author surface. Any such extension would have
6644    /// to be threaded through every renderer's inline copy of the
6645    /// destination projection in lockstep or the HTTPRoute
6646    /// `metadata.name` would silently reference a different destination
6647    /// than its own `backendRefs[]` — an operator-side
6648    /// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
6649    /// grep-by-name lookup would land on a route whose `backendRefs[]`
6650    /// silently point at a peer Servico, dropping every external
6651    /// `:entrada` flow at the gateway with the destination-drift root
6652    /// cause invisible in the emitted YAML.
6653    ///
6654    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
6655    /// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
6656    /// the per-listener singular / per-HTTPRoute plural filter axes and
6657    /// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
6658    /// resolver on the per-HTTPRoute per-rule matches axis. Same "one
6659    /// typed dispatch on the substrate primitive, thin projections at
6660    /// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
6661    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
6662    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
6663    /// [`Entrada::resolved_paths`] (1449891) lifts apply on the
6664    /// sibling per-`:entrada` scalar-value + list-value axes — this
6665    /// accessor closes the last unlifted per-`:entrada` scalar axis
6666    /// (the destination-Servico byte-string) so every downstream
6667    /// per-`:entrada` reader now routes through a typed dispatch on
6668    /// the substrate primitive.
6669    #[must_use]
6670    pub const fn destination(&self) -> &str {
6671        self.para.as_str()
6672    }
6673
6674    /// Substrate-canonical per-`:entrada` L4-port scalar accessor every
6675    /// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
6676    /// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
6677    /// reader keys off — returns the author-declared `:entrada :port`
6678    /// value verbatim as a `u16`, `Copy`-projected from the typed slot's
6679    /// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
6680    /// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
6681    /// [`AplicacaoError::EntradaPortZero`], not a silent
6682    /// admission-webhook rejection at cluster-apply time).
6683    ///
6684    /// The `:entrada :port` slot carries the destination Servico's
6685    /// canonical in-cluster L4 listener port (`trigger.service.port` on
6686    /// the `pleme-computeunit` library chart), and every downstream
6687    /// consumer that reads the port keys off this scalar (the
6688    /// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
6689    /// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
6690    /// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
6691    /// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
6692    /// CR materializer's per-Aplicacao gateway port resolver).
6693    ///
6694    /// Prior to this lift the `.port` field was accessed inline at two
6695    /// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
6696    /// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
6697    /// the [`AplicacaoSpec::port_for_destination`] resolver's
6698    /// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
6699    /// open-coded field-accesses that expressed no compile-time link
6700    /// back to the typed slot. A future extension of the `:entrada :port`
6701    /// axis to a richer author surface — a per-cluster override the
6702    /// operator pins through a future `:placement :default-port` slot the
6703    /// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
6704    /// `Option<u16>`-shape migration once the substrate grows per-`:membros`
6705    /// heterogeneous listener ports, an M4
6706    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
6707    /// admission-webhook floor that promotes the scalar to a
6708    /// per-destination map — would have had to be threaded through both
6709    /// open-coded copies in lockstep or the structural-floor validator
6710    /// and the [`AplicacaoSpec::port_for_destination`] resolver would
6711    /// silently disagree on which port a given [`Entrada`] resolves to.
6712    /// Lifting the resolution rule to a typed method on the substrate
6713    /// primitive means every downstream consumer of the Aplicacao's
6714    /// per-`:entrada` L4-port surface reaches for exactly one typed
6715    /// dispatch — the resolver's accept-set migrates as a unit on any
6716    /// future axis addition.
6717    ///
6718    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
6719    /// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
6720    /// accessors on the per-`:entrada` scalar-value axis — same "one
6721    /// typed dispatch on the substrate primitive, thin projections at
6722    /// each consumer" discipline extended onto the per-`:entrada`
6723    /// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
6724    /// the M3 mesh-slot `Entrada` type — closes the last unlifted
6725    /// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
6726    /// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
6727    /// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
6728    /// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
6729    /// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
6730    /// storage field's name; the accessor's identity name maps onto the
6731    /// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
6732    /// already carries. Declared `pub const fn` (matching the peer M3
6733    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
6734    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
6735    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
6736    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
6737    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
6738    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
6739    /// [`RateLimit`], and the sibling per-`:placement`
6740    /// [`Placement::estrategia`] on the peer M3 mesh-slot `Copy`-composite-
6741    /// enum scalar axis — every one a `pub const fn`) so every future
6742    /// substrate-side `const`-context consumer of the resolved
6743    /// per-`:entrada` L4-port scalar (a `const _: () = assert!(…)`
6744    /// module-scope pin on a per-fixture typed [`Entrada`] anchoring
6745    /// `entrada.port() >= SERVICO_PORT_MIN` at compile time, a future M4
6746    /// admission-webhook `const fn` per-CR gateway-port floor over a
6747    /// typed [`Entrada`], any `const fn` composer that fans on the port
6748    /// at compile time) reaches through the same typed dispatch on the
6749    /// substrate primitive at const-eval time as at runtime. Pinned by
6750    /// [`entrada_port_accessor_is_const_fn`] which witnesses the
6751    /// const-eval posture at module scope via `const _:() = …` items so
6752    /// any future accidental downgrade to non-`const` trips at caixa-core
6753    /// build time.
6754    #[must_use]
6755    pub const fn port(&self) -> u16 {
6756        self.port
6757    }
6758
6759    /// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
6760    /// slice accessor every HTTPRoute-aware renderer keys off when it
6761    /// wants the raw author-declared path-list (not the fallback-
6762    /// applied projection [`Self::resolved_paths`] returns) — returns
6763    /// the author-declared `:entrada :paths` list verbatim as `&[String]`,
6764    /// borrowed from the typed slot's own [`Vec<String>`] storage.
6765    ///
6766    /// Named the "raw slot" half of the per-`:entrada` path-list resolver
6767    /// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
6768    /// (1449891) closes the fallback-applying arm every per-Aplicacao
6769    /// HTTPRoute per-rule `matches[].path` emitter routes through (empty
6770    /// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
6771    /// catch-all; non-empty slot → per-entry verbatim projection); this
6772    /// accessor closes the raw-slot arm every consumer that must see the
6773    /// author's declaration verbatim (the [`AplicacaoSpec::validate`]
6774    /// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
6775    /// not `Err(EntradaPathEmpty)`, so it cannot route through the
6776    /// fallback-applying sibling; the `feira app graph` per-Aplicacao
6777    /// external-gateway summary line's `{:?}` Debug print — which must
6778    /// name the author's declaration, not the substrate's fallback, so
6779    /// an author reading their graph output can grep their caixa.lisp
6780    /// for the exact list they authored) routes through.
6781    ///
6782    /// Prior to this lift the `.paths` field was accessed inline at four
6783    /// production sites: the two internal reads in [`Self::resolved_paths`]
6784    /// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
6785    /// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
6786    /// value-shape gate's `for p in &e.paths` traversal head, and the
6787    /// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
6788    /// Debug print — four open-coded field-accesses that expressed no
6789    /// compile-time link back to the typed slot. A future extension of
6790    /// the `:entrada :paths` axis to a richer author surface — a
6791    /// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
6792    /// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
6793    /// spec supports through `matches[].method`), a per-path per-header
6794    /// filter overlay (`matches[].headers[]`), a per-cluster override
6795    /// the operator pins through a future `:placement :path-overlay`
6796    /// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6797    /// per-CR admission-webhook that normalized the list at admission
6798    /// time — would have had to be threaded through every open-coded
6799    /// copy in lockstep or the validator's per-entry gate would silently
6800    /// disagree with the renderer's per-entry emit on which list a given
6801    /// `:entrada` block resolves to. Lifting the resolution to a typed
6802    /// method on the substrate primitive means every downstream consumer
6803    /// of the Aplicacao's per-`:entrada` path-list surface reaches for
6804    /// exactly one typed dispatch — the resolver's accept-set migrates
6805    /// as a unit on any future axis addition.
6806    ///
6807    /// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
6808    /// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
6809    /// carry axis — same "one typed dispatch on the substrate primitive,
6810    /// thin projections at each consumer" discipline extended onto the
6811    /// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
6812    /// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
6813    /// carrier) so every downstream per-`:entrada` reader now routes
6814    /// through a typed dispatch on the substrate primitive. Returns
6815    /// `&[String]` (not `&Vec<String>`) because every downstream consumer
6816    /// treats the list as a read-only sequence — the slice-view is the
6817    /// narrowest borrow that supports every present + roadmapped consumer
6818    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
6819    /// `Vec`'s grow/push/reserve surface that no consumer of the typed
6820    /// view reaches for (the storage-side `Vec` remains reachable through
6821    /// the `pub paths` field for the mutation-carrying serde round-trip
6822    /// and per-test fixture-mutation paths).
6823    #[must_use]
6824    pub const fn paths(&self) -> &[String] {
6825        self.paths.as_slice()
6826    }
6827}
6828
6829/// Canonical default L4 port every typed Servico exposes on its
6830/// in-cluster K8s Service (the `trigger.service.port` axis the
6831/// `pleme-computeunit` library chart emits, the `:entrada :port` author
6832/// surface defaults to when the author omits the slot, and the
6833/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
6834/// `:entrada` block matches the per-`:contratos` destination Servico).
6835/// The single source of truth all three typed-port consumers reach for:
6836///
6837///   - [`Entrada::port`]'s serde default (via the
6838///     [`default_port`] helper this constant feeds); the author surface
6839///     `(:entrada (:host … :para …))` without an explicit `:port` slot
6840///     reads back as a typed [`Entrada`] carrying this exact value;
6841///   - the
6842///     [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
6843///     emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
6844///     fallback, fired when the typed `:entrada` block doesn't name
6845///     the per-`:contratos` destination Servico — the typed
6846///     `:contratos` graph carries no per-destination port axis (the
6847///     destination port is the destination Servico's
6848///     `lareira-<nome>` chart's `trigger.service.port`, which the
6849///     Aplicacao-level renderer has no visibility into without a
6850///     resolver round-trip), so the renderer falls back to the
6851///     substrate's canonical Servico-port assumption — by
6852///     construction the same value the destination's own
6853///     `pleme-computeunit` chart emits, the same value the
6854///     destination's own typed `:entrada :port` slot defaults to;
6855///   - every future per-Servico renderer the absorption-roadmap
6856///     acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
6857///     CR materializer's per-edge port resolver, the future
6858///     per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
6859///     emitter's per-route bucket key, the future caixa-otel
6860///     collector-pipeline emitter's per-Servico scrape port).
6861///
6862/// Until this lift landed the value `8080` lived at two production-code
6863/// call-sites: the [`default_port`] helper at
6864/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
6865/// and the `.unwrap_or(8080)` literal at
6866/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
6867/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
6868/// resolver). A future Servico-port rebrand — the substrate moving the
6869/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
6870/// gateway grows direct `:80` listeners, to `8443` once the substrate
6871/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
6872/// override the operator pins through a future
6873/// `:placement :default-port` slot — without a coordinated edit on
6874/// both sides would silently emit Servicos listening on one port and
6875/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
6876/// The CNP's apply-time symptom (the policy is admitted but every L4
6877/// flow on the destination Servico's actual port silently drops because
6878/// it doesn't match the whitelisted port) is far from the rebrand
6879/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
6880/// in hubble traces, not in `kubectl describe`. Lifting the literal to
6881/// a shared constant closes the drift footgun structurally — both
6882/// consumers read from the same `u16`, so any rebrand reaches both
6883/// sites by construction.
6884///
6885/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
6886/// per-renderer canonical-K8s-axis constant — the namespace string
6887/// and the canonical Servico port both lived as duplicated literals
6888/// across caixa-core / caixa-mesh / caixa-flux before their respective
6889/// lifts. Same "the typed constant lives in one place" discipline the
6890/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
6891/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
6892/// shared-string axes.
6893///
6894/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
6895pub const DEFAULT_SERVICO_PORT: u16 = 8080;
6896
6897/// Structural floor for the typed `:entrada :port` axis — every
6898/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
6899/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
6900///
6901/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
6902/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
6903/// interprets as "let the kernel pick a free port at bind time", not a
6904/// well-defined destination the substrate's per-`:entrada` Gateway API
6905/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
6906/// carrying `port: 0` degenerates to a nominal-only routing target: the
6907/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
6908/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
6909/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
6910/// at build time rather than at `kubectl apply` time), and the
6911/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
6912/// (caixa-mesh/src/lib.rs:2657 through
6913/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
6914/// [`Entrada::port`] typed value — silently emits a policy whose
6915/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
6916/// actual listener, dropping every L4 flow at the eBPF data plane far
6917/// from the source caixa.lisp with no field naming the port-zero-drift
6918/// root cause.
6919///
6920/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
6921/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
6922/// on the top edge (unlike the peer capped-`u32` `:politicas` /
6923/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
6924/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
6925/// well below `u32::MAX` and therefore need explicit typed caps).
6926///
6927/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
6928/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
6929/// scalar every `(:entrada (:host … :para …))` slot without an explicit
6930/// `:port` inherits through the serde default hook; this constant names
6931/// the accept-set floor every declared port must satisfy. The pair is
6932/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
6933/// substrate's default must satisfy its own accept-set floor by
6934/// construction) — a future rebrand that accidentally moved
6935/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
6936/// negative-cast typo, a per-cluster override the operator pins through
6937/// a future `:placement :default-port` slot that lands out-of-range)
6938/// would silently invalidate the serde-default emission at every
6939/// author-side `(:entrada (:host … :para …))` slot — the compile-time
6940/// invariant pin
6941/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
6942/// closes the drift footgun at caixa-core build time.
6943///
6944/// Lifted as a typed `pub const` (rather than an inline `0` literal at
6945/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
6946/// has exactly one source of truth — the future M4
6947/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
6948/// gateway resolver, the future per-Servico
6949/// `computeunit.trigger.service.port` renderer's per-CR port-value
6950/// validator, and every downstream test-fixture navigator asserting
6951/// the accept-set floor all read from one place. Same shape every
6952/// other typed bracket-floor / bracket-ceiling in this crate carries
6953/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
6954/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
6955/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
6956/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
6957/// [`POLICY_RATE_LIMIT_MAX`]).
6958pub const SERVICO_PORT_MIN: u16 = 1;
6959
6960const fn default_port() -> u16 {
6961    DEFAULT_SERVICO_PORT
6962}
6963
6964// ── the typed view ───────────────────────────────────────────────────
6965
6966/// Typed composition view of the flat Aplicacao slots on
6967/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
6968/// validation + downstream renderer consumption.
6969#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
6970#[serde(rename_all = "camelCase")]
6971pub struct AplicacaoSpec {
6972    pub membros: Vec<Membro>,
6973    pub contratos: Vec<WitContract>,
6974    pub politicas: MeshPolicy,
6975    pub placement: Placement,
6976    pub entrada: Option<Entrada>,
6977}
6978
6979impl AplicacaoSpec {
6980    /// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
6981    /// per-Aplicacao member-list slice-return accessor every
6982    /// per-Aplicacao member-list reader keys off — returns the author-
6983    /// declared `:membros` list verbatim as a `&[Membro]` slice-view
6984    /// over the same backing buffer the raw `self.membros.as_slice()`
6985    /// field access borrows from.
6986    ///
6987    /// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
6988    /// member list — the load-bearing identity of the application graph
6989    /// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
6990    /// multiset). Every per-`:membros` entry pairs a `:caixa` member-
6991    /// caixa name (through the lifted [`Membro::nome`] (4a32abf)
6992    /// accessor) with a `:versao` semver-requirement string (through
6993    /// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
6994    /// and every downstream consumer that fans on the member-set keys
6995    /// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
6996    /// membership-lookup `HashSet<&str>` seed's collect input, the
6997    /// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
6998    /// [`AplicacaoError::NoMembros`] refusal probe, the same method's
6999    /// per-member DNS-1123 / semver-requirement / duplicate-detection
7000    /// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
7001    /// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
7002    /// programs.yaml per-`:membros` fan-out emitter's per-entry
7003    /// mapping-composition loop, the `feira app graph` per-Aplicacao
7004    /// member-count print line and per-member tree traversal,
7005    /// every future wasm-operator (M4) per-Aplicacao CR materializer's
7006    /// per-member `ComputeUnit` fan-out, the future M5 adaptive-
7007    /// placement engine's per-member weight-topology reader).
7008    ///
7009    /// Prior to this lift the `.membros` `Vec<Membro>` was accessed
7010    /// inline at six production sites — the [`AplicacaoSpec::validate`]
7011    /// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
7012    /// [`AplicacaoSpec::validate_membros`]'s pre-flight
7013    /// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
7014    /// probe, the same method's per-member `for m in &self.membros`
7015    /// validate-loop traversal head, the
7016    /// [`AplicacaoSpec::detect_sync_cycles`]'s
7017    /// `for m in &self.membros` adjacency-list seed, the
7018    /// [`caixa_mesh::programs_for_aplicacao`] emitter's
7019    /// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
7020    /// paired with the peer `for m in &spec.membros` per-entry fan-out
7021    /// loop, and the `feira app graph` per-Aplicacao print line's
7022    /// `spec.membros.len()` count formatter argument paired with the
7023    /// peer `for m in &spec.membros` per-member tree traversal — six
7024    /// open-coded field-accesses that expressed no compile-time link
7025    /// back to the typed slot. A future extension of the `:membros`
7026    /// axis to a richer author surface (a per-cluster member-set
7027    /// overlay the operator pins through a future
7028    /// `:membros-overrides` slot the MESH-COMPOSITION §V federation
7029    /// roadmap acknowledges, a per-tenant member-alias table the M4
7030    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
7031    /// CR at admission time, a per-Aplicacao dynamic member-set
7032    /// derivation the future adaptive-placement engine computes from
7033    /// weighted membership topology, a promotion of the plain
7034    /// `Vec<Membro>` to a richer `{static, dynamic}` partition once
7035    /// Orleans-style virtual-actor dynamic-membership comes into typed
7036    /// scope) would have had to be threaded through all six open-coded
7037    /// copies in lockstep or one consumer would silently disagree with
7038    /// the peers on which member-set a given Aplicacao resolves to —
7039    /// the `HashSet<&str>` name-set seed reading the raw slot while
7040    /// the peer `.is_empty()` refusal probe read an operator-resolved
7041    /// slot would silently split the `:contratos` membership-lookup
7042    /// input from the pre-flight-refusal input, a six-consumer split
7043    /// at the validator + programs.yaml emitter + graph printer far
7044    /// from the source `caixa.lisp` with no field naming the member-
7045    /// set-drift root cause. Lifting the resolution rule to a typed
7046    /// method on the substrate primitive means every downstream
7047    /// consumer of the Aplicacao's per-`:membros` member-list surface
7048    /// reaches for exactly one typed dispatch — the resolver's accept-
7049    /// set migrates as a unit on any future axis addition.
7050    ///
7051    /// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
7052    /// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
7053    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
7054    /// static-child-list `Vec`-carry axis, and to the M3
7055    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
7056    /// on the peer per-`:placement` distribution-target-list `Vec`-
7057    /// carry axis. Same "one typed dispatch on the substrate primitive,
7058    /// thin projections at each consumer" discipline. The two peer
7059    /// `Vec`-carry axes still unlifted at the time of this lift —
7060    /// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
7061    /// WIT-typed edge list) and
7062    /// [`crate::UpgradeFromEntry::instructions`]
7063    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
7064    /// — inherit this accessor's discipline as future compounding runs
7065    /// migrate their consumers onto the shared slice-return shape.
7066    /// First `&[T]`-return accessor on the top-level M3 mesh-slot
7067    /// `AplicacaoSpec` type itself, extending the discipline beyond
7068    /// the inner per-slot types ([`crate::Placement`],
7069    /// [`crate::SupervisorSpec`]) onto the outermost typed composition
7070    /// view every renderer consumes. Named `membros()` to match the
7071    /// storage field's name verbatim and the tatara-lisp author-
7072    /// surface term (`:membros`) the field's own docstring already
7073    /// carries; the accessor's identity maps onto the canonical
7074    /// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
7075    /// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
7076    /// every downstream consumer of the member list treats it as a
7077    /// read-only sequence — the slice-view is the narrowest borrow
7078    /// that supports every present + roadmapped consumer
7079    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
7080    /// backing `Vec`'s grow/push/reserve surface that no consumer of
7081    /// the typed view reaches for (the storage-side `Vec` remains
7082    /// reachable through the `pub membros` field for the mutation-
7083    /// carrying serde round-trip and per-test fixture-mutation paths).
7084    #[must_use]
7085    pub const fn membros(&self) -> &[Membro] {
7086        self.membros.as_slice()
7087    }
7088
7089    /// Substrate-canonical per-`:contratos` `Vec<WitContract>`
7090    /// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
7091    /// accessor every per-Aplicacao contract-list reader keys off —
7092    /// returns the author-declared `:contratos` list verbatim as a
7093    /// `&[WitContract]` slice-view over the same backing buffer the raw
7094    /// `self.contratos.as_slice()` field access borrows from.
7095    ///
7096    /// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
7097    /// WIT-typed edge list — the load-bearing set of directed edges
7098    /// on the application graph whose nodes are the `:membros` entries
7099    /// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
7100    /// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
7101    /// six-tuple is the edge identity every downstream duplicate gate
7102    /// keys off). Every per-`:contratos` entry pairs a `:de` source-
7103    /// Servico caller name + a `:para` destination-Servico callee name
7104    /// (through the lifted [`WitContract::source`] +
7105    /// [`WitContract::destination`] (7f0fd43) accessor pair on the
7106    /// caller/callee-Servico axis) with a `:wit` world-reference
7107    /// (through the lifted [`WitContract::world_ref`] (0804823)
7108    /// accessor) and the target-shape-appropriate payload-carrier
7109    /// scalar (through the lifted [`WitContract::endpoint`] (7020470),
7110    /// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
7111    /// (ed22b66) accessor on the per-target-shape payload-carrier
7112    /// axis). Every downstream consumer that fans on the edge-set
7113    /// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
7114    /// name-set / self-edge / target-shape / dedup fan-out loop, the
7115    /// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
7116    /// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
7117    /// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
7118    /// grouping loop, the `feira app graph` per-Aplicacao contract-
7119    /// count print line and per-contract tree traversal, every future
7120    /// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
7121    /// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
7122    /// mesh-policy overlay resolver's per-contract typed-edge weight
7123    /// reader).
7124    ///
7125    /// Prior to this lift the `.contratos` `Vec<WitContract>` was
7126    /// accessed inline at four production sites — the
7127    /// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
7128    /// per-edge validate-loop traversal head (which drives every
7129    /// per-edge name-set membership lookup, self-edge check,
7130    /// target-shape dispatch, and dedup `HashSet` insert), the
7131    /// [`AplicacaoSpec::detect_sync_cycles`]'s
7132    /// `for c in &self.contratos` adjacency-list seed head (which
7133    /// drives every per-edge sync-vs-pub-sub partition and per-edge
7134    /// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
7135    /// emitter's `for c in &spec.contratos` per-`(:de, :para)`
7136    /// `BTreeMap` grouping loop head (which drives every per-CNP
7137    /// fan-out emit), and the `feira app graph` per-Aplicacao print
7138    /// line's `spec.contratos.len()` count formatter argument paired
7139    /// with the peer `for c in &spec.contratos` per-contract tree
7140    /// traversal — four open-coded field-accesses that expressed no
7141    /// compile-time link back to the typed slot. A future extension
7142    /// of the `:contratos` axis to a richer author surface (a
7143    /// per-cluster contract overlay the operator pins through a
7144    /// future `:contratos-overrides` slot the MESH-COMPOSITION §V
7145    /// federation roadmap acknowledges, a per-tenant edge-policy
7146    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
7147    /// materializer resolves per-CR at admission time, a per-edge
7148    /// weight scalar the future adaptive-placement engine reads to
7149    /// bias sync-subgraph routing, a promotion of the plain
7150    /// `Vec<WitContract>` to a richer `{static, dynamic}` partition
7151    /// once virtual-actor-style dynamic-edge composition comes into
7152    /// typed scope) would have had to be threaded through all four
7153    /// open-coded copies in lockstep or one consumer would silently
7154    /// disagree with the peers on which edge-set a given Aplicacao
7155    /// resolves to — the validator's per-edge dedup `HashSet` seed
7156    /// reading the raw slot while the peer sync-cycle adjacency-list
7157    /// seed read an operator-resolved slot would silently split the
7158    /// build-time edge-set gate from the runtime deadlock-detection
7159    /// gate, a four-consumer split at the validator, the cycle
7160    /// detector, the CNP emitter, and the graph printer far from
7161    /// the source `caixa.lisp` with no field naming the edge-set-
7162    /// drift root cause. Lifting the resolution rule to a typed method on the
7163    /// substrate primitive means every downstream consumer of the
7164    /// Aplicacao's per-`:contratos` edge-list surface reaches for
7165    /// exactly one typed dispatch — the resolver's accept-set
7166    /// migrates as a unit on any future axis addition.
7167    ///
7168    /// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
7169    /// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
7170    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
7171    /// static-child-list `Vec`-carry axis, to the M3
7172    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
7173    /// on the peer per-`:placement` distribution-target-list `Vec`-
7174    /// carry axis, and to the immediately-adjacent sibling M3
7175    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
7176    /// the peer per-`:membros` node-list `Vec`-carry axis — the
7177    /// per-`:contratos` edge-list accessor is the natural pair of
7178    /// the per-`:membros` node-list accessor (graph edges over graph
7179    /// nodes; every graph-shaped consumer reads both). Same "one
7180    /// typed dispatch on the substrate primitive, thin projections
7181    /// at each consumer" discipline. The last remaining `Vec`-carry
7182    /// axis still unlifted at the time of this lift —
7183    /// [`crate::UpgradeFromEntry::instructions`]
7184    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction
7185    /// list) — inherits this accessor's discipline as future
7186    /// compounding runs migrate its consumers onto the shared slice-
7187    /// return shape. Second `&[T]`-return accessor on the top-level
7188    /// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
7189    /// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
7190    /// `:contratos` are the two `Vec` fields on the outer typed
7191    /// composition view — `:politicas`, `:placement`, `:entrada` are
7192    /// scalar/option-shaped and already route through their per-slot
7193    /// accessor families). Named `contratos()` to match the storage
7194    /// field's name verbatim and the tatara-lisp author-surface term
7195    /// (`:contratos`) the field's own docstring already carries; the
7196    /// accessor's identity maps onto the canonical MESH-COMPOSITION
7197    /// §III.1 vocabulary the slot's docstring already reaches for.
7198    /// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
7199    /// every downstream consumer of the contract list treats it as a
7200    /// read-only sequence — the slice-view is the narrowest borrow
7201    /// that supports every present + roadmapped consumer
7202    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
7203    /// backing `Vec`'s grow/push/reserve surface that no consumer of
7204    /// the typed view reaches for (the storage-side `Vec` remains
7205    /// reachable through the `pub contratos` field for the mutation-
7206    /// carrying serde round-trip and per-test fixture-mutation paths).
7207    #[must_use]
7208    pub const fn contratos(&self) -> &[WitContract] {
7209        self.contratos.as_slice()
7210    }
7211
7212    /// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
7213    /// per-Aplicacao mesh-policy composite-reference accessor every
7214    /// per-Aplicacao policy-block reader keys off — returns the author-
7215    /// declared `:politicas` composite verbatim as a `&MeshPolicy`
7216    /// reference over the same backing storage the raw `&self.politicas`
7217    /// field access borrows from.
7218    ///
7219    /// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
7220    /// mesh-policy composite — the load-bearing container of every
7221    /// mesh-level operational-policy axis every downstream mesh-artifact
7222    /// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
7223    /// mesh-policy overlay is the single typed surface a
7224    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
7225    /// from). Every per-`:politicas` axis threads through a lifted
7226    /// per-slot accessor on the [`MeshPolicy`] type: the
7227    /// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
7228    /// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
7229    /// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
7230    /// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
7231    /// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
7232    /// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
7233    /// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
7234    /// Envoy-local-rate-limit-mesh token-bucket-declaration composite
7235    /// accessor. Every downstream consumer that reaches for a policy
7236    /// axis first passes through this outer accessor onto the composite
7237    /// and then dispatches onto the per-axis accessor — the two-level
7238    /// dispatch means every per-`:politicas` reader now routes through
7239    /// a typed dispatch on the substrate primitive at both altitudes.
7240    ///
7241    /// Prior to this lift the `.politicas` `MeshPolicy` composite was
7242    /// accessed inline at four production sites — the
7243    /// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
7244    /// &self.politicas;` traversal seed (which drives every per-axis
7245    /// zero-floor + upper-cap + canonical-form bracket dispatch through
7246    /// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
7247    /// `p.rate_limit()` on the axis-level lifted accessors), the
7248    /// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
7249    /// emitter's `spec.politicas.mtls_required()` field-then-accessor
7250    /// chain (which drives every per-`(:de, :para)` CNP
7251    /// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
7252    /// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
7253    /// timeout + retry overlay emitter's paired
7254    /// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
7255    /// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
7256    /// deadline + budget overlay onto the emitted `HTTPRoute`) — four
7257    /// open-coded outer-field accesses that expressed no compile-time
7258    /// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
7259    /// future extension of the `:politicas` outer axis to a richer
7260    /// author surface (a per-cluster policy overlay the operator pins
7261    /// through a future `:politicas-overrides` slot the MESH-COMPOSITION
7262    /// §V federation roadmap acknowledges, a per-tenant policy-alias
7263    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
7264    /// resolves per-CR at admission time, a per-Aplicacao dynamic
7265    /// policy-composite derivation the future adaptive-placement engine
7266    /// computes from a per-cluster load-topology reader, a promotion of
7267    /// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
7268    /// partition once virtual-actor-style dynamic-mesh-policy
7269    /// composition comes into typed scope) would have had to be threaded
7270    /// through all four open-coded copies in lockstep or one consumer
7271    /// would silently disagree with the peers on which mesh-policy
7272    /// composite a given Aplicacao resolves to — the validator's
7273    /// per-axis bracket-dispatch seed reading the raw slot while the
7274    /// peer CNP mTLS-overlay emitter read an operator-resolved slot
7275    /// would silently split the build-time policy-shape gate from the
7276    /// runtime CNP-emission gate, a four-consumer split at the
7277    /// validator, the CNP emitter, and the `HTTPRoute` emitter far from
7278    /// the source `caixa.lisp` with no field naming the policy-drift
7279    /// root cause. Lifting the resolution rule to a typed method on the
7280    /// substrate primitive means every downstream consumer of the
7281    /// Aplicacao's per-`:politicas` mesh-policy composite surface
7282    /// reaches for exactly one typed dispatch — the resolver's accept-
7283    /// set migrates as a unit on any future axis addition.
7284    ///
7285    /// First `&Composite`-return accessor on the top-level M3 mesh-slot
7286    /// `AplicacaoSpec` type itself — sibling to the seed slice-return
7287    /// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
7288    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
7289    /// close the two `Vec`-carry axes on the outer typed composition
7290    /// view; the outer `:politicas` composite-reference axis is the
7291    /// natural pair to the paired outer `Vec`-carry accessors on the
7292    /// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
7293    /// emitter reads all four axes as one unit (graph nodes + graph
7294    /// edges + mesh policy + placement pool). Peer to the same
7295    /// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
7296    /// slot: every M2 `SupervisorSpec`-scoped composite reader
7297    /// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
7298    /// `restart_window`, `children`) already routes through the M2
7299    /// `SupervisorSpec` accessor family — this lift extends the same
7300    /// "one typed dispatch on the substrate primitive at the outer
7301    /// composition altitude" discipline to the M3 mesh-slot
7302    /// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
7303    /// remaining peer outer-composite axes still unlifted at the time
7304    /// of this lift — [`AplicacaoSpec::placement`] (`Placement`
7305    /// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
7306    /// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
7307    /// inherit this accessor's discipline as future compounding runs
7308    /// migrate their consumers onto the shared reference-return shape.
7309    /// Named `politicas()` to match the storage field's name verbatim
7310    /// and the tatara-lisp author-surface term (`:politicas`) the
7311    /// field's own docstring already carries; the accessor's identity
7312    /// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
7313    /// slot's docstring already reaches for. Returns `&MeshPolicy`
7314    /// (not the owning composite by copy or clone) because every
7315    /// downstream consumer of the mesh-policy composite treats it as a
7316    /// read-only per-axis dispatch source — the reference-view is the
7317    /// narrowest borrow that supports every present + roadmapped
7318    /// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
7319    /// emptiness probe) without cloning the composite through every
7320    /// consumer's fast path.
7321    #[must_use]
7322    pub const fn politicas(&self) -> &MeshPolicy {
7323        &self.politicas
7324    }
7325
7326    /// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
7327    /// per-Aplicacao distribution-composite composite-reference accessor
7328    /// every per-Aplicacao placement-block reader keys off — returns the
7329    /// author-declared `:placement` composite verbatim as a `&Placement`
7330    /// reference over the same backing storage the raw `&self.placement`
7331    /// field access borrows from.
7332    ///
7333    /// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
7334    /// distribution composite — the load-bearing container of every
7335    /// where-does-this-Aplicacao-run axis every downstream cluster-artifact
7336    /// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
7337    /// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
7338    /// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
7339    /// hosting-pool identity, §V for the `M3-Adaptive`-compression
7340    /// `:affinity` hint). Every per-`:placement` axis threads through a
7341    /// lifted per-slot accessor on the [`Placement`] type: the
7342    /// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
7343    /// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
7344    /// per-cluster distribution-target slice-return accessor, the
7345    /// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
7346    /// optional-scalar accessor, and the [`Placement::shard_key`]
7347    /// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
7348    /// downstream consumer that reaches for a placement axis first passes
7349    /// through this outer accessor onto the composite and then dispatches
7350    /// onto the per-axis accessor — the two-level dispatch means every
7351    /// per-`:placement` reader now routes through a typed dispatch on the
7352    /// substrate primitive at both altitudes.
7353    ///
7354    /// Prior to this lift the `.placement` `Placement` composite was
7355    /// accessed inline at three production sites — the
7356    /// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
7357    /// seed (six `self.placement.<axis>()` field-then-inner-accessor
7358    /// chains: the pre-flight `.clusters().is_empty()` refusal probe
7359    /// paired with the `.estrategia()` diagnostic-carry copy, the per-
7360    /// cluster `.clusters()` validate-loop traversal head, the per-
7361    /// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
7362    /// non-`Sharded` partition's `.estrategia()` match arm scrutinee
7363    /// paired with the shape-gate cascade's `.shard_key()` /
7364    /// `.estrategia()` diagnostic-carry pair), the
7365    /// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
7366    /// per-entry placement-block emitter's outer
7367    /// `serde_yaml::to_value(&spec.placement)` composite-serialization
7368    /// seed (which fans onto every per-cluster `programs[]` entry as a
7369    /// self-describing distribution overlay the aggregator filters by),
7370    /// and the `feira app graph` per-Aplicacao print line's paired
7371    /// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
7372    /// then-inner-accessor chains (which drive the human-readable
7373    /// distribution summary of the typed Aplicacao view) — three open-
7374    /// coded outer-field accesses that expressed no compile-time link
7375    /// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
7376    /// extension of the `:placement` outer axis to a richer author surface
7377    /// (a per-cluster placement overlay the operator pins through a
7378    /// future `:placement-overrides` slot the MESH-COMPOSITION §V
7379    /// federation roadmap acknowledges, a per-tenant placement-alias
7380    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
7381    /// resolves per-CR at admission time, a per-Aplicacao dynamic
7382    /// placement-composite derivation the future M5 adaptive-placement
7383    /// engine computes from a per-cluster load-topology reader, a
7384    /// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
7385    /// partition once Orleans-style virtual-actor dynamic-placement comes
7386    /// into typed scope) would have had to be threaded through all three
7387    /// open-coded copies in lockstep or one consumer would silently
7388    /// disagree with the peers on which placement composite a given
7389    /// Aplicacao resolves to — the validator's per-axis bracket-dispatch
7390    /// seed reading the raw slot while the peer
7391    /// `programs_for_aplicacao` emitter read an operator-resolved slot
7392    /// would silently split the build-time distribution-shape gate from
7393    /// the runtime programs.yaml distribution-annotation gate, a three-
7394    /// consumer split at the validator, the programs.yaml emitter, and
7395    /// the `feira app graph` printer far from the source `caixa.lisp`
7396    /// with no field naming the placement-drift root cause. Lifting the
7397    /// resolution rule to a typed method on the substrate primitive
7398    /// means every downstream consumer of the Aplicacao's per-
7399    /// `:placement` distribution composite surface reaches for exactly
7400    /// one typed dispatch — the resolver's accept-set migrates as a unit
7401    /// on any future axis addition.
7402    ///
7403    /// Second `&Composite`-return accessor on the top-level M3 mesh-slot
7404    /// `AplicacaoSpec` type itself — sibling to the seed
7405    /// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
7406    /// composite-reference accessor on the peer per-`:politicas` outer-
7407    /// composite axis, and to the paired slice-return accessors
7408    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
7409    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
7410    /// the two `Vec`-carry axes on the outer typed composition view; the
7411    /// outer `:placement` composite-reference axis is the natural pair
7412    /// to the peer `:politicas` composite-reference axis on the two
7413    /// operationally-symmetric M3 mesh slots (`:politicas` carries the
7414    /// how-to-run policy overlay, `:placement` carries the where-to-run
7415    /// distribution composite — every whole-Aplicacao mesh-artifact
7416    /// emitter reads both as one unit). Same "one typed dispatch on the
7417    /// substrate primitive, thin projections at each consumer"
7418    /// discipline the peer per-`:politicas` composite-reference axis
7419    /// already routes through. The one remaining outer-composite axis
7420    /// still unlifted at the time of this lift —
7421    /// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
7422    /// external-gateway composite) — inherits this accessor's discipline
7423    /// as the next compounding run migrates its consumers onto the shared
7424    /// reference-return shape, closing the outer-composite altitude on
7425    /// every M3 mesh-slot axis. Named `placement()` to match the storage
7426    /// field's name verbatim and the tatara-lisp author-surface term
7427    /// (`:placement`) the field's own docstring already carries; the
7428    /// accessor's identity maps onto the canonical MESH-COMPOSITION §II
7429    /// vocabulary the slot's docstring already reaches for. Returns
7430    /// `&Placement` (not the owning composite by copy or clone) because
7431    /// every downstream consumer of the placement composite treats it as
7432    /// a read-only per-axis dispatch source — the reference-view is the
7433    /// narrowest borrow that supports every present + roadmapped consumer
7434    /// (per-axis accessor dispatch, serde composite-serialization) without
7435    /// cloning the composite through every consumer's fast path.
7436    #[must_use]
7437    pub const fn placement(&self) -> &Placement {
7438        &self.placement
7439    }
7440
7441    /// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
7442    /// per-Aplicacao external-gateway composite optional-composite-
7443    /// reference accessor every per-Aplicacao gateway-block reader
7444    /// keys off — returns the author-declared `:entrada` composite
7445    /// verbatim as an `Option<&Entrada>` reference over the same
7446    /// backing storage the raw `self.entrada.as_ref()` field access
7447    /// borrows from, with `None` naming the internal-only mesh shape
7448    /// (the author-omitted `:entrada` slot the K8s Gateway API v1
7449    /// gateway_routes emitter treats as "emit nothing" and the peer
7450    /// `feira app graph` printer treats as "internal-only mesh").
7451    ///
7452    /// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
7453    /// external-gateway composite — the load-bearing container of
7454    /// every does-this-Aplicacao-expose-a-public-endpoint axis every
7455    /// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
7456    /// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
7457    /// hostname axis, §III.4 for the `:para` destination-Servico
7458    /// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
7459    /// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
7460    /// axis threads through a lifted per-slot accessor on the
7461    /// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
7462    /// Gateway-API `Listener.hostname` scalar accessor, the paired
7463    /// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
7464    /// singleton-list resolver, the [`Entrada::destination`] (821a80e)
7465    /// backendRefs destination-Servico scalar accessor, the
7466    /// [`Entrada::resolved_paths`] path-fallback resolver, and the
7467    /// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
7468    /// scalar accessor. Every downstream consumer that reaches for
7469    /// an entrada axis first passes through this outer accessor onto
7470    /// the composite and then dispatches onto the per-axis accessor
7471    /// — the two-level dispatch means every per-`:entrada` reader
7472    /// now routes through a typed dispatch on the substrate primitive
7473    /// at both altitudes.
7474    ///
7475    /// Prior to this lift the `.entrada` `Option<Entrada>` composite
7476    /// was accessed inline at four production sites — the
7477    /// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
7478    /// gate's `if let Some(e) = &self.entrada { … }` traversal head
7479    /// (which drives every per-axis refusal on the composite: the
7480    /// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
7481    /// `EntradaMemberMissing` membership lookup against the
7482    /// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
7483    /// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
7484    /// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
7485    /// per-path shape gate on each entry of `e.paths`), the
7486    /// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
7487    /// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
7488    /// composite-projection seed (which drives the destination-
7489    /// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
7490    /// backendRefs port emitter fans on), the
7491    /// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
7492    /// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
7493    /// early-return seed (which drives the "no `:entrada` ⇒ no
7494    /// external artifacts" partition on the whole-Aplicacao Gateway-
7495    /// API emitter's fan-out), and the `feira app graph` per-
7496    /// Aplicacao print line's `if let Some(e) = &spec.entrada`
7497    /// external-gateway summary emitter (which drives the human-
7498    /// readable `entrada: host → para (paths=…, port=…)` /
7499    /// `entrada: (internal-only mesh)` partition on the typed
7500    /// Aplicacao view) — four open-coded outer-field accesses that
7501    /// expressed no compile-time link back to the typed slot at the
7502    /// [`AplicacaoSpec`] altitude. A future extension of the
7503    /// `:entrada` outer axis to a richer author surface (a
7504    /// multi-`:entrada` list the M4 CR materializer resolves per-CR
7505    /// at admission time so an Aplicacao can expose a public-web +
7506    /// admin-web pair, a per-cluster `:entrada-overrides` slot the
7507    /// MESH-COMPOSITION §V federation roadmap acknowledges so an
7508    /// operator can pin a per-cluster hostname override without
7509    /// re-authoring the `caixa.lisp`, a promotion of the plain
7510    /// `Option<Entrada>` to a richer `{single, multi}` partition once
7511    /// the multi-`:entrada` roadmap lands) would have had to be
7512    /// threaded through all four open-coded copies in lockstep or one
7513    /// consumer would silently disagree with the peers on which
7514    /// entrada composite a given Aplicacao resolves to — the
7515    /// validator's per-axis bracket-dispatch seed reading the raw
7516    /// slot while the peer `gateway_routes` emitter read an
7517    /// operator-resolved slot would silently split the build-time
7518    /// gateway-shape gate from the runtime Gateway + HTTPRoute
7519    /// emission gate, a four-consumer split at the validator, the
7520    /// `port_for_destination` L4-port resolver, the `gateway_routes`
7521    /// emitter, and the `feira app graph` printer far from the
7522    /// source `caixa.lisp` with no field naming the entrada-drift
7523    /// root cause. Lifting the resolution rule to a typed method on
7524    /// the substrate primitive means every downstream consumer of
7525    /// the Aplicacao's per-`:entrada` external-gateway composite
7526    /// surface reaches for exactly one typed dispatch — the
7527    /// resolver's accept-set migrates as a unit on any future axis
7528    /// addition.
7529    ///
7530    /// Third and final `&Composite`-return accessor on the top-level
7531    /// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
7532    /// unlifted outer-composite axis on the outer typed composition
7533    /// view, sibling to the seed [`AplicacaoSpec::politicas`]
7534    /// (534dc21) `&MeshPolicy` mesh-policy composite-reference
7535    /// accessor on the per-`:politicas` outer-composite axis and to
7536    /// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
7537    /// distribution-composite composite-reference accessor on the
7538    /// per-`:placement` outer-composite axis; extends the outer-
7539    /// composite reference-return discipline the two peers already
7540    /// route through onto the last unlifted per-`AplicacaoSpec`
7541    /// outer-composite axis. The `:entrada` outer-composite axis is
7542    /// the natural pair to the two peer outer-composite axes on the
7543    /// three operationally-symmetric M3 mesh-slot outer composites
7544    /// (`:politicas` carries the how-to-run policy overlay,
7545    /// `:placement` carries the where-to-run distribution composite,
7546    /// `:entrada` carries the who-can-reach-it external-gateway
7547    /// composite — every whole-Aplicacao mesh-artifact emitter reads
7548    /// all three as one unit). Same "one typed dispatch on the
7549    /// substrate primitive, thin projections at each consumer"
7550    /// discipline the peer outer-composite axes already route through.
7551    /// Named `entrada()` to match the storage field's name verbatim
7552    /// and the tatara-lisp author-surface term (`:entrada`) the
7553    /// field's own docstring already carries; the accessor's
7554    /// identity maps onto the canonical MESH-COMPOSITION §III.4
7555    /// vocabulary the slot's docstring already reaches for. Returns
7556    /// `Option<&Entrada>` (not the owning composite by copy or
7557    /// clone) because every downstream consumer of the entrada
7558    /// composite treats it as a read-only per-axis dispatch source
7559    /// — the reference-view is the narrowest borrow that supports
7560    /// every present + roadmapped consumer (per-axis accessor
7561    /// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
7562    /// port-fallback projection, early-return partition on the
7563    /// `None` arm) without cloning the composite through every
7564    /// consumer's fast path. The `Option` half of the return-type
7565    /// preserves the load-bearing "author-omitted `:entrada` ⇒
7566    /// internal-only mesh" partition (not a default composite the
7567    /// downstream must reject on emptiness) — the accessor projects
7568    /// the raw `Option<Entrada>` slot's presence bit through the
7569    /// reference-return unchanged.
7570    #[must_use]
7571    pub const fn entrada(&self) -> Option<&Entrada> {
7572        self.entrada.as_ref()
7573    }
7574
7575    /// Validate the typed shape:
7576    ///   - `:membros` is non-empty; every entry has a non-empty `:caixa`
7577    ///     and a non-empty `:versao`; no two entries share the same
7578    ///     `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
7579    ///     not a multiset)
7580    ///   - every `:contratos` :de + :para must be in `:membros`
7581    ///   - no `:contratos` edge is a self-edge (`:de == :para`) — a
7582    ///     contract is an inter-Servico edge, so a Servico contracting
7583    ///     with itself is a build error under every WIT shape
7584    ///     (MESH-COMPOSITION §III.1)
7585    ///   - no two `:contratos` entries agree on
7586    ///     `(de, para, wit, endpoint, subject, slot)` — the typed-graph
7587    ///     edges are a set, not a multiset (peer of the `:membros` /
7588    ///     `:placement :clusters` / `:entrada :paths` duplicate gates)
7589    ///   - `:entrada :para` must be in `:membros`
7590    ///   - `:placement Sharded` must declare `:shard-key` (non-empty);
7591    ///     `:placement Replicated`/`SingleNode` must NOT declare
7592    ///     `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
7593    ///     consumes it (MESH-COMPOSITION §II.4), and the typed partition
7594    ///     between strategy and shard-key is symmetric: every validated
7595    ///     `Placement` has `shard_key.is_some()` iff `estrategia ==
7596    ///     Sharded`
7597    ///   - every `:placement` strategy must declare ≥1 `:clusters` entry —
7598    ///     `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
7599    ///     the shard pool (MESH-COMPOSITION §III.1)
7600    ///   - every `:clusters` entry is non-empty and unique
7601    ///   - `:placement :affinity`, when set, is non-empty
7602    ///   - the synchronous-`:contratos` subgraph is acyclic
7603    ///     (MESH-COMPOSITION §III.3)
7604    ///   - every declared `:politicas` value is operationally meaningful
7605    ///     (zero timeout, zero retries, zero breaker thresholds, zero rate
7606    ///     limit are all build errors — MESH-COMPOSITION §V CSE invariants;
7607    ///     omit the field instead to express "no policy on this axis")
7608    pub fn validate(&self) -> Result<(), AplicacaoError> {
7609        self.validate_membros()?;
7610
7611        // `:contratos` per-slot gate — folds both structural axes on the
7612        // slot into one substrate primitive: the per-entry cascade (shape
7613        // + membership + self-loop + `:wit` emptiness + WIT-shape ↔
7614        // target + whole-edge dedup) and the cross-edge sync-cycle axis
7615        // ([`AplicacaoSpec::detect_sync_cycles`], MESH-COMPOSITION §III.3
7616        // — pub-sub edges excluded, "acyclic by construction"). Same
7617        // fold-per-axis-plus-cross-axis discipline the sibling
7618        // [`AplicacaoSpec::validate_politicas`] per-slot gate carries via
7619        // [`MeshPolicy::validate`] (f03a154 / 90a6f87), extended here
7620        // onto `:contratos` so every future consumer of the slot (the M4
7621        // admission webhook re-checking `:contratos` after a per-edge
7622        // patch, the per-edge policy resolver MESH-COMPOSITION §III.2 #3
7623        // acknowledges) reaches *both* structural axes through one call.
7624        self.validate_contratos()?;
7625
7626        self.validate_entrada()?;
7627
7628        self.validate_placement()?;
7629
7630        self.validate_politicas()?;
7631
7632        Ok(())
7633    }
7634
7635    /// The `:membros` graph-node name set — the membership oracle every
7636    /// per-Aplicacao name-reference axis resolves against.
7637    ///
7638    /// Three per-Aplicacao axes carry a Servico-name *reference* rather
7639    /// than a Servico-name *declaration*: `:contratos :de`, `:contratos
7640    /// :para`, and `:entrada :para`. Each must resolve to a declared
7641    /// `:membros :caixa` (MESH-COMPOSITION §III.1 — the typed edges and
7642    /// the external gateway both address graph nodes, so a reference to
7643    /// a node the graph does not contain is a build error). All three
7644    /// resolve against *this* set, so the set's construction is the one
7645    /// shared substrate primitive underneath the whole reference-
7646    /// resolution surface.
7647    ///
7648    /// Lifted out of [`AplicacaoSpec::validate`]'s inline
7649    /// `self.membros().iter().map(Membro::nome).collect()` builder so
7650    /// the two per-slot gates that consume it — the per-`:contratos`
7651    /// membership arms still inline at `validate` and the lifted
7652    /// [`AplicacaoSpec::validate_entrada`] below — reach the same
7653    /// oracle through one dispatch rather than each open-coding the
7654    /// projection. Every future consumer on the same axis (the M4
7655    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
7656    /// reference resolver, the per-`:contratos`-edge `:politicas`
7657    /// override MESH-COMPOSITION §III.2 #3 acknowledges — which
7658    /// resolves an edge's endpoints against the same membership set
7659    /// before it can key a per-edge policy off them) inherits the
7660    /// projection through the same call, so a future rebrand of the
7661    /// node-identity axis (a namespace-qualified member name the CR
7662    /// materializer applies per-CR, the `:membros :nome-suffix`
7663    /// overlay §III.2 acknowledges) lands at exactly one place rather
7664    /// than at every reference-resolution site in lockstep. Peer of
7665    /// the sibling per-slot substrate primitives
7666    /// [`MeshPolicy::validate`] (f03a154) and
7667    /// [`WitContract::identity`] on their own axes.
7668    fn membro_names(&self) -> std::collections::HashSet<&str> {
7669        self.membros().iter().map(Membro::nome).collect()
7670    }
7671
7672    /// Reject `:contratos` entries whose endpoints are malformed,
7673    /// reference a Servico outside the graph, self-loop, carry an
7674    /// empty `:wit` shape, duplicate a prior entry on the six-axis
7675    /// identity key, or close a synchronous-edge cycle in the
7676    /// resulting typed graph.
7677    ///
7678    /// The `:contratos` slot is the typed inter-Servico edge set
7679    /// (MESH-COMPOSITION §III.1): each entry is a WIT-typed directed
7680    /// edge whose `:de` / `:para` reference two distinct members and
7681    /// whose `:wit` picks the payload shape the paired L4/L7 renderer
7682    /// (caixa-mesh's per-`(:de, :para)` `CiliumNetworkPolicy` +
7683    /// per-HTTP `HTTPRoute`) fans out on.
7684    ///
7685    /// Two structural axes on the slot are folded into this per-slot
7686    /// gate: the per-entry axis (six per-edge arms, listed below) and
7687    /// the cross-edge synchronous-cycle axis (MESH-COMPOSITION §III.3,
7688    /// dispatched to [`AplicacaoSpec::detect_sync_cycles`] after the
7689    /// per-entry cascade). Same
7690    /// per-axis-plus-cross-axis-fold-into-one-per-slot-gate discipline
7691    /// the sibling [`AplicacaoSpec::validate_politicas`] per-slot gate
7692    /// carries via [`MeshPolicy::validate`] (f03a154 / 90a6f87) on the
7693    /// `:politicas` slot, extended here onto `:contratos`.
7694    ///
7695    /// Six per-entry axes are gated first, in the canonical
7696    /// edge-direction order the paired diagnostics already encode
7697    /// (per-arm value shape before graph-membership lookup; structural
7698    /// self-edge before payload-shape target dispatch; whole-edge dedup
7699    /// last):
7700    ///
7701    ///   - per-arm `:de` / `:para` value shape via
7702    ///     [`validate_contrato_caixa`] (empty + DNS-1123 grammar),
7703    ///     `:de` before `:para`;
7704    ///   - per-edge graph-membership against the
7705    ///     [`AplicacaoSpec::membro_names`] oracle via
7706    ///     [`WitContract::require_endpoints_in`] (folds the twin
7707    ///     `:de` / `:para` arms onto one substrate-primitive
7708    ///     dispatch), `:de` before `:para`;
7709    ///   - structural self-edge via [`WitContract::is_self_loop`]
7710    ///     (caller-equals-callee under any WIT shape);
7711    ///   - `:wit` emptiness ([`AplicacaoError::EmptyWit`]);
7712    ///   - WIT shape ↔ target consistency via [`WitContract::target`]
7713    ///     (the four `WitTarget` arms — `Http` / `PubSub` / `Store` /
7714    ///     `Capability` — each carry their own required payload field);
7715    ///   - six-axis whole-edge dedup via [`WitContract::identity`]
7716    ///     ([`ContratoIdentity`]'s `(de, para, wit, endpoint, subject,
7717    ///     slot)` tuple).
7718    ///
7719    /// One cross-edge axis is gated last, after the per-entry cascade
7720    /// completes cleanly:
7721    ///
7722    ///   - synchronous-edge cycle detection via
7723    ///     [`AplicacaoSpec::detect_sync_cycles`] (iterative DFS with
7724    ///     three-coloring over the sync-only subgraph, pub-sub edges
7725    ///     skipped per MESH-COMPOSITION §III.3 —
7726    ///     [`AplicacaoError::ContratoCycle`]). Runs *after* the
7727    ///     per-entry cascade so a per-entry defect surfaces through its
7728    ///     narrower shape/membership/dedup arm before the cross-edge
7729    ///     cycle diagnostic, matching the pre-fold `validate`-side
7730    ///     dispatch ordering (`validate_contratos()? →
7731    ///     detect_sync_cycles()?`).
7732    ///
7733    /// Lifted out of [`AplicacaoSpec::validate`]'s inline `let mut
7734    /// seen_contracts = …; for c in self.contratos() { … }` block onto
7735    /// a named per-slot gate, closing the last unlifted per-slot gate
7736    /// on the M3 mesh-slot family. Every peer slot already carries the
7737    /// shape ([`AplicacaoSpec::validate_membros`],
7738    /// [`AplicacaoSpec::validate_entrada`],
7739    /// [`AplicacaoSpec::validate_placement`],
7740    /// [`AplicacaoSpec::validate_politicas`]).
7741    ///
7742    /// Self-contained on `&self` — it resolves its own membership
7743    /// oracle through [`AplicacaoSpec::membro_names`] rather than
7744    /// borrowing one threaded down from `validate`, and runs its own
7745    /// cross-edge cycle probe rather than deferring the axis to an
7746    /// outer dispatch — so a future consumer that re-validates *one*
7747    /// slot against a mutated spec (the M4 admission webhook
7748    /// re-checking `:contratos` after a per-`(:de, :para)` edge patch
7749    /// without re-walking `:membros` / `:entrada` / `:placement` /
7750    /// `:politicas`, or the M4 per-edge policy resolver
7751    /// MESH-COMPOSITION §III.2 #3 acknowledges — which resolves an
7752    /// effective per-edge [`MeshPolicy`] and must re-check the edge's
7753    /// own identity closure *and* the sync-cycle invariant before it
7754    /// can key a per-edge override off the endpoint tuple) reaches
7755    /// *both* structural axes on the slot through one call, exactly as
7756    /// [`AplicacaoSpec::validate_politicas`] reaches both per-axis and
7757    /// cross-axis surfaces on `:politicas` through
7758    /// [`MeshPolicy::validate`].
7759    fn validate_contratos(&self) -> Result<(), AplicacaoError> {
7760        let names = self.membro_names();
7761
7762        // Identity key for the typed-edge duplicate gate below: every
7763        // field that distinguishes one contract from another. Two
7764        // entries that agree on all six are *the same edge declared
7765        // twice*, the typed-graph analogue of duplicate `:membros` /
7766        // `:placement :clusters` / `:entrada :paths` entries (which
7767        // are already build errors at this layer). Rejecting it at the
7768        // validate gate closes a renderer-side footgun: caixa-mesh's
7769        // `cilium_network_policies` keys each emitted policy by
7770        // `<aplicacao>-<de>-to-<para>`, so two contracts with identical
7771        // (de, para) and identical payload would land as two K8s
7772        // objects with colliding `metadata.name`, rejected at apply
7773        // time far from the source caixa.lisp.
7774        let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
7775            std::collections::HashSet::new();
7776        for c in self.contratos() {
7777            // Per-axis value-shape gate on every `:contratos` name
7778            // reference, before any graph-membership lookup. Empty +
7779            // DNS-1123-malformed `:de`/`:para` values silently fell
7780            // through to `ContratoMemberMissing` at the lookup arm
7781            // because every `:membros :caixa` is shape-validated
7782            // (3f9d7a0), so the `names` set structurally cannot contain
7783            // an empty / malformed string and the membership-lookup
7784            // diagnostic always misframed the root cause as
7785            // "this caixa is not in `:membros`". The shape gate runs
7786            // ahead of the lookup so structurally-impossible-to-match
7787            // inputs route through the narrower self-locating
7788            // diagnostic, preserving the legitimate "well-shaped
7789            // phantom reference" arm. `:de` runs before `:para` per
7790            // the canonical edge-direction order the existing
7791            // membership lookup, self-edge check, target dispatch,
7792            // and diagnostic strings already use.
7793            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
7794            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
7795            // Per-edge graph-membership gate on the twin `:de` / `:para`
7796            // arms — folded onto the substrate-primitive dispatch
7797            // [`WitContract::require_endpoints_in`] so every per-edge
7798            // consumer of the endpoint-resolution axis (this per-slot
7799            // gate at build time, the M4 admission webhook re-checking
7800            // one edge after a per-`(:de, :para)` patch, the per-edge
7801            // `:politicas` override MESH-COMPOSITION §III.2 #3
7802            // acknowledges) reaches the axis through one call rather
7803            // than re-inlining the twin `if !names.contains(...)`
7804            // cascade. `:de` fires before `:para` inside the primitive,
7805            // preserving byte-equal diagnostic ordering with the
7806            // pre-lift inline cascade.
7807            c.require_endpoints_in(&names)?;
7808            // A `:contratos` entry is an *inter*-Servico contract
7809            // (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
7810            // typed edge between two distinct graph nodes. An edge whose
7811            // `:de` equals its `:para` is a Servico contracting with
7812            // itself — a degenerate edge under every WIT shape. Firing
7813            // the gate before the `:wit`/`target()` shape checks means
7814            // the structural "this edge can't exist" error precedes the
7815            // narrower payload-shape diagnostics, and shape-agnostically
7816            // covers all four `WitTarget` arms (HTTP / Store / Capability
7817            // / PubSub) at one point. Peer of the duplicate-`:contratos`
7818            // / duplicate-`:membros` set gates: both reject a structurally
7819            // ill-formed graph at the typed surface, before the renderer
7820            // emits a K8s object that fails or no-ops far from the source
7821            // caixa.lisp.
7822            if c.is_self_loop() {
7823                return Err(AplicacaoError::contrato_self_loop(c));
7824            }
7825            if c.world_ref().is_empty() {
7826                return Err(AplicacaoError::empty_wit(c.edge_pair()));
7827            }
7828            // Shape ↔ target consistency — surfaces "HTTP wit without
7829            // :endpoint", "NATS wit with :endpoint set", etc. as named
7830            // build errors instead of silent renderer drops. Threaded
7831            // through the duplicate-edge diagnostic below (via
7832            // [`WitTarget::label`]) so the "which typed target arm did
7833            // the duplicate carry" question is answered by the typed
7834            // enum's variant discriminator, not by re-probing the raw
7835            // `Option<String>` payload fields.
7836            let target_view = c.target()?;
7837            // Contract identity: (de, para, wit, endpoint, subject, slot).
7838            // Two contracts that match on all six are the same typed edge
7839            // declared twice — author error, not a legitimate variant of
7840            // "same caller-callee pair, different payload" (e.g.
7841            // cart→catalog at /products vs /search), which keeps distinct
7842            // identity keys via the differing endpoint payloads.
7843            let key = c.identity();
7844            crate::render::insert_first_seen(&mut seen_contracts, key, || {
7845                let (de, para, wit) = c.edge_triple();
7846                AplicacaoError::ContratoDuplicate {
7847                    de,
7848                    para,
7849                    wit,
7850                    target: target_view.label(),
7851                }
7852            })?;
7853        }
7854
7855        // Cross-edge cycle axis on the `:contratos` slot — folded into
7856        // the per-slot gate so the two structural axes on `:contratos`
7857        // (per-entry shape + membership + dedup above; cross-edge sync-
7858        // cycle detection here) reach every consumer through one call.
7859        // Same discipline the sibling per-slot compound gate
7860        // [`MeshPolicy::validate`] (f03a154) established on `:politicas`
7861        // — one named per-slot gate that folds *both* per-axis and
7862        // cross-axis surfaces on the same slot onto one substrate
7863        // primitive — extended here onto `:contratos`, closing the last
7864        // per-slot-axis-family that lived split across `validate` (the
7865        // per-entry `validate_contratos` half here and the cross-edge
7866        // `detect_sync_cycles` call the sibling below at `validate`
7867        // dispatched separately).
7868        //
7869        // Runs after the per-entry cascade so a per-entry defect (empty
7870        // arm, unknown endpoint, self-loop, empty `:wit`, WIT-shape ↔
7871        // target inconsistency, whole-edge duplicate) surfaces first
7872        // through its narrower [`AplicacaoError`] arm before the cross-
7873        // edge cycle diagnostic. This matches the pre-lift ordering the
7874        // `validate`-side dispatch used verbatim (`self.validate_contratos()?
7875        // → self.detect_sync_cycles()?`) — the cycle detector was
7876        // already the second `:contratos`-axis gate in the dispatch,
7877        // just at the outer altitude; the fold moves it under the same
7878        // named per-slot gate without reshaping the diagnostic order.
7879        self.detect_sync_cycles()?;
7880
7881        Ok(())
7882    }
7883
7884    /// Reject `:entrada` values that are operationally meaningless,
7885    /// structurally malformed, or reference a Servico outside the
7886    /// graph.
7887    ///
7888    /// The `:entrada` slot is the Aplicacao's single external ingress
7889    /// (MESH-COMPOSITION §III.1): `:host` + `:port` become a K8s
7890    /// Gateway API v1 `Listener`, `:paths` become the paired
7891    /// `HTTPRoute`'s `matches[].path.value` entries, and `:para` names
7892    /// the member the route forwards to. Omitting the slot entirely is
7893    /// the internal-only-mesh partition — an Aplicacao with no external
7894    /// surface — so the `None` arm is a clean pass, not a refusal.
7895    ///
7896    /// Five axes are gated here, in the canonical order the paired
7897    /// diagnostics already encode (reference-resolution before value
7898    /// shape, per-axis emptiness before per-axis grammar):
7899    ///
7900    ///   - `:para` — DNS-1123 value shape, then membership against the
7901    ///     [`AplicacaoSpec::membro_names`] oracle;
7902    ///   - `:host` — emptiness, then the Gateway API hostname grammar;
7903    ///   - `:port` — the [`SERVICO_PORT_MIN`] structural floor;
7904    ///   - `:paths` — per-entry emptiness, leading-`/`, the Gateway API
7905    ///     path grammar, and set-not-multiset uniqueness.
7906    ///
7907    /// Lifted out of [`AplicacaoSpec::validate`]'s inline `if let
7908    /// Some(e) = self.entrada() { … }` block onto a named per-slot
7909    /// gate, the shape the three peer M3 mesh slots already carry
7910    /// ([`AplicacaoSpec::validate_membros`],
7911    /// [`AplicacaoSpec::validate_placement`],
7912    /// [`AplicacaoSpec::validate_politicas`]). Self-contained on
7913    /// `&self` — it resolves its own membership oracle through
7914    /// [`AplicacaoSpec::membro_names`] rather than borrowing one
7915    /// threaded down from `validate` — so a future consumer that
7916    /// re-validates *one* slot against a mutated spec (the M4 admission
7917    /// webhook re-checking `:entrada` after a gateway-host patch
7918    /// without re-walking the whole `:contratos` graph) reaches the
7919    /// axis through one call, exactly as `detect_sync_cycles` is
7920    /// already self-contained for the M4 per-edge policy resolver.
7921    fn validate_entrada(&self) -> Result<(), AplicacaoError> {
7922        let names = self.membro_names();
7923        if let Some(e) = self.entrada() {
7924            // Route the per-`:entrada` composite-reference read
7925            // through the lifted [`AplicacaoSpec::entrada`] accessor
7926            // rather than the raw `&self.entrada` field access — the
7927            // shape-and-membership gate's traversal head is now the
7928            // canonical read-side surface every per-Aplicacao entrada
7929            // consumer routes through, closing the fourth of four
7930            // open-coded outer-field accesses on the per-`:entrada`
7931            // outer-composite axis.
7932            //
7933            // Shape gate on `:entrada :para` runs ahead of the
7934            // membership lookup. Every `:membros :caixa` past
7935            // `validate_membro_caixa` is a valid DNS-1123 label
7936            // (3f9d7a0), so the `names` set structurally cannot
7937            // contain an empty / malformed string and the membership-
7938            // lookup diagnostic always misframed the root cause as
7939            // "this caixa is not in `:membros`". The shape gate
7940            // routes structurally-impossible-to-match inputs through
7941            // the narrower self-locating diagnostic, preserving the
7942            // legitimate "well-shaped phantom reference" arm — the
7943            // same trajectory the peer `:membros :caixa` (3f9d7a0),
7944            // `:placement :clusters` (6c8c00b), and `:contratos :de`
7945            // / `:para` (8d5af6b) axes already follow. This closes
7946            // the fourth and last Aplicacao-level Servico-name
7947            // reference axis on the canonical DNS-1123 floor.
7948            // Route the per-`:entrada :para` byte-string reads through
7949            // the lifted [`Entrada::destination`] accessor rather than
7950            // the raw `e.para` field access — the three
7951            // per-`AplicacaoSpec::validate` `:entrada :para` consumers
7952            // (shape-gate `validate_entrada_para` arg, membership
7953            // lookup, `EntradaMemberMissing` diagnostic carry) now key
7954            // off exactly one typed dispatch on the substrate
7955            // primitive, closing the last unlifted per-`:entrada :para`
7956            // raw-field-access axis on the M3 mesh-slot validator.
7957            // The `.destination().to_string()` at the diagnostic site
7958            // is byte-identical to `.para.clone()` — pinned by the
7959            // sibling `destination_returns_entrada_para_byte_equal` +
7960            // `destination_borrows_from_entrada_para_storage` accessor
7961            // tests — so a future rebrand of the underlying `:para`
7962            // storage (a lift from `String` to a typed
7963            // `ServicoName(String)` newtype, a per-Aplicacao interning
7964            // arena the M4 CR materializer authors, a
7965            // `smol_str::SmolStr` inline-buffer swap) flows through
7966            // the accessor's one body without a coordinated
7967            // per-consumer rewrite across the M3 mesh validator.
7968            validate_entrada_para(e.destination())?;
7969            if !names.contains(e.destination()) {
7970                return Err(AplicacaoError::entrada_member_missing(e));
7971            }
7972            // Route the per-`:entrada :host` byte-string reads through
7973            // the lifted [`Entrada::hostname`] accessor rather than
7974            // the raw `e.host` field access — the emptiness gate and
7975            // the shape-gate `validate_entrada_host` arg now key off
7976            // exactly one typed dispatch on the substrate primitive,
7977            // closing the last unlifted per-`:entrada :host` raw-
7978            // field-access axis on the M3 mesh-slot validator. Peer
7979            // of the sibling per-`:entrada :para` convergence above
7980            // and pinned by the existing
7981            // `hostname_returns_entrada_host_byte_equal` +
7982            // `hostnames_returns_singleton_of_hostname_accessor`
7983            // accessor tests, so any future
7984            // Gateway-API-shaped host renormalization (a wildcard-
7985            // label lift, a trailing-`.` FQDN substitution, an IDNA
7986            // Punycode round-trip the SNI fan-out overlay authors)
7987            // flows through the accessor's one body without a
7988            // coordinated per-consumer rewrite across the M3 mesh
7989            // validator.
7990            if e.hostname().is_empty() {
7991                return Err(AplicacaoError::EmptyEntradaHost);
7992            }
7993            // The `:host` lands verbatim as a K8s Gateway API v1
7994            // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
7995            // both apiserver-validated against the same restrictive
7996            // pattern: lowercase RFC 1123 DNS subdomain, optional
7997            // single leading wildcard label (`*.`), max length 253,
7998            // per-label max length 63, no IP literals, no scheme,
7999            // no port. Until this gate landed `validate()` only
8000            // refused the empty string (`EmptyEntradaHost`); a
8001            // structurally invalid hostname (`"https://example.com"`,
8002            // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
8003            // `"_underscored.example.com"`, `"FOO.example.com"`,
8004            // `"checkout.quero.cloud."`) silently passed validate
8005            // and the apiserver `field is invalid` error surfaced at
8006            // `kubectl apply` time, far from the source caixa.lisp.
8007            // Lifting the gate to caixa-build time mirrors the
8008            // `:entrada :paths` value-shape trajectory (eb3456d) and
8009            // closes the last unstructured `:entrada` axis.
8010            validate_entrada_host(e.hostname())?;
8011            // Structural-floor gate on `:entrada :port`: every
8012            // validated `Entrada::port` past this gate lies in
8013            // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
8014            // type-inferred ceiling closes the top edge, so no companion
8015            // upper-cap arm is needed here — unlike the peer capped-
8016            // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
8017            // `require_positive_bounded_u32` bracket covers both edges).
8018            // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
8019            // accept-set-floor const rather than the prior inline
8020            // `if e.port == 0` byte-check so a future rebrand of the
8021            // accept-set floor (a hypothetical unprivileged-only
8022            // migration lifting the floor to `1024`, a per-cluster
8023            // scoping the operator pins through a future
8024            // `:placement :port-floor` slot as the M4 typed-slot
8025            // trajectory adds it, the future
8026            // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
8027            // per-Aplicacao gateway resolver reaching for the same
8028            // floor) is a one-line edit on the canonical
8029            // [`SERVICO_PORT_MIN`] declaration, not a coordinated
8030            // rewrite across the emit site + the pin test + every
8031            // future per-target renderer the substrate adds.
8032            if e.port() < SERVICO_PORT_MIN {
8033                return Err(AplicacaoError::EntradaPortZero);
8034            }
8035            // Each `:entrada :paths` entry becomes a K8s Gateway API
8036            // HTTPRoute `matches[].path.value`. The Gateway API rejects
8037            // values that don't start with `/` for `type: PathPrefix`,
8038            // and an empty value is meaningless. Surface those as build
8039            // errors (MESH-COMPOSITION §III.3) rather than apply-time
8040            // failures. Empty `:paths` itself is fine — caixa-mesh
8041            // falls back to a single `/` catch-all.
8042            let mut seen = std::collections::HashSet::new();
8043            // Route the per-entry value-shape gate's traversal head
8044            // through the lifted [`Entrada::paths`] slice accessor
8045            // rather than the raw `&e.paths` field access — the
8046            // per-Aplicacao `:entrada :paths` validate loop now keys
8047            // off the canonical raw-slot surface every downstream
8048            // per-`:entrada` path-list consumer (the sibling
8049            // [`Entrada::resolved_paths`] fallback-applying resolver
8050            // internal reads, `feira app graph`'s per-Aplicacao entrada
8051            // summary line's `{:?}` Debug print) routes through, so any
8052            // future rebrand on the typed slot's raw-slot reader lands
8053            // at exactly one place. Same convergence discipline as the
8054            // sibling [`Placement::clusters`] (a6e18d7) reader-site
8055            // convergences on the peer M3 mesh-slot `Vec<String>`-carry
8056            // axis.
8057            for p in e.paths() {
8058                if p.is_empty() {
8059                    return Err(AplicacaoError::EntradaPathEmpty);
8060                }
8061                if !p.starts_with('/') {
8062                    return Err(AplicacaoError::entrada_path_not_absolute(p));
8063                }
8064                // Per-entry value-shape gate: the path lands verbatim
8065                // as a K8s Gateway API HTTPRoute `matches[].path.value`
8066                // (caixa-mesh/src/lib.rs:498), apiserver-validated
8067                // against `maxLength: 1024` + the Gateway API webhook's
8068                // path-grammar rules (no `//`, no `/./`, no `/../`, no
8069                // query/fragment separators, no whitespace, no control
8070                // characters, no non-ASCII bytes). Until this gate
8071                // landed `validate` only refused the empty string and
8072                // missing-leading-slash (eb3456d); a structurally
8073                // invalid path (`"/api?q=1"`, `"/api#frag"`,
8074                // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
8075                // 1025-byte URL-shaped slug) silently passed validate
8076                // and the failure surfaced at `kubectl apply` time as
8077                // a Gateway API webhook rejection, far from the source
8078                // caixa.lisp, with no field naming the offending
8079                // `:paths` entry. Lifting the gate to caixa-build time
8080                // mirrors the `:entrada :host` value-shape trajectory
8081                // (c7d05ec) on the sibling axis — every author surface
8082                // that emits a Gateway API field now matches the
8083                // apiserver's accepted set at validate time.
8084                validate_entrada_path(p)?;
8085                crate::render::insert_first_seen(&mut seen, p.as_str(), || {
8086                    AplicacaoError::entrada_path_duplicate(p)
8087                })?;
8088            }
8089        }
8090
8091        Ok(())
8092    }
8093
8094    /// Reject `:membros` values that are operationally meaningless. The
8095    /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
8096    /// every entry names a Servico that participates in the Aplicacao,
8097    /// and the rendered programs.yaml fan-out emits one entry per
8098    /// `:membros`. Three authoring footguns are closed here:
8099    ///
8100    ///   - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
8101    ///     a `programs:` entry whose `name:` is the empty string, which
8102    ///     downstream `lareira-fleet-programs` rejects at template time
8103    ///     with a non-localized error;
8104    ///   - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
8105    ///     an empty semver constraint, so the failure surfaces far from
8106    ///     the source caixa.lisp;
8107    ///   - duplicate `:caixa` names — two entries with the same name
8108    ///     produce duplicate programs.yaml entries (one silently
8109    ///     overwrites the other in the cluster's HelmRelease values), and
8110    ///     contract membership lookups against `:contratos` collapse the
8111    ///     two onto one node, masking authoring mistakes.
8112    ///
8113    /// Same value-shape discipline as `:placement :clusters` (where empty
8114    /// + duplicate cluster names are rejected) and `:entrada :paths`
8115    /// (where empty + duplicate path entries are rejected). Lifting these
8116    /// invariants to the typed surface mirrors the MESH-COMPOSITION
8117    /// §III.3 promise that the `:membros` set — the load-bearing identity
8118    /// of the application graph — is well-formed by construction.
8119    fn validate_membros(&self) -> Result<(), AplicacaoError> {
8120        if self.membros().is_empty() {
8121            return Err(AplicacaoError::NoMembros);
8122        }
8123        let mut seen = std::collections::HashSet::new();
8124        for m in self.membros() {
8125            // Every emitted cluster artifact's `metadata.name` derives
8126            // from a `:membros :caixa` value verbatim — the rendered
8127            // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
8128            // the [`crate::LABEL_PROGRAM`] label value on every CNP
8129            // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
8130            // 272), the composed `CiliumNetworkPolicy` `metadata.name`
8131            // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
8132            // `metadata.name` when the member is the `:entrada :para`
8133            // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
8134            // schema enforces the DNS-1123 label rule on admission;
8135            // a structurally invalid member name (`"Cart"`, `"my_cart"`,
8136            // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
8137            // mistaken-identity slug) silently passes the prior empty-/
8138            // duplicate-only gate and the failure surfaces at `kubectl
8139            // apply` time as a `metadata.name: Invalid value` rejection,
8140            // far from the source caixa.lisp, with no field naming the
8141            // offending `:membros` entry. Lifting the gate to caixa-build
8142            // time mirrors the `:entrada :host` value-shape trajectory
8143            // (c7d05ec) on the peer axis — every author surface that
8144            // emits a K8s name now matches the apiserver's accepted set
8145            // at validate time.
8146            validate_membro_caixa(m.nome())?;
8147            // The author surface for `:versao` is the same Cargo-shaped
8148            // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
8149            // `"*"`) every `:deps` entry carries — and the lacre pipeline
8150            // resolves both axes through the same
8151            // [`crate::version::parse_requirement`] entry-point. The
8152            // shared [`crate::render::require_valid_versao_requirement`]
8153            // helper brackets the empty-first + parse cascade both peer
8154            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
8155            // [`crate::SupervisorSpec::validate`] on `:children :versao`)
8156            // route through, so drift between the three axes' accepted
8157            // requirement sets is structurally impossible and the parse-
8158            // side no-op the empty-first arm closes (semver's empty
8159            // parse yields an implicit `*`) lives in exactly one
8160            // predicate.
8161            crate::render::require_valid_versao_requirement(
8162                m.versao_requirement(),
8163                || AplicacaoError::membro_versao_empty(m.nome()),
8164                |reason| {
8165                    AplicacaoError::membro_versao_invalid(m.nome(), m.versao_requirement(), reason)
8166                },
8167            )?;
8168            crate::render::insert_first_seen(&mut seen, m.nome(), || {
8169                AplicacaoError::membro_duplicate(m.nome())
8170            })?;
8171        }
8172        Ok(())
8173    }
8174
8175    /// Reject `:placement` values that are operationally meaningless or
8176    /// internally contradictory. Each strategy variant has the same
8177    /// invariants on `:clusters` (non-empty list, non-empty unique
8178    /// entries) — the §III.1 author surface is uniform on this axis,
8179    /// even though the *meaning* of the list differs by strategy
8180    /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
8181    /// shard pool).
8182    ///
8183    /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
8184    /// are the same authoring footgun closed for `:politicas` zero
8185    /// values and `:entrada` empty paths: the field is *declared* but
8186    /// carries no meaning, so downstream renderers either skip it
8187    /// silently (cluster-fanout drops the empty entry, no diagnostic)
8188    /// or apply it literally and fail at admission time. Lifting both
8189    /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
8190    /// violation is a build error" promise.
8191    ///
8192    /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
8193    /// is required exactly when `:estrategia Sharded` (hash-keyed
8194    /// distribution, Akka cluster-sharding convention, §II.4) and
8195    /// refused on `:estrategia Replicated`/`SingleNode` (where no
8196    /// hash-keyed routing axis consumes it). The partition closes the
8197    /// "I think I configured sharding" footgun where an author writes
8198    /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
8199    /// the typed slot's value silently vanishes at the renderer layer
8200    /// — every validated `Placement` past this call satisfies
8201    /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
8202    fn validate_placement(&self) -> Result<(), AplicacaoError> {
8203        // Every strategy needs at least one named cluster: `Replicated`
8204        // and `SingleNode` use the list as hosting/takeover candidates
8205        // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
8206        // §II.1), while `Sharded` uses it as the shard pool
8207        // (Akka cluster-sharding convention — §II.4). An empty list is
8208        // meaningless under any of the three.
8209        //
8210        // Route the paired pre-flight `.is_empty()` refusal probe and
8211        // the per-cluster validate loop's traversal head through the
8212        // lifted [`Placement::clusters`] slice-return accessor rather
8213        // than the raw `self.placement.clusters` field access — the
8214        // two production consumers of the per-`:placement` cluster-
8215        // pool `Vec`-carry now key off exactly one typed dispatch on
8216        // the substrate primitive, so any future rebrand on the axis
8217        // (a per-tenant cluster-pool overlay the operator pins through
8218        // a future `:placement :clusters-overrides` slot, a per-
8219        // Aplicacao dynamic cluster-pool derivation the future M5
8220        // adaptive-placement engine computes from `:affinity` weights)
8221        // migrates as a single caixa-core edit rather than a
8222        // coordinated rewrite of the paired arms — sibling of the
8223        // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
8224        // arm migration on the per-`:supervisor` static-child-list
8225        // `Vec`-carry axis.
8226        //
8227        // Route the per-`:placement` outer-composite reference read
8228        // through the lifted [`AplicacaoSpec::placement`] outer accessor
8229        // rather than the raw `&self.placement` field access — the
8230        // per-axis bracket-dispatch fan-out below (`p.clusters()`,
8231        // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
8232        // axis-level lifted accessor family) now routes through the
8233        // substrate-primitive typed dispatch at the outer composition
8234        // altitude, the same shape the peer caixa-mesh
8235        // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
8236        // and the sibling `feira app graph` per-Aplicacao print line
8237        // now key off after this accessor lift.
8238        let p = self.placement();
8239        if p.clusters().is_empty() {
8240            // Route the per-`:placement` empty-clusters diagnostic
8241            // through the substrate-primitive
8242            // [`AplicacaoError::placement_without_clusters`] ctor rather
8243            // than the pre-lift three-line open-coded
8244            // `AplicacaoError::PlacementWithoutClusters { estrategia:
8245            // p.estrategia() }` struct-literal — folds the sole in-crate
8246            // wire-up on this variant onto one dispatch matching the
8247            // sibling per-`:placement :clusters` dedup /
8248            // per-`:contratos` self-edge / per-`:upgrade-from :from`
8249            // duplicate substrate-primitive-projection ctors on the
8250            // same `AplicacaoError` / `UpgradeError` envelopes.
8251            return Err(AplicacaoError::placement_without_clusters(p));
8252        }
8253        let mut seen = std::collections::HashSet::new();
8254        for c in p.clusters() {
8255            // Per-entry value-shape gate: the cluster name lands in
8256            // every K8s context / `lareira-fleet-programs` aggregator
8257            // filter / future M4 CR materializer's per-cluster axis
8258            // a validated `:clusters` entry passes through, each
8259            // enforcing the DNS-1123 label rule on admission. Same
8260            // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
8261            // on the peer name axis — both axes' validated values
8262            // are guaranteed-accepted by the apiserver without
8263            // re-validation at any downstream renderer or admission
8264            // layer.
8265            validate_placement_cluster(c)?;
8266            crate::render::insert_first_seen(&mut seen, c.as_str(), || {
8267                // Route the per-`:placement :clusters` dedup diagnostic
8268                // through the substrate-primitive
8269                // [`AplicacaoError::placement_cluster_duplicate`] ctor
8270                // rather than the pre-lift three-line open-coded
8271                // `AplicacaoError::PlacementClusterDuplicate { cluster:
8272                // c.clone() }` struct-literal — folds the sole in-crate
8273                // wire-up on this variant onto one dispatch matching the
8274                // sibling per-`:membros :caixa` / per-`:entrada :paths` /
8275                // per-`:politicas <scalar>` single-slot ctor families on
8276                // the same [`AplicacaoError`] envelope.
8277                AplicacaoError::placement_cluster_duplicate(c)
8278            })?;
8279        }
8280        // Route the per-`:placement :affinity` per-hint value-shape
8281        // gate through the typed [`Placement::affinity`] accessor rather
8282        // than the raw `&self.placement.affinity` field access — the
8283        // sole open-coded field-access site on the per-`:placement`
8284        // M3-Adaptive-compression-hint axis the accessor lift now owns.
8285        // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
8286        // the accessor's `Option<&str>` return type;
8287        // [`validate_placement_affinity`]'s `&str` parameter accepts
8288        // the narrower borrow without a re-allocation, so the routing
8289        // change is byte-for-byte in the pass arm and remains
8290        // byte-for-byte in every failure diagnostic
8291        // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
8292        // String` field is populated inside
8293        // [`validate_placement_affinity`] via the peer `.to_string()`
8294        // path on the same borrowed slice). Peer of the sibling
8295        // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
8296        // routing through [`Placement::shard_key`] at the caixa-core
8297        // site above — extends the "read `:placement` optional-scalars
8298        // through the typed accessor" discipline to the second
8299        // `Option<String>`-shape slot on the M3 mesh-slot family.
8300        //
8301        // Per-hint value-shape gate: the `:affinity` value lands
8302        // verbatim in the M3 Adaptive compression overlay
8303        // (caixa-mesh's `placement.affinity` emission) and every
8304        // future M4 placement-engine routing axis keying off the
8305        // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
8306        // selector — each enforces the DNS-1123 label rule on
8307        // admission. Same typed-shape trajectory as `:placement
8308        // :clusters` (6c8c00b) on the sibling slot and the four
8309        // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
8310        // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
8311        // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
8312        // on the Aplicacao surface to land on the canonical
8313        // [`crate::render::is_dns_1123_label`] floor.
8314        if let Some(a) = p.affinity() {
8315            validate_placement_affinity(a)?;
8316        }
8317        match p.estrategia() {
8318            // Route the `Sharded`-arm shape-gate cascade through the
8319            // typed [`Placement::shard_key`] accessor rather than the
8320            // raw `&self.placement.shard_key` field access — one of the
8321            // two open-coded field-access sites on the per-`:placement`
8322            // Akka-cluster-sharding-key axis the accessor lift now
8323            // owns. The `Some(k)`-bound `k` narrows from `&String` to
8324            // `&str` under the accessor's `Option<&str>` return type;
8325            // `str::is_empty` and [`validate_placement_shard_key`]'s
8326            // `&str` parameter both accept the narrower borrow without
8327            // a re-allocation.
8328            PlacementStrategy::Sharded => match p.shard_key() {
8329                None => return Err(AplicacaoError::ShardedWithoutKey),
8330                Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
8331                // Per-axis value-shape gate on the Akka-cluster-sharding
8332                // `:shard-key` extractor expression. The shape gate runs
8333                // after the more self-locating `ShardedKeyEmpty` arm so
8334                // a `:shard-key ""` surfaces the narrower empty
8335                // diagnostic first; every non-empty `:shard-key` past
8336                // this call is guaranteed to be a printable-ASCII
8337                // single-token reference the future M4 Akka-style
8338                // cluster-sharding reconciler can hash without
8339                // re-validating at the runtime layer. Mirrors the
8340                // payload-axis shape gates on the peer `:contratos`
8341                // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
8342                // 63e18a0 / c4213a4) — each lifts the runtime parser's
8343                // intersection-floor to a caixa-build-time gate.
8344                Some(k) => validate_placement_shard_key(k)?,
8345            },
8346            // `:shard-key` is the Akka-cluster-sharding axis
8347            // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
8348            // across the cluster pool. `Replicated` (active-active across
8349            // every named cluster) and `SingleNode` (Erlang/OTP
8350            // distributed-app takeover/failover, §II.1) have no hash-keyed
8351            // routing axis to consume the slot; downstream renderers
8352            // (caixa-mesh's `placement.shardKey` overlay at
8353            // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
8354            // sharding reconciler) ignore `:shard-key` outside the
8355            // `Sharded` arm by construction. Until this gate landed an
8356            // author who wrote `:placement (:estrategia Replicated
8357            // :shard-key "tenantId")` (an off-by-one strategy typo, a
8358            // copy-paste from a Sharded sibling caixa, the "I think I
8359            // configured sharding" footgun) silently passed validate and
8360            // the typed slot's value vanished at the renderer layer with
8361            // no diagnostic — the canonical "declared-but-inert" footgun
8362            // the empty-:affinity / empty-shard-key / zero-:politicas /
8363            // empty-:contratos-target gates already close on every other
8364            // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
8365            // Lifting the rejection to a build-time gate closes the
8366            // Sharded ↔ non-Sharded partition over the typed
8367            // `:placement` slot: every validated `Placement` past this
8368            // call has `shard_key.is_some()` iff `estrategia ==
8369            // Sharded`, structurally — the future Akka reconciler can
8370            // reach for `placement.shard_key` knowing it's `Some` exactly
8371            // when the strategy consumes it, without re-deriving the
8372            // partition from inline strategy probes.
8373            PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
8374                // Route the non-`Sharded`-arm declared-but-inert refusal
8375                // through the typed [`Placement::shard_key`] accessor —
8376                // the second of the two open-coded field-access sites the
8377                // accessor lift now owns. The `Some(k)`-bound `k` narrows
8378                // from `&String` to `&str`; the `AplicacaoError::
8379                // ShardKeyOnNonSharded { shard_key: String }` diagnostic
8380                // materializes the owned `String` via `k.to_string()`
8381                // (peer to the sibling per-Membro `String`-carry sites
8382                // 4127bb6 routed through `m.nome().to_string()` /
8383                // `m.versao_requirement().to_string()`), so the whole
8384                // `Sharded` ↔ non-`Sharded` partition on the
8385                // `:shard-key` axis now flows through the same typed
8386                // dispatch as the sibling `Sharded`-arm shape gate.
8387                if let Some(k) = p.shard_key() {
8388                    return Err(AplicacaoError::shard_key_on_non_sharded(p, k));
8389                }
8390            }
8391        }
8392        Ok(())
8393    }
8394
8395    /// Reject `:politicas` values that are operationally meaningless.
8396    /// Each axis is optional — omitting it expresses "no policy on this
8397    /// axis". Carrying a *zero* value for a declared axis is the bug
8398    /// this function rejects: zero is either
8399    ///
8400    ///   - re-interpreted as "infinite" by downstream proxies (Envoy's
8401    ///     `RouteAction.timeout = 0s` disables the timeout entirely),
8402    ///     directly contradicting MESH-COMPOSITION §V CSE invariant
8403    ///     "every Aplicacao declares :politicas :timeout (no infinite
8404    ///     blocking)", or
8405    ///   - a renderer footgun (a 0-failure circuit breaker trips on the
8406    ///     first call; a 0-rate rate-limit denies every request).
8407    ///
8408    /// Lifting these "0 means the opposite of what you think" idioms to
8409    /// the typed Aplicacao surface as build errors mirrors the §III.3
8410    /// promise that contract drift, capability leaks, and cycles are all
8411    /// build errors — not runtime surprises.
8412    fn validate_politicas(&self) -> Result<(), AplicacaoError> {
8413        // Route the whole per-axis + cross-axis `:politicas` cascade
8414        // through the substrate primitive [`MeshPolicy::validate`],
8415        // which folds all six per-axis brackets (`:timeout`,
8416        // `:retries`, `:circuit-breaker :max-failures`,
8417        // `:circuit-breaker :window`, `:rate-limit` rate, `:rate-limit`
8418        // window-canonical-form) plus the compound cross-axis fold
8419        // [`MeshPolicy::first_cross_axis_violation`] into one
8420        // `Result<(), AplicacaoError>` return. The whole per-axis-
8421        // brackets + cross-axis-fold cascade collapses to one call, and
8422        // every future [`MeshPolicy`] consumer (the future M4
8423        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
8424        // admission webhook, the per-`:contratos`-edge `:politicas`
8425        // override MESH-COMPOSITION §III.2 #3 acknowledges — the last
8426        // of which resolves an *effective* per-edge [`MeshPolicy`] and
8427        // must emit *the same* diagnostic on the same input as `feira
8428        // build`) reaches through the same substrate-primitive dispatch
8429        // rather than re-inlining the four-per-axis + one-cross-axis
8430        // cascade in lockstep with this validate gate. Same trajectory
8431        // the peer per-kind compound entry gates
8432        // [`crate::render::require_aplicacao_view`] (7242d45 / 3aefefb),
8433        // [`crate::render::require_supervisor_view`] (8d8a5c3),
8434        // [`crate::render::require_v0_servico_shape`] (per-Caixa
8435        // layout axis) and the sibling compound cross-axis fold
8436        // [`MeshPolicy::first_cross_axis_violation`] (90a6f87) carry —
8437        // extended here onto the per-slot compound entry gate that
8438        // folds both per-axis + cross-axis surfaces on the M3
8439        // mesh-slot family.
8440        self.politicas().validate()
8441    }
8442
8443    /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
8444    /// A synchronous edge is any contract whose typed [`WitTarget`] is
8445    /// `Http`, `Store`, or `Capability` — the caller blocks on the
8446    /// callee, so a cycle would deadlock at runtime. Pub-sub edges
8447    /// (`WitTarget::PubSub`) are skipped: an event publisher does not
8448    /// block on its subscribers, so they can never close a sync loop.
8449    ///
8450    /// Iterative DFS with three-coloring; the reported cycle is the
8451    /// path of caixa names traversed from the back-edge target around
8452    /// to itself, in declaration order. Adjacency lists and DFS roots
8453    /// are visited in `BTreeMap` key order so the diagnostic is
8454    /// deterministic across runs.
8455    ///
8456    /// Now the cross-edge axis of the per-slot compound gate
8457    /// [`AplicacaoSpec::validate_contratos`] — invoked at the tail of
8458    /// the per-entry cascade rather than at the outer
8459    /// [`AplicacaoSpec::validate`] dispatch, so both structural axes on
8460    /// `:contratos` (per-entry shape + membership + dedup; cross-edge
8461    /// sync-cycle) reach every consumer through one call. Kept
8462    /// standalone (rather than inlined) so consumers that want only the
8463    /// cross-edge axis (the M4 per-edge policy resolver
8464    /// MESH-COMPOSITION §III.2 #3 acknowledges, whose per-edge patch
8465    /// mutates one `:contratos` entry and needs to re-probe *just* the
8466    /// cycle invariant against the post-patch adjacency without
8467    /// re-running the per-entry shape/membership/dedup cascade the
8468    /// per-entry-only [M4 admission] fast path already covered) still
8469    /// have a self-contained entry point on the cycle axis.
8470    fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
8471        use std::collections::{BTreeMap, BTreeSet};
8472
8473        #[derive(Clone, Copy, PartialEq, Eq)]
8474        enum Mark {
8475            White,
8476            Gray,
8477            Black,
8478        }
8479
8480        let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
8481        for m in self.membros() {
8482            adj.entry(m.nome()).or_default();
8483        }
8484        for c in self.contratos() {
8485            // target() was already called by validate(); re-running here
8486            // keeps detect_sync_cycles self-contained for callers that
8487            // reuse it (M4 per-edge policy resolver) without revalidating.
8488            //
8489            // The pub-sub-arm check routes through the lifted
8490            // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
8491            // arm-discriminator predicate rather than a raw `matches!(…,
8492            // WitTarget::PubSub { .. })` on the variant so a future
8493            // rebrand on the axis (an M4 per-edge WIT registry split of
8494            // [`WitTarget::PubSub`] into shape-specific peers, a
8495            // per-consumer rename that the accept-set already carries)
8496            // reaches this call site through the derive rather than a
8497            // scattered per-arm `matches!` rewrite — same
8498            // `IsVariant`-derived-arm-discriminator discipline the
8499            // peer closed-set typed enums ([`crate::CaixaKind`] via
8500            // f5bba80, [`PlacementStrategy`] via 766ec63,
8501            // [`crate::supervisor::RestartStrategy`] +
8502            // [`crate::supervisor::RestartPolicy`],
8503            // [`crate::upgrade::UpgradeInstruction`] via 915a934)
8504            // already route through on the substrate's other typed-enum
8505            // arm-discriminator axes.
8506            if c.target()?.is_pubsub() {
8507                continue;
8508            }
8509            adj.entry(c.source()).or_default().insert(c.destination());
8510        }
8511
8512        let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
8513        let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
8514
8515        // Stable DFS root order — BTreeMap iteration is sorted by key.
8516        let roots: Vec<&str> = adj.keys().copied().collect();
8517
8518        // Frame: (node, sorted-neighbours snapshot, next-edge index).
8519        for root in roots {
8520            if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
8521                continue;
8522            }
8523            let root_neighbors: Vec<&str> = adj
8524                .get(root)
8525                .map(|s| s.iter().copied().collect())
8526                .unwrap_or_default();
8527            let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
8528            color.insert(root, Mark::Gray);
8529
8530            loop {
8531                // Read+advance the top frame in one borrow scope so we
8532                // can later mutate the stack (push/pop) without holding
8533                // a borrow across.
8534                let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
8535                    let node = top.0;
8536                    if top.2 >= top.1.len() {
8537                        (node, None)
8538                    } else {
8539                        let nxt = top.1[top.2];
8540                        top.2 += 1;
8541                        (node, Some(nxt))
8542                    }
8543                });
8544                let Some((node, nxt_opt)) = step else { break };
8545                let Some(nxt) = nxt_opt else {
8546                    color.insert(node, Mark::Black);
8547                    stack.pop();
8548                    continue;
8549                };
8550                let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
8551                match nxt_color {
8552                    Mark::Gray => {
8553                        // Reconstruct the cycle from `node` back through
8554                        // the parent chain to `nxt`, then close.
8555                        let mut cycle = Vec::new();
8556                        let mut cur = node;
8557                        cycle.push(cur.to_string());
8558                        while cur != nxt {
8559                            match parent.get(cur).copied() {
8560                                Some(p) => {
8561                                    cur = p;
8562                                    cycle.push(cur.to_string());
8563                                }
8564                                None => break,
8565                            }
8566                        }
8567                        cycle.reverse();
8568                        cycle.push(nxt.to_string());
8569                        return Err(AplicacaoError::contrato_cycle(cycle));
8570                    }
8571                    Mark::White => {
8572                        parent.insert(nxt, node);
8573                        color.insert(nxt, Mark::Gray);
8574                        let nxt_neighbors: Vec<&str> = adj
8575                            .get(nxt)
8576                            .map(|s| s.iter().copied().collect())
8577                            .unwrap_or_default();
8578                        stack.push((nxt, nxt_neighbors, 0));
8579                    }
8580                    Mark::Black => {}
8581                }
8582            }
8583        }
8584        Ok(())
8585    }
8586
8587    /// Substrate-canonical destination-facing TCP port every emitted
8588    /// per-Aplicacao artifact must key `destination`-shaped port axes
8589    /// off. Returns the typed `:entrada :port` scalar when this
8590    /// Aplicacao's `:entrada` block names `destination` under its
8591    /// `:para` axis (the destination Servico *is* the ingress apex, so
8592    /// the substrate honors the author-declared listener port
8593    /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
8594    /// fallback otherwise (every non-apex destination — the internal
8595    /// mesh Servicos `:contratos` reach across, the future per-edge
8596    /// policy resolver's per-destination probe targets, the
8597    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
8598    /// L4 port resolver — reads the same substrate-canonical port floor
8599    /// by construction).
8600    ///
8601    /// Prior to this lift the "if :entrada matches this destination use
8602    /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
8603    /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
8604    /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
8605    /// prior to this lift), with no typed method on the substrate primitive
8606    /// that named the rule. A future per-destination port axis addition
8607    /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
8608    /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
8609    /// per-Servico listener ports land, a per-cluster override the operator
8610    /// pins through a future `:placement :default-port` slot — would have
8611    /// to be threaded through every renderer's inline cascade in lockstep
8612    /// or one consumer would silently disagree on which port a given
8613    /// destination Servico's ingress lands at. Lifting the rule to a
8614    /// typed method on the substrate primitive means the M4 CR
8615    /// materializer, the future per-edge policy resolver, and every
8616    /// downstream test-fixture navigator reach for exactly one typed
8617    /// dispatch — the resolver's accept-set moves as a unit on any
8618    /// future axis addition.
8619    ///
8620    /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
8621    /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
8622    /// the typed primitive, thin projections at each consumer"
8623    /// discipline lifts on the sibling `:contratos` payload / `:politicas
8624    /// :rate-limit` unit-suffix axes; extends the discipline onto the
8625    /// destination-facing port-resolution axis every per-Aplicacao
8626    /// L4-fallback renderer consumes.
8627    #[must_use]
8628    pub fn port_for_destination(&self, destination: &str) -> u16 {
8629        // Route the per-`:entrada` composite-reference read through
8630        // the lifted [`AplicacaoSpec::entrada`] accessor rather than
8631        // the raw `self.entrada.as_ref()` field access — the
8632        // per-destination L4-port fallback resolver's composite-
8633        // projection seed is now the canonical read-side surface
8634        // every per-Aplicacao entrada consumer routes through, peer
8635        // of the sibling `validate` per-`:entrada` shape-and-
8636        // membership gate migration on the same outer-composite
8637        // axis.
8638        // Route the per-`:entrada` apex-destination membership probe
8639        // through the lifted [`Entrada::destination`] accessor rather
8640        // than the raw `e.para == destination` field access — the last
8641        // un-lifted `.para` production-code read site on the per-
8642        // `:entrada` `:para` axis, sibling to the four caixa-core
8643        // consumer sites the peer 15ddd8c converge already routed
8644        // through the accessor (the three
8645        // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
8646        // membership gate sites: the `validate_entrada_para` DNS-1123
8647        // shape gate, the per-`:membros` membership lookup, and the
8648        // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
8649        // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
8650        // `entrada.para`-projection converge at
8651        // caixa-core/src/render.rs (the `gateway_api_http_route_name`
8652        // route-name projection site). Prior to this converge the
8653        // `port_for_destination` resolver was the solitary consumer
8654        // bypassing the typed dispatch on the `.para` axis — the two
8655        // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
8656        // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
8657        // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
8658        // reach through the same accessor family compose with this
8659        // resolver at the emit boundary via the apex-identity
8660        // invariant `spec.port_for_destination(entrada.destination())
8661        // == entrada.port` the sibling
8662        // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
8663        // pin pins across four permutations. A future extension of the
8664        // `:entrada :para` axis to a richer author surface (a per-
8665        // cluster alias overlay the operator pins through a future
8666        // `:placement`-scoped slot, a namespace-qualified rewrite the
8667        // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
8668        // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
8669        // §III.2 acknowledges) that lands on the accessor would silently
8670        // disagree between this resolver and the two `caixa-mesh` emit
8671        // sites — an author-declared `:para "cart"` value the accessor
8672        // rewrote to `"cart-v2"` under a future canary arm would leave
8673        // the resolver's membership arm falling through to
8674        // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
8675        // `.para`) while the peer emit-site consumers landed on the
8676        // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
8677        // silently disagreed on which destination port a given typed
8678        // `:entrada` resolves to at cluster-apply time. Pinned by the
8679        // drift-detection test
8680        // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
8681        // below.
8682        self.entrada()
8683            .filter(|e| e.destination() == destination)
8684            .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
8685    }
8686}
8687
8688/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
8689/// entry may name the Aplicacao's own `:nome`.
8690///
8691/// An Aplicacao that lists itself as a member is a degenerate self-edge in
8692/// the typed graph — the application graph is a DAG rooted at the Aplicacao
8693/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
8694/// Servicos that compose the app; an Aplicacao is never its own constituent),
8695/// and the lacre pipeline's closure-resolution would otherwise be handed a
8696/// node that is its own parent: a one-node cycle it either rejects far from
8697/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
8698/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
8699/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
8700/// label + lacre closure root), a member whose `:caixa` equals the
8701/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
8702/// peer.
8703///
8704/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
8705/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
8706/// gate `validate_upgrade_from_against_versao` and the supervision-tree
8707/// self-parent gate `crate::supervisor::validate_no_self_supervision`
8708/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
8709/// not a tree/mesh edge" discipline, here on the second typed-graph axis
8710/// (the Aplicacao :membros set; the supervision-tree :children list was the
8711/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
8712/// every validated Supervisor's children are distinct from its `:nome`,
8713/// every validated Aplicacao's membros are distinct from its `:nome`. The
8714/// transitive consequence is that `:entrada :para` and `:contratos`
8715/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
8716/// name the Aplicacao itself, without re-deriving the partition.
8717pub fn validate_no_self_membership(
8718    membros: &[Membro],
8719    parent_nome: &str,
8720) -> Result<(), AplicacaoError> {
8721    for m in membros {
8722        if m.nome() == parent_nome {
8723            return Err(AplicacaoError::membro_is_self_aplicacao(parent_nome));
8724        }
8725    }
8726    Ok(())
8727}
8728
8729#[derive(Debug, Error, PartialEq, Eq)]
8730pub enum AplicacaoError {
8731    #[error("Aplicacao must declare at least one :membros entry")]
8732    NoMembros,
8733    #[error(
8734        ":membros entry has empty :caixa (every member must name a Servico; \
8735         omit the entry instead of carrying an empty name)"
8736    )]
8737    MembroCaixaEmpty,
8738    #[error(
8739        ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
8740         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
8741         name / label value the member name lands in; use a lowercase \
8742         alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
8743    )]
8744    MembroCaixaInvalid { caixa: String, reason: String },
8745    #[error(
8746        ":membros entry {caixa:?} has empty :versao (every member must pin a \
8747         semver constraint that resolves through the lacre pipeline)"
8748    )]
8749    MembroVersaoEmpty { caixa: String },
8750    #[error(
8751        ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
8752         requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
8753         `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
8754         carries; the lacre pipeline resolves both through the same parser)"
8755    )]
8756    MembroVersaoInvalid {
8757        caixa: String,
8758        versao: String,
8759        reason: String,
8760    },
8761    #[error(
8762        ":membros entry {caixa:?} appears more than once (the graph node set \
8763         is a set, not a multiset; duplicate members produce duplicate \
8764         programs.yaml entries and ambiguous :contratos membership lookups)"
8765    )]
8766    MembroDuplicate { caixa: String },
8767    #[error(
8768        "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
8769         never its own constituent Servico (the application graph is a DAG rooted \
8770         at the Aplicacao; :membros names the *other* caixas that compose the \
8771         app, not the app itself). Since every :nome is a globally-unique \
8772         substrate identity, a member naming the Aplicacao's own :nome is a \
8773         one-node lacre-closure recursion, not a coincidentally-named peer; \
8774         drop the self-referential :membros entry or rename it to the actual \
8775         constituent caixa."
8776    )]
8777    MembroIsSelfAplicacao { caixa: String },
8778    #[error(
8779        "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
8780         caixa declared in :membros; omit the contract or fill the {slot} field with a \
8781         member name)"
8782    )]
8783    ContratoCaixaEmpty { slot: &'static str },
8784    #[error(
8785        "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
8786         :contratos {slot} value names a member of :membros, which is itself a \
8787         DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
8788         object the member name lands in — Service, Pod, identity-based Cilium \
8789         selector; use a lowercase alphanumeric + hyphen identifier like \
8790         `\"checkout\"` or `\"cart-v2\"`)"
8791    )]
8792    ContratoCaixaInvalid {
8793        slot: &'static str,
8794        caixa: String,
8795        reason: String,
8796    },
8797    #[error("contrato references caixa {caixa:?} not declared in :membros")]
8798    ContratoMemberMissing { caixa: String },
8799    #[error(
8800        "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
8801         entry is an inter-Servico contract whose :de and :para must name distinct \
8802         :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
8803         the contract, or point :para at the member it actually calls)"
8804    )]
8805    ContratoSelfLoop { caixa: String, wit: String },
8806    #[error("contrato {de:?} → {para:?} has empty :wit")]
8807    EmptyWit { de: String, para: String },
8808    #[error(
8809        "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
8810         {reason} (the substrate dispatches `:wit` values on the canonical \
8811         lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
8812         `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
8813         demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
8814         kebab-case identifier per segment)"
8815    )]
8816    ContratoWitInvalid {
8817        de: String,
8818        para: String,
8819        wit: String,
8820        reason: String,
8821    },
8822    #[error(
8823        ":entrada :para is empty (every :entrada must route to a caixa declared in \
8824         :membros; fill the :para field with a member name)"
8825    )]
8826    EntradaParaEmpty,
8827    #[error(
8828        ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
8829         :entrada :para value names a member of :membros, which is itself a DNS-1123 \
8830         label per the K8s apiserver's `metadata.name` rule on every object the \
8831         member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
8832         Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
8833         `\"checkout\"` or `\"cart-v2\"`)"
8834    )]
8835    EntradaParaInvalid { para: String, reason: String },
8836    #[error(":entrada routes to caixa {para:?} not declared in :membros")]
8837    EntradaMemberMissing { para: String },
8838    #[error(":entrada must declare a non-empty :host")]
8839    EmptyEntradaHost,
8840    #[error(
8841        ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
8842         (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
8843         `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
8844         like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
8845    )]
8846    EntradaHostInvalid { host: String, reason: String },
8847    #[error(":entrada :port must be in 1..=65535, got 0")]
8848    EntradaPortZero,
8849    #[error(":entrada :paths entry is empty (use the empty list to match all)")]
8850    EntradaPathEmpty,
8851    #[error(
8852        ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
8853    )]
8854    EntradaPathNotAbsolute { path: String },
8855    #[error(
8856        ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
8857         value: {reason} (the K8s apiserver enforces the same shape on \
8858         `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
8859         single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
8860         requires percent-encoding `%XX` for non-ASCII and whitespace)"
8861    )]
8862    EntradaPathInvalid { path: String, reason: String },
8863    #[error(":entrada :paths entry {path:?} appears more than once")]
8864    EntradaPathDuplicate { path: String },
8865    #[error(
8866        ":placement {estrategia} requires at least one :clusters entry \
8867         (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
8868    )]
8869    PlacementWithoutClusters { estrategia: PlacementStrategy },
8870    #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
8871    PlacementClusterEmpty,
8872    #[error(
8873        ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
8874         (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
8875         in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
8876         future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
8877         — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
8878         identifier like `\"rio\"` or `\"mar-east\"`)"
8879    )]
8880    PlacementClusterInvalid { cluster: String, reason: String },
8881    #[error(":placement :clusters entry {cluster:?} appears more than once")]
8882    PlacementClusterDuplicate { cluster: String },
8883    #[error(
8884        ":placement :affinity must be non-empty when set (omit :affinity to express \
8885         `no placement hint`)"
8886    )]
8887    PlacementAffinityEmpty,
8888    #[error(
8889        ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
8890         (placement hints land verbatim in the M3 Adaptive compression overlay's \
8891         `placement.affinity` field and in every future M4 placement-engine routing \
8892         axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
8893         selector — both enforce the DNS-1123 label rule on admission; use a \
8894         lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
8895         `\"low-latency\"`, or `\"anti-affinity\"`)"
8896    )]
8897    PlacementAffinityInvalid { affinity: String, reason: String },
8898    #[error(":placement Sharded requires :shard-key")]
8899    ShardedWithoutKey,
8900    #[error(
8901        ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
8902         hashes every entity onto the same shard, defeating sharding entirely)"
8903    )]
8904    ShardedKeyEmpty,
8905    #[error(
8906        ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
8907         entity-id extractor expression: {reason} (the future M4 Akka-style \
8908         cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
8909         as a single-token property reference and hashes the extracted entity ID \
8910         to compute shard placement; use a printable-ASCII extractor expression \
8911         like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
8912         `\"${{tenant}}\"`)"
8913    )]
8914    ShardKeyInvalid { shard_key: String, reason: String },
8915    #[error(
8916        ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
8917         Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
8918         convention); :estrategia Replicated runs every cluster active-active and \
8919         :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
8920         distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
8921         to :estrategia Sharded if hash-keyed routing is the intent"
8922    )]
8923    ShardKeyOnNonSharded {
8924        estrategia: PlacementStrategy,
8925        shard_key: String,
8926    },
8927    #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
8928    ContratoMissingTarget {
8929        de: String,
8930        para: String,
8931        wit: String,
8932        expected: &'static str,
8933    },
8934    #[error(
8935        "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
8936         expected `:{expected}` only"
8937    )]
8938    ContratoWrongTarget {
8939        de: String,
8940        para: String,
8941        wit: String,
8942        expected: &'static str,
8943    },
8944    #[error(
8945        "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
8946         like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
8947         that matches no traffic and silently drops every request)"
8948    )]
8949    ContratoEndpointEmpty { de: String, para: String },
8950    #[error(
8951        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
8952         (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
8953         :entrada :paths)"
8954    )]
8955    ContratoEndpointNotAbsolute {
8956        de: String,
8957        para: String,
8958        endpoint: String,
8959    },
8960    #[error(
8961        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
8962         Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
8963         emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
8964         caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
8965         shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
8966         like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
8967         and whitespace)"
8968    )]
8969    ContratoEndpointInvalid {
8970        de: String,
8971        para: String,
8972        endpoint: String,
8973        reason: String,
8974    },
8975    #[error(
8976        "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
8977         subject is a no-op subscribe; omit :subject only if the WIT world is not \
8978         pub-sub-shaped)"
8979    )]
8980    ContratoSubjectEmpty { de: String, para: String },
8981    #[error(
8982        "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
8983         NATS subject: {reason} (the NATS server's subject parser enforces the \
8984         same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
8985         single-token and `>` multi-token wildcards — at publish/subscribe time; \
8986         use a token-by-token form like `\"checkout.events.charge.failed\"` or \
8987         `\"orders.*.completed\"` — a malformed subject silently drops every \
8988         message at runtime far from the source caixa.lisp)"
8989    )]
8990    ContratoSubjectInvalid {
8991        de: String,
8992        para: String,
8993        subject: String,
8994        reason: String,
8995    },
8996    #[error(
8997        "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
8998         addresses the bucket root, defeating the per-key isolation the slot exists \
8999         for; omit :slot only if the WIT world is not store-shaped)"
9000    )]
9001    ContratoSlotEmpty { de: String, para: String },
9002    #[error(
9003        "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
9004         WASI keyvalue store slot template: {reason} (the substrate enforces \
9005         the printable-ASCII intersection-floor every kv backend admits — \
9006         use a single-token path / template expression like `\"checkout/$orderId\"`, \
9007         `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
9008         percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
9009         slot either gets rejected on write by strict backends or silently \
9010         corrupts the next read on permissive ones, far from the source caixa.lisp)"
9011    )]
9012    ContratoSlotInvalid {
9013        de: String,
9014        para: String,
9015        slot: String,
9016        reason: String,
9017    },
9018    #[error(
9019        "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
9020         or an event-sourced indirection (MESH-COMPOSITION §III.3)",
9021        cycle.join(" → ")
9022    )]
9023    ContratoCycle { cycle: Vec<String> },
9024    #[error(
9025        ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
9026         than once (the typed graph edges are a set, not a multiset; duplicate \
9027         contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
9028         values that K8s admission rejects far from the source caixa.lisp)"
9029    )]
9030    ContratoDuplicate {
9031        de: String,
9032        para: String,
9033        wit: String,
9034        target: String,
9035    },
9036    #[error(
9037        ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
9038         contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
9039         express `no per-call deadline on this axis`"
9040    )]
9041    PolicyTimeoutZero,
9042    #[error(
9043        ":politicas :retries must be > 0 when set; omit :retries to express \
9044         `no retries on transient failure`"
9045    )]
9046    PolicyRetriesZero,
9047    #[error(
9048        ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
9049         (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
9050         retry policy into a thundering-herd amplification vector on transient \
9051         failure (one caller request fans out to `(retries+1)^depth` server-side \
9052         calls across the synchronous-:contratos subgraph), exactly the failure \
9053         mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
9054         Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
9055         or omit :retries to disable retries entirely"
9056    )]
9057    PolicyRetriesExceedsCap { retries: u32 },
9058    #[error(
9059        ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
9060         breaker trips on the first call); omit :circuit-breaker to disable it"
9061    )]
9062    PolicyBreakerZeroFailures,
9063    #[error(
9064        ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
9065         mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
9066         above this cap turns the typed breaker policy into a no-op: the trip \
9067         threshold is structurally so high that no realistic failures-per-:window \
9068         traffic shape can reach it, so the breaker never trips and every typed-slot \
9069         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
9070         Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
9071         structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
9072         Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
9073         omit :circuit-breaker to disable the breaker entirely"
9074    )]
9075    PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
9076    #[error(
9077        ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
9078         tracks no failures); omit :circuit-breaker to disable it"
9079    )]
9080    PolicyBreakerZeroWindow,
9081    #[error(
9082        ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
9083         request); omit :rate-limit to disable rate limiting"
9084    )]
9085    PolicyRateLimitZero,
9086    #[error(
9087        ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
9088         (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
9089         rate-limit policy into a no-op limiter: the token-bucket capacity is \
9090         structurally so high that no realistic per-edge traffic shape can drain it, \
9091         so the limiter never trips and every typed-slot consumer (the future \
9092         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9093         local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
9094         that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
9095         Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
9096         Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
9097         Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
9098         to disable rate limiting entirely"
9099    )]
9100    PolicyRateLimitExceedsCap { rate: u32 },
9101    #[error(
9102        ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
9103         the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
9104         rate-limit codec round-trips losslessly; got {window:?} which renders to a \
9105         non-round-trippable form (omit :rate-limit to disable, or pick one of the \
9106         three canonical windows)"
9107    )]
9108    PolicyRateLimitWindowNotCanonical { window: Duration },
9109    #[error(
9110        ":politicas :timeout must be an integer number of milliseconds — the canonical \
9111         authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
9112         duration codec round-trips losslessly; got {timeout:?} which carries a \
9113         sub-millisecond residue that either truncates to a different `Duration` on \
9114         re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
9115         to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
9116         zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
9117         (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
9118    )]
9119    PolicyTimeoutNotCanonical { timeout: Duration },
9120    #[error(
9121        ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
9122         (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
9123         per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
9124         overlays carry a deadline so long no realistic synchronous-:contratos \
9125         traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
9126         CSE invariant degenerates to enforcement only at the per-Servico \
9127         `:limits :wall-clock` layer — far above the per-edge granularity the typed \
9128         `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
9129         (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
9130         ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
9131         maxes out at the same `3600s` ceiling) or omit :timeout to express \
9132         `no per-call deadline on this axis` (the synchronous-call deadline then \
9133         relies entirely on the per-Servico `:limits :wall-clock` axis)"
9134    )]
9135    PolicyTimeoutExceedsCap { timeout: Duration },
9136    #[error(
9137        ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
9138         the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
9139         the shared duration codec round-trips losslessly; got {window:?} which carries a \
9140         sub-millisecond residue that either truncates to a different `Duration` on \
9141         re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
9142         Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
9143    )]
9144    PolicyBreakerWindowNotCanonical { window: Duration },
9145    #[error(
9146        ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
9147         (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
9148         rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
9149         is structurally so long that transient failures are never forgotten, the breaker \
9150         trips once and stays tripped for the lifetime of the component, and every typed-slot \
9151         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9152         outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
9153         Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
9154         default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
9155         the breaker entirely"
9156    )]
9157    PolicyBreakerWindowExceedsCap { window: Duration },
9158    #[error(
9159        ":politicas :circuit-breaker :window ({window:?}) is shorter than :politicas \
9160         :timeout ({timeout:?}) — the rolling failure-observation interval closes before \
9161         a single timing-out call can be declared failed, so the dominant failure mode \
9162         the breaker exists to catch is structurally never counted: a call dispatched at \
9163         t=0 is only reported failed at t={timeout:?}, by which point the window that was \
9164         open at dispatch has already rolled, and every typed-slot consumer (the future \
9165         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9166         outlier_detection.interval paired against the per-route request timeout) emits a \
9167         breaker that cannot trip on timeouts however high the call volume. Pin :window \
9168         at or above :timeout (Hystrix defaults 10s rolling window against a 1s execution \
9169         timeout — a 10× ratio; Envoy / resilience4j production playbooks recommend the \
9170         same shape), lower :timeout, or omit one of the two axes"
9171    )]
9172    PolicyBreakerWindowBelowTimeout { window: Duration, timeout: Duration },
9173    #[error(
9174        ":politicas :rate-limit ({rate} per {rl_window:?}) starves :politicas \
9175         :circuit-breaker so :max-failures ({max_failures}) cannot be reached inside \
9176         :window ({cb_window:?}) — the token-bucket dispatches at most \
9177         `rate × cb_window / rl_window` calls per rolling breaker window, which is \
9178         structurally below the trip threshold, so the breaker cannot trip even under \
9179         100% failure and every typed-slot consumer (the future \
9180         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9181         outlier_detection.consecutive_5xx paired against \
9182         local_rate_limit.token_bucket.max_tokens) emits a protection that is \
9183         structurally never enforced. Raise :rate, shorten :rate-limit :window, lower \
9184         :max-failures, lengthen :circuit-breaker :window, or omit one of the two axes"
9185    )]
9186    PolicyBreakerCannotTripUnderRateLimit {
9187        rate: u32,
9188        rl_window: Duration,
9189        max_failures: u32,
9190        cb_window: Duration,
9191    },
9192    #[error(
9193        ":politicas :retries ({retries}) plus the initial attempt saturates :politicas \
9194         :circuit-breaker :max-failures ({max_failures}) mid-retry — one client's failing \
9195         attempts alone accumulate {retries}+1 failures, which reaches the trip threshold \
9196         at or before the last retry, so the breaker opens with declared retries still \
9197         unused and every typed-slot consumer (the future CiliumClusterwideEnvoyConfig \
9198         per-:politicas overlay, Envoy's retry_policy.num_retries paired against \
9199         outlier_detection.consecutive_5xx) emits a retry policy the substrate \
9200         structurally truncates. Pin :max-failures strictly above :retries (Hystrix / \
9201         Envoy / resilience4j production playbooks recommend the breaker's trip \
9202         threshold be observably larger than any single client's retry budget so the \
9203         breaker distinguishes one persistently-failing client from sustained \
9204         multi-client failure), lower :retries, or omit one of the two axes"
9205    )]
9206    PolicyBreakerTripsBeforeRetriesExhausted { retries: u32, max_failures: u32 },
9207    #[error(
9208        ":politicas :rate-limit ({rate} per window) cannot admit :politicas :retries \
9209         ({retries}) plus the initial attempt — one client's declared retry sequence is \
9210         {retries}+1 attempts, each of which consumes one token from the local rate-limit \
9211         bucket, but the bucket admits at most {rate} tokens per refill window, so the \
9212         retry policy is silently truncated by the same rate limiter it feeds through and \
9213         every typed-slot consumer (the future CiliumClusterwideEnvoyConfig per-:politicas \
9214         overlay, Envoy's retry_policy.num_retries paired against \
9215         local_rate_limit.token_bucket.max_tokens) emits a retry policy the substrate \
9216         structurally throttles. Raise :rate strictly above :retries (Envoy / Istio / \
9217         resilience4j / AWS App Mesh production playbooks recommend the local rate-limit \
9218         bucket capacity be observably larger than any single client's retry budget so the \
9219         limiter distinguishes one client's declared retries from sustained multi-client \
9220         load), lower :retries, or omit one of the two axes"
9221    )]
9222    PolicyRateLimitCannotAdmitRetryBurst { retries: u32, rate: u32 },
9223}
9224
9225// The `AplicacaoError::EntradaHostInvalid { host, reason }` variant's
9226// ctor `entrada_host_invalid` is folded onto the sibling
9227// [`aplicacao_field_reason_ctors!`] macro below alongside the six peer
9228// `{ <field>: String, reason: String }` variants
9229// (`MembroCaixaInvalid` / `EntradaParaInvalid` / `EntradaPathInvalid` /
9230// `PlacementClusterInvalid` / `PlacementAffinityInvalid` /
9231// `ShardKeyInvalid`), so every variant on the uniform two-slot
9232// `{ <field>: String, reason: String }` envelope on [`AplicacaoError`]
9233// reads through one substrate-primitive family rather than one macro
9234// closing six sites plus a hand-written seventh ctor closing the
9235// paired site alone. Prior separate-ctor rationale (17dd504) migrates
9236// verbatim to the macro's outer doc block.
9237
9238// Fold the seven `AplicacaoError::Contrato{Wrong,Missing}Target { de, para,
9239// wit, expected }` wire-up sites at [`WitContract::target`] onto one
9240// substrate-primitive family per typed variant — the paired sibling on
9241// [`AplicacaoError`] of the four `LayoutError` constructor families
9242// [`layout_violation_ctors!`] (131ca0d, 16 variants on `{ caixa, issue }`),
9243// [`layout_slot_kind_ctors!`] (0419438, 4 variants on
9244// `{ caixa, kind, slots }`), [`LayoutError::missing_entry`] (1b09f9d,
9245// 1 variant on `{ kind, path }`), and [`layout_nome_only_ctors!`] (3fe3dd7,
9246// 6 variants on `<Variant>(String)`) each carry on the sibling layout-side
9247// envelope. Every one of the seven wire-up sites in [`WitContract::target`]
9248// (four `ContratoWrongTarget` arms on the payload-field-mismatch axis —
9249// HTTP with subject/slot, PubSub with endpoint/slot, Store with
9250// endpoint/subject, Capability with any payload; three
9251// `ContratoMissingTarget` arms on the payload-field-absent axis — HTTP
9252// without `:endpoint`, PubSub without `:subject`, Store without `:slot`)
9253// opened the identical six-line
9254// `AplicacaoError::Contrato<Wrong|Missing>Target { de, para, wit, expected:
9255// WitTarget::<label> }` struct-literal against the local `edge()` closure
9256// returning `(de, para, wit) = self.edge_triple()` — the exact "same block
9257// re-inlined at every consumer" shape the PRIME DIRECTIVE names as a bug,
9258// on the same altitude the peer four `LayoutError` constructor families
9259// each closed on their sibling envelopes.
9260//
9261// The macro below generates one `#[must_use]` inherent constructor per
9262// variant of shape `fn <ctor>(edge: (String, String, String), expected:
9263// &'static str) -> AplicacaoError`, collapsing the seven sites onto one
9264// dispatch per arm: `return
9265// Err(AplicacaoError::contrato_wrong_target(edge(), <label>));` / `.ok_or_else(||
9266// AplicacaoError::contrato_missing_target(edge(), <label>))?`, byte-equal to
9267// the pre-lift struct-literal on the same edge fixture. The uniform four-
9268// field construction (`de, para, wit` triple-destructure onto same-named
9269// fields + `expected` verbatim) is spelled once — inside the macro —
9270// rather than at every wire-up site. `#[must_use]` fires a compile warning
9271// at any wire-up that mistakenly discards the constructed error.
9272//
9273// Every future consumer that wants to construct one of these two variants
9274// outside [`WitContract::target`] (a deferred
9275// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
9276// admission validator raising wrong-target / missing-target diagnostics
9277// on unrecognized shapes, a future `feira validate --contratos` per-caixa
9278// admission verb, a per-`WitContract` payload-axis pre-emitter probing
9279// the [`WitTarget`] arm against the declared `:endpoint`/`:subject`/`:slot`
9280// slots) reaches the variant through one call rather than re-inlining the
9281// six-line struct-literal block in lockstep with the seven in-crate
9282// wire-up sites.
9283macro_rules! contrato_target_ctors {
9284    ($($ctor:ident => $variant:ident),* $(,)?) => {
9285        impl AplicacaoError {
9286            $(
9287                #[doc = concat!(
9288                    "Construct an [`AplicacaoError::",
9289                    stringify!($variant),
9290                    "`] naming the offending edge `(de, para, wit)` triple ",
9291                    "under the given `expected` payload-field-name label. ",
9292                    "Folds the uniform `{ de, para, wit, expected }` four-",
9293                    "slot struct-literal onto one substrate primitive so ",
9294                    "every [`WitContract::target`] wire-up on this variant ",
9295                    "reads through one dispatch rather than the pre-lift ",
9296                    "six-line open-coded block. The `edge` triple threads ",
9297                    "verbatim from [`WitContract::edge_triple`] via the ",
9298                    "local `edge()` closure at the call site."
9299                )]
9300                #[must_use]
9301                pub fn $ctor(edge: (String, String, String), expected: &'static str) -> Self {
9302                    let (de, para, wit) = edge;
9303                    Self::$variant { de, para, wit, expected }
9304                }
9305            )*
9306        }
9307    };
9308}
9309
9310contrato_target_ctors! {
9311    contrato_wrong_target => ContratoWrongTarget,
9312    contrato_missing_target => ContratoMissingTarget,
9313}
9314
9315// Fold the four `AplicacaoError::{EmptyWit, ContratoEndpointEmpty,
9316// ContratoSubjectEmpty, ContratoSlotEmpty} { de, para }` wire-up sites
9317// onto one substrate-primitive family per typed variant — the paired
9318// `{ de: String, para: String }` two-slot sibling on [`AplicacaoError`]
9319// of the peer four-slot [`contrato_target_ctors!`] (14b81d5,
9320// `{ de, para, wit, expected }` on `ContratoWrongTarget` /
9321// `ContratoMissingTarget`) and of the two-slot
9322// [`AplicacaoError::entrada_host_invalid`] (17dd504, `{ host, reason }`)
9323// on the sibling per-`:entrada :host` envelope. Every one of the four
9324// wire-up sites — three under [`WitContract::target`] (the empty
9325// [`WitTarget::Http`] `:endpoint`, empty [`WitTarget::PubSub`]
9326// `:subject`, empty [`WitTarget::Store`] `:slot`) and one under
9327// [`AplicacaoSpec::validate`] (the empty `:contratos :wit` field the
9328// value-shape gate fires ahead of) — opened the identical two-line
9329// `let (de, para) = <contract>.edge_pair(); return Err(
9330// AplicacaoError::<Variant> { de, para });` block against the local
9331// [`WitContract::edge_pair`] composite-projection accessor, the exact
9332// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE
9333// names as a bug, on the same altitude the peer [`contrato_target_ctors!`]
9334// and [`AplicacaoError::entrada_host_invalid`] each closed on their
9335// sibling envelopes.
9336//
9337// The macro below generates one `#[must_use]` inherent constructor per
9338// variant of shape `fn <ctor>(edge: (String, String)) -> AplicacaoError`,
9339// collapsing the four sites onto one dispatch per arm:
9340// `return Err(AplicacaoError::<ctor>(<contract>.edge_pair()));`, byte-
9341// equal to the pre-lift struct-literal on the same edge pair. The
9342// uniform two-field construction (`de, para` pair-destructure onto
9343// same-named fields) is spelled once — inside the macro — rather than
9344// at every wire-up site. `#[must_use]` fires a compile warning at any
9345// wire-up that mistakenly discards the constructed error.
9346//
9347// Every future consumer that wants to construct one of these four
9348// variants outside the two in-crate wire-up sites (a deferred
9349// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
9350// admission validator raising empty-payload / empty-`:wit` diagnostics,
9351// a future `feira validate --contratos` per-caixa admission verb, an
9352// M4 typed WIT-registry-driven per-arm pre-emitter probing the
9353// [`WitContract`] payload slot against a canonical per-arm requirement
9354// table) reaches the variant through one call rather than re-inlining
9355// the two-line pair-destructure block in lockstep with the four
9356// in-crate wire-up sites.
9357macro_rules! contrato_empty_pair_ctors {
9358    ($($ctor:ident => $variant:ident),* $(,)?) => {
9359        impl AplicacaoError {
9360            $(
9361                #[doc = concat!(
9362                    "Construct an [`AplicacaoError::",
9363                    stringify!($variant),
9364                    "`] naming the offending edge `(de, para)` pair. ",
9365                    "Folds the uniform `{ de, para }` two-slot struct-",
9366                    "literal onto one substrate primitive so every ",
9367                    "wire-up on this variant reads through one dispatch ",
9368                    "rather than the pre-lift two-line open-coded ",
9369                    "`let (de, para) = <contract>.edge_pair(); return ",
9370                    "Err(<Variant> { de, para });` block. The `edge` ",
9371                    "pair threads verbatim from [`WitContract::edge_pair`] ",
9372                    "at the call site."
9373                )]
9374                #[must_use]
9375                pub fn $ctor(edge: (String, String)) -> Self {
9376                    let (de, para) = edge;
9377                    Self::$variant { de, para }
9378                }
9379            )*
9380        }
9381    };
9382}
9383
9384contrato_empty_pair_ctors! {
9385    empty_wit => EmptyWit,
9386    contrato_endpoint_empty => ContratoEndpointEmpty,
9387    contrato_subject_empty => ContratoSubjectEmpty,
9388    contrato_slot_empty => ContratoSlotEmpty,
9389}
9390
9391// Fold the last open-coded `AplicacaoError::ContratoEndpointNotAbsolute
9392// { de, para, endpoint: <val>.to_string() }` three-slot struct-literal
9393// wire-up site at [`WitContract::target`]'s HTTP-arm leading-slash gate
9394// onto one substrate primitive on [`AplicacaoError`] — sibling on the
9395// `{ de: String, para: String, <field>: String }` three-slot envelope of
9396// the peer [`contrato_empty_pair_ctors!`] macro just above (8580068, four
9397// variants on the paired `{ de, para }` two-slot envelope carrying the
9398// same `let (de, para) = <contract>.edge_pair(); return Err(<Variant>
9399// { de, para });` pair-destructure prelude), the peer four-slot
9400// [`contrato_pair_value_reason_ctors!`] macro (14e13f1, four variants on
9401// the paired `{ de, para, <field>: String, reason: String }` envelope
9402// carrying the parser-shaped `reason` trailer), and the peer four-slot
9403// [`contrato_target_ctors!`] macro (14b81d5, two variants on the paired
9404// `{ de, para, wit, expected: &'static str }` envelope carrying the
9405// canonical target-field-name label). The `ContratoEndpointNotAbsolute`
9406// variant is the sole occupant of the three-slot `{ de, para, <field>:
9407// String }` shape on [`AplicacaoError`] (no sibling
9408// `ContratoSubjectNotAbsolute` / `ContratoSlotNotAbsolute` — the `:subject`
9409// and `:slot` axes carry no "must start with /" invariant, since the
9410// NATS subject grammar and the WASI keyvalue slot template grammar don't
9411// share the Gateway-API-HTTPPathMatch leading-slash prelude the
9412// `:endpoint` axis does), so a full macro isn't warranted; a single
9413// `#[must_use]` inherent ctor matching the ambient
9414// `fn <ctor>(edge: (String, String), <field>: &str) -> Self` shape the
9415// peer per-`:contratos` ctor families each carry closes the last
9416// open-coded three-slot struct-literal on the envelope, matching the
9417// same standalone-ctor discipline the sibling
9418// [`crate::LayoutError::missing_entry`] (1b09f9d, one variant on the
9419// `{ kind: &'static str, path: PathBuf }` two-slot envelope),
9420// [`crate::SupervisorError::child_caixa_invalid`] /
9421// [`::child_versao_invalid`] (d2ef2ec, two variants on the paired
9422// `{ caixa: String, [versao: String,] reason: String }` two- and three-
9423// slot envelopes), and [`AplicacaoError::entrada_host_invalid`] (17dd504,
9424// one variant on the `{ host: String, reason: String }` two-slot
9425// envelope) apply on their sibling one-off variants.
9426//
9427// The one wire-up site on this variant — [`WitContract::target`]'s
9428// HTTP-arm leading-slash gate at `if !ep.starts_with('/')`, one of the
9429// six per-`:contratos` value-shape gates inside the same method body,
9430// where the other five (`ContratoWrongTarget`, `ContratoMissingTarget`,
9431// `ContratoEndpointEmpty`, `ContratoEndpointInvalid`,
9432// `ContratoWitInvalid`) each already reach through one of the three
9433// peer macro-generated ctor families above — opened the same five-line
9434// `let (de, para) = self.edge_pair(); return
9435// Err(AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint:
9436// ep.to_string() });` struct-literal against the local
9437// [`WitContract::edge_pair`] composite-projection accessor and the
9438// caller-side `&str` endpoint — the exact "same block re-inlined at
9439// every consumer" shape the PRIME DIRECTIVE names as a bug, on the same
9440// altitude the six peer `AplicacaoError` constructor families each
9441// closed on their sibling envelopes. Every guarantee in MESH-COMPOSITION
9442// §III.3 (a `:contratos :endpoint` value that doesn't start with `/`
9443// becomes a caixa-build error, not a Cilium L7 policy-side path-match
9444// silent traffic drop far from the source caixa.lisp) now routes through
9445// one substrate primitive on the envelope.
9446//
9447// The ctor below folds the site onto one dispatch:
9448// `return Err(AplicacaoError::contrato_endpoint_not_absolute(
9449// self.edge_pair(), ep));`, byte-equal to the pre-lift struct-literal
9450// on the same `(edge_pair, endpoint)` pair. The uniform three-field
9451// construction (`de, para` pair-destructure onto same-named fields +
9452// `endpoint: endpoint.to_string()`) is spelled once — inside the ctor
9453// body — rather than at the wire-up site. `#[must_use]` fires a compile
9454// warning at any future wire-up that mistakenly discards the constructed
9455// error.
9456//
9457// Every future consumer that wants to construct this variant outside
9458// [`WitContract::target`] (a deferred `mesh.pleme.io/v1alpha1/Aplicacao`
9459// CR materializer's per-`:contratos` admission validator raising the
9460// leading-slash diagnostic on unrecognized `:endpoint` shapes, a future
9461// `feira validate --contratos` per-caixa admission verb re-running the
9462// leading-slash arm on demand, an M4 typed Cilium L7 rule pre-emitter
9463// probing each declared `:endpoint` against the same shared
9464// HTTPPathMatch grammar prelude, a per-tenant per-`Aplicacao` overlay
9465// resolver rejecting a leading-slash-missing `:endpoint` against a
9466// cluster-local Cilium snapshot the M4 CR materializer projects) now
9467// reaches this variant through one call rather than re-inlining the
9468// five-line pair-destructure + struct-literal block in lockstep with
9469// the sole in-crate wire-up site.
9470impl AplicacaoError {
9471    /// Construct an [`AplicacaoError::ContratoEndpointNotAbsolute`]
9472    /// naming the offending edge `(de, para)` pair and the per-payload
9473    /// `endpoint` value. Folds the uniform `{ de, para, endpoint:
9474    /// endpoint.to_string() }` three-slot struct-literal onto one
9475    /// substrate primitive so every wire-up on this variant reads
9476    /// through one dispatch rather than the pre-lift five-line
9477    /// pair-destructure + struct-literal block. The `edge` pair threads
9478    /// verbatim from [`WitContract::edge_pair`] at the call site,
9479    /// matching the sibling [`AplicacaoError::contrato_endpoint_empty`] /
9480    /// [`AplicacaoError::contrato_endpoint_invalid`] ctors' shape on the
9481    /// paired two-slot and four-slot per-`:contratos :endpoint`
9482    /// envelopes on the same [`AplicacaoError`] type.
9483    #[must_use]
9484    pub fn contrato_endpoint_not_absolute(edge: (String, String), endpoint: &str) -> Self {
9485        let (de, para) = edge;
9486        Self::ContratoEndpointNotAbsolute {
9487            de,
9488            para,
9489            endpoint: endpoint.to_string(),
9490        }
9491    }
9492
9493    /// Construct an [`AplicacaoError::ContratoSelfLoop`] naming the
9494    /// offending self-edge's owning `caixa` and its `:wit` world
9495    /// reference, projecting both slots through the [`WitContract`]'s
9496    /// own [`WitContract::source`] and [`WitContract::world_ref`]
9497    /// scalar accessors on the substrate primitive.
9498    ///
9499    /// Folds the uniform `{ caixa: contract.source().to_string(), wit:
9500    /// contract.world_ref().to_string() }` two-slot struct-literal onto
9501    /// one substrate primitive so every wire-up on this variant reads
9502    /// through one dispatch rather than the pre-lift four-line
9503    /// twin-`.to_string()` struct-literal block. The `contract` borrow
9504    /// threads verbatim from the caller-side `for c in
9505    /// self.contratos()` iteration at the sole in-crate wire-up site
9506    /// [`AplicacaoSpec::validate_contratos`], matching the sibling
9507    /// per-`:contratos` `WitContract`-projection ctor discipline the
9508    /// peer [`AplicacaoError::empty_wit`] /
9509    /// [`AplicacaoError::contrato_endpoint_empty`] /
9510    /// [`AplicacaoError::contrato_subject_empty`] /
9511    /// [`AplicacaoError::contrato_slot_empty`] ctors carry through
9512    /// [`WitContract::edge_pair`] on the sibling two-slot `{ de, para }`
9513    /// envelope.
9514    ///
9515    /// The `caixa` slot is projected through [`WitContract::source`]
9516    /// rather than [`WitContract::destination`] to preserve byte-equal
9517    /// diagnostic ordering with the pre-lift open-coded body — a
9518    /// [`WitContract::is_self_loop`]-gated call site has
9519    /// `source() == destination()` by that predicate's own contract, so
9520    /// the two accessors are exchange-symmetric at this call site, but
9521    /// naming `source` at the ctor definition matches the pre-lift
9522    /// site's field selection and pins the discipline for any future
9523    /// consumer that constructs the variant against a not-yet-gated
9524    /// candidate contract (e.g. an M4
9525    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
9526    /// webhook re-checking a per-`(:de, :para)` patched contract, a
9527    /// future `feira validate --contratos` per-caixa verb re-running
9528    /// the self-loop diagnostic on demand, a per-tenant per-Aplicacao
9529    /// overlay resolver rejecting a self-edge introduced by a
9530    /// cluster-local `:contratos` override the M4 CR materializer
9531    /// projects).
9532    ///
9533    /// Peer of the sibling `WitContract`-projection ctors on the
9534    /// per-`:contratos` envelopes on the same [`AplicacaoError`] type —
9535    /// same "one typed dispatch on the substrate primitive, projecting
9536    /// through the paired [`WitContract`] accessors, thin projections
9537    /// at each consumer" discipline extended here onto the last unlifted
9538    /// two-slot `{ caixa: String, wit: String }` per-self-edge envelope
9539    /// inside [`AplicacaoSpec::validate_contratos`].
9540    #[must_use]
9541    pub fn contrato_self_loop(contract: &WitContract) -> Self {
9542        Self::ContratoSelfLoop {
9543            caixa: contract.source().to_string(),
9544            wit: contract.world_ref().to_string(),
9545        }
9546    }
9547
9548    /// Construct an [`AplicacaoError::MembroVersaoInvalid`] naming the
9549    /// offending `:membros :caixa` and its `:versao` requirement under
9550    /// the given `reason`. Folds the uniform `Self::MembroVersaoInvalid {
9551    /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
9552    /// reason.into() }` three-slot struct-literal onto one substrate
9553    /// primitive so every wire-up on this variant reads through one
9554    /// dispatch, matching the peer
9555    /// [`crate::SupervisorError::child_versao_invalid`] (d2ef2ec) ctor's
9556    /// shape verbatim on the sibling `SupervisorError { caixa: String,
9557    /// versao: String, reason: String }` envelope's per-`:children :versao`
9558    /// axis. `reason` accepts both `&str` literals and `format!(…)`
9559    /// outputs through the `impl Into<String>` bound so the sole
9560    /// [`AplicacaoSpec::validate_membros`] wire-up's per-`:membros`
9561    /// requirement-cascade closure (routing the shared
9562    /// [`crate::render::require_valid_versao_requirement`]-delivered
9563    /// `reason` verbatim) picks the ctor up without a per-arm wrapper
9564    /// transformation on the caller-side `reason` axis. The
9565    /// [`Membro::nome`] / [`Membro::versao_requirement`] typed-accessor
9566    /// routing the sole wire-up already threads through remains verbatim
9567    /// — the ctor's two `&str` parameters accept the two accessors'
9568    /// returns as-is with no re-allocation at the call site.
9569    #[must_use]
9570    pub fn membro_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
9571        Self::MembroVersaoInvalid {
9572            caixa: caixa.to_string(),
9573            versao: versao.to_string(),
9574            reason: reason.into(),
9575        }
9576    }
9577
9578    /// Construct an [`AplicacaoError::PlacementClusterDuplicate`] naming
9579    /// the offending `:placement :clusters` entry.
9580    ///
9581    /// Folds the uniform `Self::PlacementClusterDuplicate { cluster:
9582    /// cluster.to_string() }` one-field struct-literal onto one substrate
9583    /// primitive so every wire-up on this variant reads through one
9584    /// dispatch rather than the pre-lift three-line open-coded
9585    /// struct-literal block. The `cluster` slot threads verbatim from the
9586    /// caller-side `for c in p.clusters()` iteration at the sole in-crate
9587    /// wire-up site [`AplicacaoSpec::validate_placement_shape`], via the
9588    /// per-entry dedup closure passed to
9589    /// [`crate::render::insert_first_seen`] whose `FnOnce`-shaped ctor
9590    /// bracket accepts the free function pointer as-is.
9591    ///
9592    /// Sibling of the per-`:membros :caixa` / per-`:entrada :paths` /
9593    /// per-`:politicas <scalar>` single-slot ctor families
9594    /// ([`aplicacao_caixa_only_ctors!`] on `{ caixa: String }` at the
9595    /// peer per-membership envelope, [`aplicacao_path_only_ctors!`] on
9596    /// `{ path: String }` at the peer per-gateway envelope,
9597    /// [`aplicacao_policy_scalar_ctors!`] on `{ <field>: Copy-scalar }`
9598    /// at the peer per-`:politicas` cap-scalar envelope) on the same
9599    /// [`AplicacaoError`] type — extends the "one typed dispatch per
9600    /// substrate primitive on every single-slot per-M3-slot envelope"
9601    /// discipline onto the last unlifted `{ cluster: String }` one-slot
9602    /// per-`:placement :clusters` dedup-envelope inside
9603    /// [`AplicacaoSpec::validate_placement_shape`].
9604    ///
9605    /// Every future consumer that wants to construct this variant outside
9606    /// [`AplicacaoSpec::validate_placement_shape`] — a deferred
9607    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
9608    /// webhook re-checking a `:placement :clusters` overlay against a
9609    /// per-tenant cluster-topology snapshot, a future `feira validate
9610    /// --placement` per-caixa admission verb re-running the dedup check
9611    /// on demand, an M4 per-cluster placement resolver rejecting a
9612    /// duplicate cluster-name entry introduced by a fleet-local overlay
9613    /// the M4 CR materializer projects — now reaches this variant through
9614    /// one call rather than re-inlining the three-line struct-literal.
9615    #[must_use]
9616    pub fn placement_cluster_duplicate(cluster: &str) -> Self {
9617        Self::PlacementClusterDuplicate {
9618            cluster: cluster.to_string(),
9619        }
9620    }
9621
9622    /// Construct an [`AplicacaoError::PlacementWithoutClusters`] naming
9623    /// the offending `:placement :estrategia` scalar the empty `:clusters`
9624    /// list was declared against, projecting through the paired
9625    /// [`Placement::estrategia`] `Copy`-scalar accessor on the substrate
9626    /// primitive.
9627    ///
9628    /// Folds the uniform `Self::PlacementWithoutClusters { estrategia:
9629    /// placement.estrategia() }` one-field struct-literal onto one
9630    /// substrate primitive so every wire-up on this variant reads through
9631    /// one dispatch rather than the pre-lift three-line open-coded
9632    /// `AplicacaoError::PlacementWithoutClusters { estrategia:
9633    /// p.estrategia() }` block inside
9634    /// [`AplicacaoSpec::validate_placement`]. Same substrate-primitive-
9635    /// projection posture as the sibling
9636    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting through
9637    /// [`WitContract::source`] / [`WitContract::world_ref`] on the paired
9638    /// per-`:contratos` self-edge envelope) and the peer
9639    /// [`crate::UpgradeError::duplicate_from`] (7e52aec, projecting through
9640    /// [`crate::UpgradeFromEntry::prior_versao`] on the sibling
9641    /// per-`:upgrade-from :from` envelope) ctors — extended here onto the
9642    /// last unlifted `{ estrategia: PlacementStrategy }` one-slot
9643    /// per-`:placement` empty-clusters envelope inside
9644    /// [`AplicacaoSpec::validate_placement`].
9645    ///
9646    /// `#[must_use]` and `const fn` alike: the ctor threads the paired
9647    /// [`Placement::estrategia`] `Copy`-scalar return through one
9648    /// zero-runtime-work construction — no allocation, no owned-string
9649    /// materialization — so the pre-lift `Copy`-pass-through property the
9650    /// open-coded `p.estrategia()` field expression carried survives
9651    /// verbatim through the substrate primitive. The sibling
9652    /// [`AplicacaoError::placement_cluster_duplicate`] (92b1c92) ctor
9653    /// carries the paired `.to_string()`-owned-String allocation on the
9654    /// `{ cluster: String }` envelope; this ctor's `Copy`-scalar envelope
9655    /// preserves the zero-alloc posture at the substrate-primitive
9656    /// dispatch, matching the peer
9657    /// [`aplicacao_policy_scalar_ctors!`] (7ef425e, eight variants on
9658    /// `{ <scalar>: Copy }`) family's `const fn` posture on the sibling
9659    /// per-`:politicas` cap-scalar envelopes.
9660    ///
9661    /// Every future consumer that wants to construct this variant outside
9662    /// [`AplicacaoSpec::validate_placement`] — a deferred
9663    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
9664    /// webhook re-checking a `:placement :clusters` overlay against a
9665    /// per-tenant cluster-topology snapshot when the overlay resolves to
9666    /// an empty list, a future `feira validate --placement` per-caixa
9667    /// admission verb re-running the empty-clusters check on demand, an
9668    /// M4 per-cluster placement resolver rejecting an empty cluster pool
9669    /// after a fleet-local overlay strips every declared cluster — now
9670    /// reaches this variant through one call rather than re-inlining the
9671    /// three-line struct-literal in lockstep with the one in-crate
9672    /// wire-up site.
9673    #[must_use]
9674    pub const fn placement_without_clusters(placement: &Placement) -> Self {
9675        Self::PlacementWithoutClusters {
9676            estrategia: placement.estrategia(),
9677        }
9678    }
9679
9680    /// Construct an [`AplicacaoError::ShardKeyOnNonSharded`] naming the
9681    /// offending `:placement :estrategia` scalar and the declared-but-
9682    /// inert `:shard-key` value the non-`Sharded` arm refused, projecting
9683    /// the strategy through the paired [`Placement::estrategia`]
9684    /// `Copy`-scalar accessor on the substrate primitive.
9685    ///
9686    /// Folds the uniform `Self::ShardKeyOnNonSharded { estrategia:
9687    /// placement.estrategia(), shard_key: shard_key.to_string() }`
9688    /// two-slot struct-literal onto one substrate primitive so every
9689    /// wire-up on this variant reads through one dispatch rather than
9690    /// the pre-lift four-line open-coded struct-literal block inside
9691    /// [`AplicacaoSpec::validate_placement`]'s
9692    /// `PlacementStrategy::Replicated | PlacementStrategy::SingleNode`
9693    /// arm. Same substrate-primitive-projection posture as the sibling
9694    /// [`AplicacaoError::placement_without_clusters`] (b0d24ba,
9695    /// projecting through [`Placement::estrategia`] on the peer
9696    /// `{ estrategia: PlacementStrategy }` one-slot per-`:placement`
9697    /// empty-clusters envelope) and the peer
9698    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting
9699    /// through [`WitContract::source`] / [`WitContract::world_ref`] on
9700    /// the paired per-`:contratos` self-edge envelope) ctors — extended
9701    /// here onto the last unlifted `{ estrategia: PlacementStrategy,
9702    /// shard_key: String }` two-slot per-`:placement :shard-key`
9703    /// declared-but-inert envelope on the sibling non-`Sharded`-arm
9704    /// partition.
9705    ///
9706    /// The `shard_key: &str` parameter accepts both the `Some(k)`-bound
9707    /// `&str` from the sole in-crate wire-up site (narrowed from
9708    /// `Option<&str>` via [`Placement::shard_key`]) and any future
9709    /// `&String` deref from a downstream consumer that reaches for the
9710    /// slot through the paired accessor, materializing the owned
9711    /// [`String`] via one `.to_string()` at the substrate primitive so
9712    /// no per-arm `.to_string()` allocation lives at the caller. The
9713    /// `estrategia` slot threads through [`Placement::estrategia`]'s
9714    /// `Copy`-scalar return rather than accepting a bare
9715    /// [`PlacementStrategy`] argument, matching the peer
9716    /// [`AplicacaoError::placement_without_clusters`] discipline —
9717    /// carrying the [`Placement`] borrow through one accessor call at
9718    /// the substrate primitive is strictly stronger than accepting the
9719    /// scalar as a separate argument (a future caller that constructs
9720    /// the error against a candidate [`Placement`] whose
9721    /// [`Placement::estrategia`] value the caller re-derives from
9722    /// another source can silently disagree with the storage the
9723    /// [`Placement`] carries; the accessor-projected primitive cannot).
9724    ///
9725    /// Peer of the sibling per-`:placement` single-slot / two-slot ctor
9726    /// families on the same [`AplicacaoError`] type — same "one typed
9727    /// dispatch on the substrate primitive, projecting through the
9728    /// paired [`Placement`] accessors, thin projections at each
9729    /// consumer" discipline extended here onto the last unlifted
9730    /// per-`:placement :shard-key` non-`Sharded`-arm envelope inside
9731    /// [`AplicacaoSpec::validate_placement`].
9732    ///
9733    /// Every future consumer that wants to construct this variant
9734    /// outside [`AplicacaoSpec::validate_placement`] — a deferred
9735    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
9736    /// webhook re-checking a `:placement (:estrategia Replicated
9737    /// :shard-key …)` overlay against a per-tenant cluster-topology
9738    /// snapshot, a future `feira validate --placement` per-caixa
9739    /// admission verb re-running the non-`Sharded`-arm refusal on
9740    /// demand, an M4 per-cluster placement resolver rejecting a
9741    /// declared-but-inert `:shard-key` introduced by a fleet-local
9742    /// overlay the M4 CR materializer projects — now reaches this
9743    /// variant through one call rather than re-inlining the four-line
9744    /// struct-literal in lockstep with the one in-crate wire-up site.
9745    #[must_use]
9746    pub fn shard_key_on_non_sharded(placement: &Placement, shard_key: &str) -> Self {
9747        Self::ShardKeyOnNonSharded {
9748            estrategia: placement.estrategia(),
9749            shard_key: shard_key.to_string(),
9750        }
9751    }
9752
9753    /// Construct an [`AplicacaoError::EntradaMemberMissing`] naming the
9754    /// offending `:entrada :para` value the membership lookup against the
9755    /// [`AplicacaoSpec::membro_names`] oracle refused, projecting the
9756    /// slot through the paired [`Entrada::destination`] byte-string
9757    /// accessor on the substrate primitive.
9758    ///
9759    /// Folds the uniform `Self::EntradaMemberMissing { para:
9760    /// entrada.destination().to_string() }` one-field struct-literal onto
9761    /// one substrate primitive so every wire-up on this variant reads
9762    /// through one dispatch rather than the pre-lift three-line
9763    /// open-coded `AplicacaoError::EntradaMemberMissing { para:
9764    /// e.destination().to_string() }` block inside
9765    /// [`AplicacaoSpec::validate_entrada`]. Same substrate-primitive-
9766    /// projection posture as the sibling
9767    /// [`AplicacaoError::placement_without_clusters`] (b0d24ba,
9768    /// projecting through [`Placement::estrategia`] on the peer
9769    /// `{ estrategia: PlacementStrategy }` one-slot per-`:placement`
9770    /// empty-clusters envelope) and the sibling
9771    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting
9772    /// through [`WitContract::source`] / [`WitContract::world_ref`] on
9773    /// the paired per-`:contratos` self-edge envelope) ctors — extended
9774    /// here onto the last unlifted `{ para: String }` one-slot
9775    /// per-`:entrada :para` phantom-reference envelope on the sibling
9776    /// per-`:entrada` slot.
9777    ///
9778    /// The `entrada: &Entrada` parameter threads verbatim from the
9779    /// caller-side `if let Some(e) = self.entrada() { … }` traversal at
9780    /// the sole in-crate wire-up site
9781    /// [`AplicacaoSpec::validate_entrada`], matching the sibling
9782    /// per-`:entrada` byte-string reads that already route through
9783    /// [`Entrada::destination`] one accessor call earlier in the same
9784    /// gate (`validate_entrada_para(e.destination())?;` +
9785    /// `if !names.contains(e.destination()) …`). Carrying the [`Entrada`]
9786    /// borrow through one accessor call at the substrate primitive is
9787    /// strictly stronger than accepting the bare `&str` as a separate
9788    /// argument — a future consumer that constructs the error against a
9789    /// candidate [`Entrada`] whose [`Entrada::destination`] value the
9790    /// caller re-derives from another source (a raw `e.para` field
9791    /// access that skipped the accessor, a stale snapshot of the
9792    /// pre-normalization storage) can silently disagree with the
9793    /// storage the [`Entrada`] carries; the accessor-projected primitive
9794    /// cannot. Matches the peer
9795    /// [`AplicacaoError::placement_without_clusters`] and
9796    /// [`AplicacaoError::shard_key_on_non_sharded`]
9797    /// [`Placement`]-borrow-projection discipline on the sibling
9798    /// per-`:placement` envelope, and matches the peer
9799    /// [`AplicacaoError::contrato_self_loop`] and
9800    /// [`AplicacaoError::contrato_endpoint_not_absolute`]
9801    /// [`WitContract`]-borrow-projection discipline on the sibling
9802    /// per-`:contratos` envelope.
9803    ///
9804    /// Every future consumer that wants to construct this variant
9805    /// outside [`AplicacaoSpec::validate_entrada`] — a deferred
9806    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
9807    /// webhook re-checking a `:entrada :para` overlay against a
9808    /// per-tenant `:membros` snapshot after a fleet-local overlay
9809    /// renames a member, a future `feira validate --entrada` per-caixa
9810    /// admission verb re-running the phantom-reference lookup on
9811    /// demand, an M4 per-cluster Gateway API pre-emitter rejecting a
9812    /// `:entrada :para` whose target Servico was stripped from the
9813    /// cluster-local `:membros` overlay, a future authoring-surface
9814    /// widening the field into a `(String, Vec<Suggestion>)` pair
9815    /// carrying a "did-you-mean-<nearest-member>" hint — now reaches
9816    /// this variant through one call rather than re-inlining the
9817    /// three-line struct-literal in lockstep with the one in-crate
9818    /// wire-up site.
9819    #[must_use]
9820    pub fn entrada_member_missing(entrada: &Entrada) -> Self {
9821        Self::EntradaMemberMissing {
9822            para: entrada.destination().to_string(),
9823        }
9824    }
9825
9826    /// Construct an [`AplicacaoError::ContratoCycle`] naming the
9827    /// synchronous-`:contratos` cycle path the DFS-with-three-coloring
9828    /// sync-only-subgraph gate at
9829    /// [`AplicacaoSpec::detect_sync_cycles`] reconstructed from the
9830    /// gray-arm's back-edge target through the parent chain, folding the
9831    /// uniform `Self::ContratoCycle { cycle }` one-field struct-literal
9832    /// onto one substrate primitive so every wire-up on this variant
9833    /// reads through one dispatch rather than the pre-lift open-coded
9834    /// `AplicacaoError::ContratoCycle { cycle }` block at the sole
9835    /// in-crate wire-up site inside
9836    /// [`AplicacaoSpec::detect_sync_cycles`]'s gray-arm cycle-close
9837    /// return. Same substrate-primitive-projection posture as the
9838    /// sibling [`AplicacaoError::entrada_member_missing`] (deeae5c,
9839    /// projecting through [`Entrada::destination`] on the peer `{ para:
9840    /// String }` one-slot per-`:entrada :para` phantom-reference
9841    /// envelope) and [`AplicacaoError::placement_without_clusters`]
9842    /// (b0d24ba, projecting through [`Placement::estrategia`] on the
9843    /// sibling `{ estrategia: PlacementStrategy }` one-slot
9844    /// per-`:placement` empty-clusters envelope) ctors — extended here
9845    /// onto the last unlifted `{ cycle: Vec<String> }` one-slot
9846    /// per-`:contratos` cross-edge sync-cycle envelope on the same
9847    /// [`AplicacaoError`] type. Closes the last unlifted `AplicacaoError`
9848    /// struct-literal wire-up under
9849    /// [`AplicacaoSpec::detect_sync_cycles`].
9850    ///
9851    /// The `cycle: Vec<String>` parameter threads verbatim from the
9852    /// caller-side DFS traversal's reconstructed cycle path (built up by
9853    /// walking `parent` from the gray-back-edge's source node back to
9854    /// its target, reversing, then appending the target once more so the
9855    /// first and last elements coincide by construction and the
9856    /// `Display` rendering under the [`AplicacaoError::ContratoCycle`]
9857    /// `cycle.join(" → ")` formatter reads as a closed loop), matching
9858    /// the pre-lift open-coded body's field selection exactly. Taking
9859    /// the owned [`Vec<String>`] rather than a borrowed slice + collect
9860    /// on the ctor side keeps the pre-lift wire-up byte-identical (the
9861    /// caller already owns the reconstructed [`Vec<String>`] at the
9862    /// gray-arm return, so no per-arm re-allocation lands on the ctor
9863    /// path).
9864    ///
9865    /// Peer of the sibling per-`:contratos` single-slot / two-slot ctor
9866    /// families on the same [`AplicacaoError`] type — same "one typed
9867    /// dispatch on the substrate primitive, thin projections at each
9868    /// consumer" discipline extended here onto the last unlifted
9869    /// per-`:contratos` cross-edge cycle envelope inside
9870    /// [`AplicacaoSpec::detect_sync_cycles`].
9871    ///
9872    /// Every future consumer that wants to construct this variant
9873    /// outside [`AplicacaoSpec::detect_sync_cycles`] — a deferred
9874    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
9875    /// webhook re-checking a per-tenant `:contratos` overlay's
9876    /// sync-cycle invariant after a fleet-local overlay adds or removes
9877    /// a synchronous edge, a future `feira validate --contratos`
9878    /// per-caixa admission verb re-running the cross-edge cycle detector
9879    /// on demand, the M4 per-edge policy resolver MESH-COMPOSITION §III.2
9880    /// #3 acknowledges (whose per-edge patch mutates one `:contratos`
9881    /// entry and needs to re-probe *just* the cycle invariant against
9882    /// the post-patch adjacency), a future authoring-surface widening
9883    /// the field into a `(Vec<String>, Vec<WitTarget>)` pair carrying
9884    /// the per-hop WIT shape for a richer "break here" hint — now
9885    /// reaches this variant through one call rather than re-inlining the
9886    /// open-coded struct-literal in lockstep with the one in-crate
9887    /// wire-up site.
9888    #[must_use]
9889    pub fn contrato_cycle(cycle: Vec<String>) -> Self {
9890        Self::ContratoCycle { cycle }
9891    }
9892}
9893
9894// Fold the seven `AplicacaoError::{MembroCaixa, EntradaPara, EntradaHost,
9895// EntradaPath, PlacementCluster, PlacementAffinity, ShardKey}Invalid
9896// { <field>: <val>.to_string(), reason: <expr> }` wire-up sites onto one
9897// substrate-primitive family per typed variant — the paired
9898// `{ <field>: String, reason: String }` two-slot sibling on
9899// [`AplicacaoError`] of the peer four-slot [`contrato_target_ctors!`]
9900// (14b81d5, `{ de, para, wit, expected }` on `ContratoWrongTarget` /
9901// `ContratoMissingTarget`) and the peer two-slot
9902// [`contrato_empty_pair_ctors!`] (8580068, `{ de, para }` on `EmptyWit` /
9903// `ContratoEndpointEmpty` / `ContratoSubjectEmpty` / `ContratoSlotEmpty`)
9904// on the sibling per-`:contratos` envelopes, plus the peer four-family
9905// `LayoutError` ctor set ([`layout_violation_ctors!`] 131ca0d — 16
9906// variants on `{ caixa, issue }`, [`layout_slot_kind_ctors!`] 0419438 —
9907// 4 variants on `{ caixa, kind, slots }`, [`LayoutError::missing_entry`]
9908// 1b09f9d — 1 variant on `{ kind, path }`, [`layout_nome_only_ctors!`]
9909// 3fe3dd7 — 6 variants on `<Variant>(String)`) each carry on the
9910// sibling layout-side envelope.
9911//
9912// Every one of the seven wire-up sites — six under the per-axis
9913// `validate_*` wrappers around [`crate::render::require_valid_dns_1123_label`]
9914// (`validate_membro_caixa` on `MembroCaixaInvalid`, `validate_entrada_para`
9915// on `EntradaParaInvalid`, `validate_placement_cluster` on
9916// `PlacementClusterInvalid`, `validate_placement_affinity` on
9917// `PlacementAffinityInvalid`) plus [`crate::render::is_gateway_api_http_path`]
9918// (`validate_entrada_path` on `EntradaPathInvalid`), and two under
9919// [`validate_placement_shard_key`] (the length-cap arm and the per-byte
9920// printable-ASCII arm on `ShardKeyInvalid`) — plus the fourteen wire-up
9921// sites at [`validate_entrada_host`] (17dd504 already folded onto the
9922// pre-macro standalone `entrada_host_invalid` ctor, now converged onto
9923// the macro-generated ctor of the same name), opened the identical
9924// four-line `AplicacaoError::<Variant>Invalid
9925// { <field>: <val>.to_string(), reason: <expr> }` struct-literal against
9926// the local `<field>: &str` argument — the exact "same block re-inlined
9927// at every consumer" shape the PRIME DIRECTIVE names as a bug, on the
9928// same altitude the peer three `AplicacaoError` constructor families
9929// and the four peer `LayoutError` constructor families each closed on
9930// their sibling envelopes.
9931//
9932// The macro below generates one `#[must_use]` inherent constructor per
9933// variant of shape `fn <ctor>(<field>: &str, reason: impl Into<String>)
9934// -> AplicacaoError`, collapsing every site onto one dispatch per arm:
9935// `return Err(AplicacaoError::<ctor>(<val>, <reason>));` /
9936// `|reason| AplicacaoError::<ctor>(<val>, reason)`, byte-equal to the
9937// pre-lift struct-literal on the same `(<field>, reason)` pair. The
9938// uniform two-field construction (`<field>: <val>.to_string()`,
9939// `reason: reason.into()`) is spelled once — inside the macro — rather
9940// than at every wire-up site. The `reason: impl Into<String>` bound
9941// accepts both `&str` literals (with or without a trailing
9942// `.to_string()` at the caller) and `format!(…)` outputs verbatim so no
9943// wire-up site changes its per-arm diagnostic shape at the lift.
9944// `#[must_use]` fires a compile warning at any wire-up that mistakenly
9945// discards the constructed error rather than routing it through
9946// `return Err(…)` / `.map_err(…)` / a closure return.
9947//
9948// Every future consumer that wants to construct one of these seven
9949// variants outside the current in-crate wire-up sites (the deferred
9950// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-slot
9951// admission validators, a future `feira validate --<axis>` per-caixa
9952// admission verb, a per-`Certificate` SAN pre-emitter for cert-manager
9953// on `:entrada :host`, an M4 typed placement-engine per-cluster /
9954// per-affinity / per-shard-key pre-emitter, an M4 typed Gateway API
9955// per-path pre-emitter) reaches the variant through one call rather
9956// than re-inlining the four-line struct-literal block in lockstep with
9957// the current in-crate wire-up sites.
9958macro_rules! aplicacao_field_reason_ctors {
9959    ($($ctor:ident => $variant:ident { $field:ident }),* $(,)?) => {
9960        impl AplicacaoError {
9961            $(
9962                #[doc = concat!(
9963                    "Construct an [`AplicacaoError::",
9964                    stringify!($variant),
9965                    "`] naming the offending `",
9966                    stringify!($field),
9967                    "` under the given `reason`. Folds the uniform ",
9968                    "`{ ",
9969                    stringify!($field),
9970                    ": ",
9971                    stringify!($field),
9972                    ".to_string(), reason: reason.into() }` two-slot ",
9973                    "construction onto one substrate primitive so every ",
9974                    "wire-up on this variant reads through one dispatch ",
9975                    "rather than the pre-lift four-line struct-literal ",
9976                    "block. `reason` accepts both `&str` literals and ",
9977                    "`format!(…)` outputs through the `impl Into<String>` ",
9978                    "bound."
9979                )]
9980                #[must_use]
9981                pub fn $ctor($field: &str, reason: impl Into<String>) -> Self {
9982                    Self::$variant {
9983                        $field: $field.to_string(),
9984                        reason: reason.into(),
9985                    }
9986                }
9987            )*
9988        }
9989    };
9990}
9991
9992aplicacao_field_reason_ctors! {
9993    membro_caixa_invalid => MembroCaixaInvalid { caixa },
9994    entrada_para_invalid => EntradaParaInvalid { para },
9995    entrada_host_invalid => EntradaHostInvalid { host },
9996    entrada_path_invalid => EntradaPathInvalid { path },
9997    placement_cluster_invalid => PlacementClusterInvalid { cluster },
9998    placement_affinity_invalid => PlacementAffinityInvalid { affinity },
9999    shard_key_invalid => ShardKeyInvalid { shard_key },
10000}
10001
10002// Fold the four `AplicacaoError::Contrato{Endpoint,Subject,Slot,Wit}Invalid
10003// { de, para, <field>: <val>.to_string(), reason }` wire-up sites at
10004// [`WitContract::target`] onto one substrate-primitive family per typed
10005// variant — the paired `{ de: String, para: String, <field>: String,
10006// reason: String }` four-slot sibling on [`AplicacaoError`] of the peer
10007// four-slot [`contrato_target_ctors!`] (14b81d5, `{ de, para, wit,
10008// expected }` on `ContratoWrongTarget` / `ContratoMissingTarget`), the
10009// peer two-slot [`contrato_empty_pair_ctors!`] (8580068, `{ de, para }`
10010// on `EmptyWit` / `ContratoEndpointEmpty` / `ContratoSubjectEmpty` /
10011// `ContratoSlotEmpty`), and the peer two-slot
10012// [`aplicacao_field_reason_ctors!`] (981060b, `{ <field>: String,
10013// reason: String }` on `MembroCaixaInvalid` / `EntradaParaInvalid` /
10014// `EntradaHostInvalid` / `EntradaPathInvalid` / `PlacementClusterInvalid`
10015// / `PlacementAffinityInvalid` / `ShardKeyInvalid`) each carry on the
10016// sibling `AplicacaoError` envelopes, plus the peer four-family
10017// `LayoutError` ctor set on the sibling layout-side envelope.
10018//
10019// Every one of the four wire-up sites — four per-`:contratos` value-
10020// shape gates inside [`WitContract::target`] (the world-ref prefix
10021// [`crate::render::is_wit_world_ref`] failure on `:wit`, the HTTP arm's
10022// [`crate::render::is_gateway_api_http_path`] failure on `:endpoint`,
10023// the pub-sub arm's [`crate::render::is_nats_subject`] failure on
10024// `:subject`, the store arm's [`crate::render::is_wasi_keyvalue_slot`]
10025// failure on `:slot`) — opened the identical five-line
10026// `let (de, para) = self.edge_pair();
10027// return Err(AplicacaoError::Contrato<Field>Invalid { de, para,
10028// <field>: <val>.to_string(), reason });` block against the local
10029// [`WitContract::edge_pair`] composite-projection accessor and the
10030// per-arm `<val>: &str` argument — the exact "same block re-inlined at
10031// every consumer" shape the PRIME DIRECTIVE names as a bug, on the same
10032// altitude the peer three `AplicacaoError` constructor families and the
10033// four peer `LayoutError` constructor families each closed on their
10034// sibling envelopes. Absorbing `ContratoWitInvalid` onto the same
10035// macro closes the last unlifted `{ de, para, <field>: String, reason:
10036// String }` four-slot envelope inside `impl WitContract`, so every
10037// per-`:contratos` value-shape diagnostic on [`AplicacaoError`] now
10038// reads through this one substrate primitive.
10039//
10040// The macro below generates one `#[must_use]` inherent constructor per
10041// variant of shape `fn <ctor>(edge: (String, String), <field>: &str,
10042// reason: impl Into<String>) -> AplicacaoError`, collapsing the four
10043// sites onto one dispatch per arm:
10044// `return Err(AplicacaoError::<ctor>(self.edge_pair(), <val>, reason));`,
10045// byte-equal to the pre-lift struct-literal on the same
10046// `(edge_pair, <val>, reason)` triple. The uniform four-field
10047// construction (`de, para` pair-destructure onto same-named fields +
10048// `<field>: <val>.to_string()` + `reason: reason.into()`) is spelled
10049// once — inside the macro — rather than at every wire-up site. The
10050// `reason: impl Into<String>` bound accepts both `&str` literals and
10051// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
10052// diagnostic shape at the lift, matching the peer
10053// [`aplicacao_field_reason_ctors!`] bound on the sibling two-slot
10054// envelope. `#[must_use]` fires a compile warning at any wire-up that
10055// mistakenly discards the constructed error.
10056//
10057// Every future consumer that wants to construct one of these four
10058// variants outside [`WitContract::target`] (a deferred
10059// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
10060// admission validator raising per-payload value-shape diagnostics on
10061// unrecognized `:wit` / `:endpoint` / `:subject` / `:slot` shapes, a
10062// future `feira validate --contratos` per-caixa admission verb, an M4
10063// typed WIT-registry-driven per-arm pre-emitter probing each declared
10064// `:endpoint` / `:subject` / `:slot` payload against a canonical
10065// per-arm shape gate, a per-`Certificate` SAN pre-emitter for
10066// cert-manager on the `:endpoint` axis, an M4 typed Cilium L7 rule
10067// pre-emitter probing each `:endpoint` against the same shared
10068// HTTPPathMatch grammar) reaches the variant through one call rather
10069// than re-inlining the five-line pair-destructure + struct-literal
10070// block in lockstep with the four in-crate wire-up sites.
10071macro_rules! contrato_pair_value_reason_ctors {
10072    ($($ctor:ident => $variant:ident { $field:ident }),* $(,)?) => {
10073        impl AplicacaoError {
10074            $(
10075                #[doc = concat!(
10076                    "Construct an [`AplicacaoError::",
10077                    stringify!($variant),
10078                    "`] naming the offending edge `(de, para)` pair, the ",
10079                    "per-payload `",
10080                    stringify!($field),
10081                    "` value, and the parser-shaped `reason`. Folds the ",
10082                    "uniform `{ de, para, ",
10083                    stringify!($field),
10084                    ": ",
10085                    stringify!($field),
10086                    ".to_string(), reason: reason.into() }` four-slot ",
10087                    "construction onto one substrate primitive so every ",
10088                    "wire-up on this variant reads through one dispatch ",
10089                    "rather than the pre-lift five-line pair-destructure ",
10090                    "+ struct-literal block. The `edge` pair threads ",
10091                    "verbatim from [`WitContract::edge_pair`] at the ",
10092                    "call site; `reason` accepts both `&str` literals ",
10093                    "and `format!(…)` outputs through the `impl ",
10094                    "Into<String>` bound."
10095                )]
10096                #[must_use]
10097                pub fn $ctor(edge: (String, String), $field: &str, reason: impl Into<String>) -> Self {
10098                    let (de, para) = edge;
10099                    Self::$variant {
10100                        de,
10101                        para,
10102                        $field: $field.to_string(),
10103                        reason: reason.into(),
10104                    }
10105                }
10106            )*
10107        }
10108    };
10109}
10110
10111contrato_pair_value_reason_ctors! {
10112    contrato_endpoint_invalid => ContratoEndpointInvalid { endpoint },
10113    contrato_subject_invalid => ContratoSubjectInvalid { subject },
10114    contrato_slot_invalid => ContratoSlotInvalid { slot },
10115    contrato_wit_invalid => ContratoWitInvalid { wit },
10116}
10117
10118// Fold the five `AplicacaoError::{ContratoMemberMissing, MembroVersaoEmpty,
10119// MembroDuplicate, MembroIsSelfAplicacao} { caixa: <&str>.to_string() }`
10120// caixa-only struct-variant wire-up sites at
10121// [`WitContract::require_endpoints_in`] (two sites, the `:contratos :de` and
10122// `:contratos :para` arms of `ContratoMemberMissing`),
10123// [`AplicacaoSpec::validate_membros`] (two sites, the empty-`:versao` arm of
10124// `MembroVersaoEmpty` and the per-`:membros` dedup arm of `MembroDuplicate`),
10125// and [`validate_no_self_membership`] (one site, the parent-`:nome`
10126// self-membership arm of `MembroIsSelfAplicacao`) onto one substrate primitive
10127// per typed variant — the sibling on the M3 mesh `AplicacaoError` envelope of
10128// the peer [`crate::supervisor::supervisor_caixa_only_ctors!`] macro (db09650,
10129// three variants on `{ caixa: String }` at
10130// [`crate::SupervisorSpec::validate_children`] and
10131// [`crate::supervisor::validate_no_self_supervision`]) on the sibling M2
10132// `SupervisorError` envelope, extending the same "one substrate primitive per
10133// typed variant on the single-slot `{ <ident>: String }` envelope shape" fold
10134// discipline onto the M3 mesh side. Peers on peer envelopes: the M2 sibling
10135// [`crate::behavior::behavior_slot_path_ctors!`] (67c31ec, 3 variants on
10136// `{ slot: &'static str, path: PathBuf }`) two-slot fold on the `:behavior`
10137// envelope; the M2 sibling [`crate::upgrade::upgrade_from_script_ctors!`]
10138// (8e67041, 3 variants on `{ from: String, script: PathBuf }`) and
10139// [`crate::upgrade::upgrade_script_only_ctors!`] (7468ca9, 3 variants on
10140// `{ script: PathBuf }`) two folds on the sibling `:upgrade-from` envelope;
10141// the sibling [`crate::dep::dep_nome_only_ctors!`] (792aa92, 5 variants on
10142// `{ nome: String }`), [`crate::dep::fonte_caminho_ctors!`] (f85f145, 11
10143// variants on `{ nome, caminho }`), and
10144// [`crate::dep::fonte_caminho_byte_ctors!`] (0e35793, 12 variants on
10145// `{ nome, caminho, byte }`) folds on the sibling `DepError` envelope; the
10146// peer three `AplicacaoError` sub-family folds already lifted here
10147// ([`contrato_target_ctors!`] 14b81d5, [`contrato_empty_pair_ctors!`] 8580068,
10148// [`aplicacao_field_reason_ctors!`] 981060b,
10149// [`contrato_pair_value_reason_ctors!`] 14e13f1); the peer four `LayoutError`
10150// families ([`crate::layout::layout_violation_ctors!`] 131ca0d,
10151// [`crate::layout::layout_slot_kind_ctors!`] 0419438,
10152// [`crate::LayoutError::missing_entry`] 1b09f9d,
10153// [`crate::layout::layout_nome_only_ctors!`] 3fe3dd7); and the three
10154// [`crate::limits::limits_codec_value_*_ctors!`] codec families (81c856c).
10155//
10156// Each of the five wire-up sites on this shape (two on `ContratoMemberMissing`
10157// at the per-`:contratos :de`/`:para` unknown-member arms, one on
10158// `MembroVersaoEmpty` at the per-`:membros` empty-semver-requirement arm, one
10159// on `MembroDuplicate` at the per-`:membros` dedup arm, one on
10160// `MembroIsSelfAplicacao` at the parent-`:nome` self-membership arm) opened
10161// the identical `AplicacaoError::<Variant> { caixa: <&str>.to_string() }`
10162// three-line struct-literal against a caller-side `&str` — the exact "same
10163// block re-inlined at every consumer" shape the PRIME DIRECTIVE names as a
10164// bug, on the same altitude the peer `SupervisorError` /
10165// `AplicacaoError` (three prior sub-families) / `DepError` / `LayoutError` /
10166// `UpgradeError` / `BehaviorError` / `LimitsError` families each closed on
10167// their sibling envelopes. The four variants share one `{ caixa: String }`
10168// shape, so the fold routes each wire-up site through one dispatch per typed
10169// variant.
10170//
10171// The macro below generates one `#[must_use]` inherent constructor per
10172// variant of shape `fn <ctor>(caixa: &str) -> AplicacaoError`, so every
10173// wire-up site collapses onto one dispatch:
10174// `AplicacaoError::<ctor>(<&str>)`, byte-equal to the pre-lift struct-literal
10175// on the same `&str` fixture. The uniform one-field construction
10176// (`caixa: caixa.to_string()`) is spelled once — inside the macro — rather
10177// than at every wire-up site. Every constructor is `#[must_use]` so a caller
10178// who mistakenly discards the constructed error trips a compile warning at
10179// the wire-up site.
10180//
10181// Every future consumer that wants to construct one of these four variants
10182// outside the current in-crate wire-up sites — a deferred
10183// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook
10184// re-checking one added/renamed `:membros` entry against the sibling
10185// `:contratos` graph, a future `feira validate --membros` per-caixa admission
10186// verb re-checking each declared `:membros` entry's `:caixa` name against the
10187// same axes, a per-tenant per-`Aplicacao` overlay resolver rejecting a
10188// duplicate / self-referencing / unknown-membered `:contratos` entry against
10189// a cluster-local snapshot the M4 CR materializer projects — now reaches each
10190// variant through one call rather than re-inlining the three-line
10191// struct-literal in lockstep with the five in-crate wire-up sites.
10192macro_rules! aplicacao_caixa_only_ctors {
10193    ($($ctor:ident => $variant:ident),* $(,)?) => {
10194        impl AplicacaoError {
10195            $(
10196                #[doc = concat!(
10197                    "Construct an [`AplicacaoError::",
10198                    stringify!($variant),
10199                    "`] naming the offending `:membros :caixa` (or ",
10200                    "parent `:nome`, on the self-membership arm; or ",
10201                    "`:contratos :de`/`:para`, on the unknown-member ",
10202                    "arm). Folds the uniform `Self::",
10203                    stringify!($variant),
10204                    " { caixa: caixa.to_string() }` one-field ",
10205                    "struct-literal onto one substrate primitive so ",
10206                    "every wire-up on this variant reads through one ",
10207                    "dispatch rather than the pre-lift three-line ",
10208                    "open-coded struct-literal block."
10209                )]
10210                #[must_use]
10211                pub fn $ctor(caixa: &str) -> Self {
10212                    Self::$variant { caixa: caixa.to_string() }
10213                }
10214            )*
10215        }
10216    };
10217}
10218
10219aplicacao_caixa_only_ctors! {
10220    contrato_member_missing => ContratoMemberMissing,
10221    membro_versao_empty => MembroVersaoEmpty,
10222    membro_duplicate => MembroDuplicate,
10223    membro_is_self_aplicacao => MembroIsSelfAplicacao,
10224}
10225
10226// Fold the three `AplicacaoError::{EntradaPathNotAbsolute,
10227// EntradaPathDuplicate} { path: <val>.to_string() | <val>.clone() }` wire-up
10228// sites onto one substrate-primitive family per typed variant — the direct
10229// per-`:entrada :paths` value-shape sibling of the peer
10230// `aplicacao_caixa_only_ctors!` (d9f6867, `{ caixa: String }` on
10231// `ContratoMemberMissing` / `MembroVersaoEmpty` / `MembroDuplicate` /
10232// `MembroIsSelfAplicacao`) on the sibling per-`:membros :caixa` envelope, and
10233// per-`:entrada :para` sibling of the peer `contrato_empty_pair_ctors!`
10234// (8580068, `{ de, para }` on `EmptyWit` / `ContratoEndpointEmpty` /
10235// `ContratoSubjectEmpty` / `ContratoSlotEmpty`) on the per-`:contratos` edge
10236// envelope. Same shape family as the [`crate::dep::dep_nome_only_ctors!`]
10237// (792aa92, `{ nome: String }` on five `DepError` variants) fold on the peer
10238// `:deps` envelope — every single-`String`-slot error family in caixa-core
10239// now reaches through one substrate primitive per typed variant.
10240//
10241// The three wire-up sites — one under [`validate_entrada_path`]'s
10242// leading-slash grammar arm (`EntradaPathNotAbsolute` against
10243// `path: &str`), one under the per-`:entrada :paths` loop's identical
10244// arm (`EntradaPathNotAbsolute` against a `&String` head via `.clone()`),
10245// and one under the per-`:entrada :paths` loop's dedup arm
10246// (`EntradaPathDuplicate` against the same `&String` via
10247// [`crate::render::insert_first_seen`]'s ctor closure) — opened the identical
10248// `AplicacaoError::EntradaPath<Variant> { path: <val>.to_string() | .clone() }`
10249// three-line struct-literal against a caller-side `&str` / `&String`, the
10250// exact "same block re-inlined at every consumer" shape the PRIME DIRECTIVE
10251// names as a bug. Every one of the compile-time guarantees in
10252// MESH-COMPOSITION.md §III.3 (a `:entrada :paths` entry whose value doesn't
10253// start with `/` becomes a caixa-build error, not a Gateway API webhook
10254// rejection at `kubectl apply` time; a duplicated `:entrada :paths` entry
10255// becomes a caixa-build error, not a silent last-writer-wins render) now
10256// routes through one dispatch per typed variant at every emit site.
10257//
10258// The macro below generates one `#[must_use]` inherent constructor per
10259// variant of shape `fn <ctor>(path: &str) -> AplicacaoError`, collapsing
10260// every wire-up site onto one dispatch:
10261// `AplicacaoError::<ctor>(<path>)` (byte-equal to the pre-lift struct-literal
10262// on the same `&str` fixture) or the `&String` sites through
10263// `p.as_str()` (byte-equal on the same slice-view). The uniform one-field
10264// construction (`path: path.to_string()`) is spelled once — inside the
10265// macro — rather than at every wire-up site. Every ctor is `#[must_use]` so
10266// a caller who mistakenly discards the constructed error trips a compile
10267// warning at the wire-up site.
10268//
10269// Every future consumer that wants to construct one of these two variants
10270// outside the current in-crate wire-up sites — a deferred
10271// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook
10272// per-`:entrada :paths` re-check against a cluster-local Gateway API
10273// snapshot, a future `feira validate --entrada` per-caixa admission verb
10274// re-checking each declared `:paths` entry against the same axes, a
10275// per-tenant per-`Aplicacao` overlay resolver rejecting a
10276// duplicate / non-absolute `:paths` entry against a cluster-local Gateway
10277// snapshot the M4 CR materializer projects — now reaches each variant
10278// through one call rather than re-inlining the three-line struct-literal in
10279// lockstep with the three in-crate wire-up sites.
10280macro_rules! aplicacao_path_only_ctors {
10281    ($($ctor:ident => $variant:ident),* $(,)?) => {
10282        impl AplicacaoError {
10283            $(
10284                #[doc = concat!(
10285                    "Construct an [`AplicacaoError::",
10286                    stringify!($variant),
10287                    "`] naming the offending `:entrada :paths` entry. ",
10288                    "Folds the uniform `Self::",
10289                    stringify!($variant),
10290                    " { path: path.to_string() }` one-field ",
10291                    "struct-literal onto one substrate primitive so ",
10292                    "every wire-up on this variant reads through one ",
10293                    "dispatch rather than the pre-lift three-line ",
10294                    "open-coded struct-literal block."
10295                )]
10296                #[must_use]
10297                pub fn $ctor(path: &str) -> Self {
10298                    Self::$variant { path: path.to_string() }
10299                }
10300            )*
10301        }
10302    };
10303}
10304
10305aplicacao_path_only_ctors! {
10306    entrada_path_not_absolute => EntradaPathNotAbsolute,
10307    entrada_path_duplicate => EntradaPathDuplicate,
10308}
10309
10310// Fold the eight `AplicacaoError::Policy<Slot><Axis> { <field>: <val> }`
10311// one-slot `Copy`-scalar wire-up sites at [`MeshPolicy::validate`] onto one
10312// substrate-primitive family per typed variant — the per-`:politicas` copy-
10313// scalar `{ timeout | retries | max_failures | window | rate: Duration | u32 }`
10314// sibling of the peer per-`:membros :caixa` [`aplicacao_caixa_only_ctors!`]
10315// (d9f6867, `{ caixa: String }` on `ContratoMemberMissing` /
10316// `MembroVersaoEmpty` / `MembroDuplicate` / `MembroIsSelfAplicacao`) and the
10317// peer per-`:entrada :paths` [`aplicacao_path_only_ctors!`] (3ba8de6,
10318// `{ path: String }` on `EntradaPathNotAbsolute` / `EntradaPathDuplicate`) on
10319// the `String`-slot axis, and the peer per-`:politicas` cross-axis
10320// [`AplicacaoError::Policy*`] cascade [`MeshPolicy::first_cross_axis_violation`]
10321// carries at line 3064 on the same M3 mesh envelope.
10322//
10323// The eight wire-up sites inside [`MeshPolicy::validate`] at lines 3170-3218
10324// each opened the identical `|<slot>| AplicacaoError::Policy<Slot><Axis>
10325// { <slot> }` one-line struct-literal closure against the caller-side
10326// `<slot>: <ty>` argument that the shared
10327// [`crate::render::require_positive_bounded_u32`] /
10328// [`crate::render::require_positive_canonical_bounded_duration`] gate rebinds
10329// verbatim under the `impl FnOnce(u32) -> AplicacaoError` /
10330// `impl FnOnce(Duration) -> AplicacaoError` bracket-closure slots (plus one
10331// direct `return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical
10332// { window: rl.window() })` at the `:rate-limit :window` canonical-form arm
10333// on line 3211) — the exact "same one-line struct-literal re-inlined at every
10334// consumer" shape the PRIME DIRECTIVE names as a bug, on the last remaining
10335// per-`:politicas` per-axis `AplicacaoError` variant family that had not yet
10336// been folded onto a substrate primitive.
10337//
10338// The macro below generates one `#[must_use] pub const fn <ctor>(<field>: <ty>)
10339// -> AplicacaoError` per variant of shape `Self::<variant> { <field> }`,
10340// collapsing every wire-up onto either one direct dispatch
10341// (`return Err(AplicacaoError::<ctor>(<val>))`, byte-equal to the pre-lift
10342// struct-literal on the same `Copy`-`<ty>` fixture) or one bare function
10343// pointer at the `impl FnOnce(<ty>) -> AplicacaoError` bracket-closure slot
10344// (`AplicacaoError::<ctor>` in the position where every pre-lift site spelled
10345// `|<slot>| AplicacaoError::<Variant> { <slot> }`) — Rust's function-pointer-
10346// to-`FnOnce` coercion on any `fn(<ty>) -> AplicacaoError` inherent
10347// constructor with matching arity and signature. The `const fn` qualifier
10348// preserves the pre-lift `Copy`-pass-through's zero-runtime-work property
10349// verbatim (no `.to_string()` / `.into()` allocation, no branching); the
10350// per-variant `$field:ident` axis re-uses the enum's canonical field name so
10351// the generated ctor's parameter name matches every wire-up's local binding
10352// (`|timeout|` calls `policy_timeout_not_canonical(timeout)`, etc.), matching
10353// the peer [`aplicacao_field_reason_ctors!`] / [`aplicacao_caixa_only_ctors!`]
10354// / [`aplicacao_path_only_ctors!`] convention. `#[must_use]` fires a compile
10355// warning at any wire-up that mistakenly discards the constructed error, on
10356// the same footing as every sibling `AplicacaoError` / `DepError` /
10357// `SupervisorError` / `LayoutError` / `LimitsError` / `BehaviorError` /
10358// `UpgradeError` ctor macro (14b81d5 / 8580068 / 981060b / 14e13f1 / 81c856c
10359// / 8e67041 / 7468ca9 / 67c31ec / d2ef2ec / f85f145 / 0e35793 / 792aa92 /
10360// 6f5e0cd / 3fe3dd7 / 1b09f9d / 131ca0d / 0419438).
10361//
10362// Every future consumer that wants to construct one of these eight variants
10363// outside [`MeshPolicy::validate`] — a deferred
10364// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook re-
10365// checking each `:politicas` axis against a cluster-local `:politicas` cap
10366// overlay, a future per-`:contratos`-edge `:politicas` override the
10367// MESH-COMPOSITION §III.2 #3 roadmap acknowledges resolving an *effective*
10368// per-edge [`MeshPolicy`] and emitting the same per-axis diagnostic on the
10369// same input as `feira build`, an M4 per-cluster `:politicas`-cap resolver
10370// projecting a per-tenant per-axis ceiling into the same diagnostic shape,
10371// a future `feira validate --politicas` per-caixa admission verb re-checking
10372// each declared per-axis value against the same bounds — now reaches each
10373// variant through one call rather than re-inlining the one-line struct-
10374// literal in lockstep with the seven `MeshPolicy::validate` wire-up sites,
10375// which is exactly the invariant every prior ctor-macro lift already closed
10376// on its sibling envelope. Closes the last remaining per-`:politicas`
10377// per-axis `AplicacaoError` variant family that had not yet been folded onto
10378// a substrate primitive; the compound cross-axis variants
10379// ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`] / `*RateLimit` /
10380// `*RetriesBurst`) each carry a distinct multi-slot field shape and are folded
10381// on a separate axis by [`MeshPolicy::first_cross_axis_violation`].
10382macro_rules! aplicacao_policy_scalar_ctors {
10383    ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
10384        impl AplicacaoError {
10385            $(
10386                #[doc = concat!(
10387                    "Construct an [`AplicacaoError::",
10388                    stringify!($variant),
10389                    "`] naming the offending per-`:politicas` `",
10390                    stringify!($field),
10391                    "` scalar. Folds the uniform `Self::",
10392                    stringify!($variant),
10393                    " { ",
10394                    stringify!($field),
10395                    " }` one-field `Copy`-pass-through struct-literal onto ",
10396                    "one substrate primitive so every per-axis wire-up on ",
10397                    "this variant reads through one dispatch — as a direct ",
10398                    "call (`AplicacaoError::",
10399                    stringify!($ctor),
10400                    "(<val>)`, byte-equal to the pre-lift struct-literal on ",
10401                    "the same `Copy`-`",
10402                    stringify!($ty),
10403                    "` fixture) or as a bare function pointer in the ",
10404                    "`impl FnOnce(",
10405                    stringify!($ty),
10406                    ") -> AplicacaoError` bracket-closure slot every ",
10407                    "`crate::render::require_positive_bounded_*` / ",
10408                    "`crate::render::require_positive_canonical_bounded_*` ",
10409                    "gate carries — rather than the pre-lift open-coded ",
10410                    "one-line closure over the same one-field struct-",
10411                    "literal. `const fn` preserves the `Copy`-pass-through's ",
10412                    "zero-runtime-work property verbatim."
10413                )]
10414                #[must_use]
10415                pub const fn $ctor($field: $ty) -> Self {
10416                    Self::$variant { $field }
10417                }
10418            )*
10419        }
10420    };
10421}
10422
10423aplicacao_policy_scalar_ctors! {
10424    policy_timeout_not_canonical => PolicyTimeoutNotCanonical { timeout: Duration },
10425    policy_timeout_exceeds_cap => PolicyTimeoutExceedsCap { timeout: Duration },
10426    policy_retries_exceeds_cap => PolicyRetriesExceedsCap { retries: u32 },
10427    policy_breaker_max_failures_exceeds_cap =>
10428        PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
10429    policy_breaker_window_not_canonical =>
10430        PolicyBreakerWindowNotCanonical { window: Duration },
10431    policy_breaker_window_exceeds_cap =>
10432        PolicyBreakerWindowExceedsCap { window: Duration },
10433    policy_rate_limit_exceeds_cap => PolicyRateLimitExceedsCap { rate: u32 },
10434    policy_rate_limit_window_not_canonical =>
10435        PolicyRateLimitWindowNotCanonical { window: Duration },
10436}
10437
10438#[cfg(test)]
10439mod tests {
10440    use super::*;
10441
10442    fn membro(name: &str, ver: &str) -> Membro {
10443        Membro {
10444            caixa: name.into(),
10445            versao: ver.into(),
10446        }
10447    }
10448
10449    fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
10450        WitContract {
10451            de: de.into(),
10452            para: para.into(),
10453            wit: "wasi:http/proxy".into(),
10454            endpoint: Some(ep.into()),
10455            subject: None,
10456            slot: None,
10457        }
10458    }
10459
10460    fn three_member_spec() -> AplicacaoSpec {
10461        AplicacaoSpec {
10462            membros: vec![
10463                membro("catalog", "^0.1"),
10464                membro("cart", "^0.1"),
10465                membro("payment", "^0.2"),
10466            ],
10467            contratos: vec![
10468                contract_http("cart", "catalog", "/products/:id"),
10469                contract_http("cart", "payment", "/charge"),
10470            ],
10471            politicas: MeshPolicy {
10472                timeout: Some(Duration::from_secs(30)),
10473                retries: Some(3),
10474                mtls_required: Some(true),
10475                ..Default::default()
10476            },
10477            placement: Placement {
10478                estrategia: PlacementStrategy::Replicated,
10479                clusters: vec!["rio".into(), "mar".into()],
10480                affinity: Some("data-locality".into()),
10481                shard_key: None,
10482            },
10483            entrada: Some(Entrada {
10484                host: "checkout.quero.cloud".into(),
10485                para: "cart".into(),
10486                paths: vec!["/api/cart".into(), "/api/products".into()],
10487                port: 8080,
10488            }),
10489        }
10490    }
10491
10492    #[test]
10493    fn happy_path_validates() {
10494        three_member_spec().validate().unwrap();
10495    }
10496
10497    #[test]
10498    fn rejects_empty_membros() {
10499        let mut s = three_member_spec();
10500        s.membros = vec![];
10501        assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
10502    }
10503
10504    #[test]
10505    fn rejects_empty_membro_caixa() {
10506        // A `:caixa ""` entry has no name to render into programs.yaml
10507        // and no caixa.lisp to resolve at lacre time.
10508        let mut s = three_member_spec();
10509        s.membros[1].caixa = String::new();
10510        assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
10511    }
10512
10513    #[test]
10514    fn rejects_empty_membro_versao() {
10515        // A `:versao ""` entry can't pin a semver constraint, so the
10516        // lacre pipeline fails far from the source.
10517        let mut s = three_member_spec();
10518        s.membros[2].versao = String::new();
10519        let err = s.validate().unwrap_err();
10520        assert!(
10521            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
10522            "got {err:?}"
10523        );
10524    }
10525
10526    #[test]
10527    fn rejects_duplicate_membro_caixa() {
10528        // Two `:membros` entries with the same `:caixa` collapse to one
10529        // node in the membership HashSet, which masks `:contratos`
10530        // membership errors and produces duplicate programs.yaml entries.
10531        let mut s = three_member_spec();
10532        s.membros.push(membro("cart", "^0.2"));
10533        let err = s.validate().unwrap_err();
10534        assert!(
10535            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
10536            "got {err:?}"
10537        );
10538    }
10539
10540    #[test]
10541    fn rejects_invalid_membro_versao_requirement() {
10542        // The fail-before-pass-after pin: a non-empty but malformed
10543        // semver requirement (`"^bad-version"`) silently passed
10544        // `validate()` on every pre-gate codebase because the prior
10545        // shape only refused the empty string. The parse failure
10546        // surfaced far downstream at lacre-resolve time with a
10547        // `semver::Error` that didn't name which `:membros` entry
10548        // carried the typo. The new gate moves the check to caixa-build
10549        // time at the source caixa.lisp.
10550        let mut s = three_member_spec();
10551        s.membros[2].versao = "^bad-version".into();
10552        let err = s.validate().unwrap_err();
10553        assert!(
10554            matches!(
10555                err,
10556                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
10557                    if caixa == "payment" && versao == "^bad-version"
10558            ),
10559            "got {err:?}"
10560        );
10561    }
10562
10563    #[test]
10564    fn rejects_membro_versao_with_double_caret_typo() {
10565        // `"^^0.1"` is the canonical doubled-caret typo — looks like a
10566        // Cargo-shaped requirement on first glance but fails the parser
10567        // because semver doesn't accept stacked operators. Pin this
10568        // adjacent-shape footgun explicitly so a future relaxation that
10569        // accepts "looks-canonical-but-isn't" forms surfaces here.
10570        let mut s = three_member_spec();
10571        s.membros[0].versao = "^^0.1".into();
10572        let err = s.validate().unwrap_err();
10573        assert!(
10574            matches!(
10575                err,
10576                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
10577                    if caixa == "catalog" && versao == "^^0.1"
10578            ),
10579            "got {err:?}"
10580        );
10581    }
10582
10583    #[test]
10584    fn rejects_membro_versao_with_v_prefixed_tag() {
10585        // `"v0.1"` is the canonical "git-tag-shape leaking into the
10586        // semver requirement slot" typo — an author copies the
10587        // publish-side git-tag string verbatim into `:versao`, but
10588        // Cargo's semver parser rejects the leading `v` (only digits +
10589        // canonical operators are valid in the major-version
10590        // position). The gate's diagnostic names which member entry
10591        // carried the v-prefix so the fix is one edit, not a grep
10592        // through every member's `:versao`. (Note: bare `x`-glob
10593        // shorthands like `^0.1.x` are *accepted* by the semver crate
10594        // as an `*` wildcard on the patch axis — they're a Cargo-side
10595        // valid shape, not a typo, so the gate intentionally lets them
10596        // through.)
10597        let mut s = three_member_spec();
10598        s.membros[1].versao = "v0.1".into();
10599        let err = s.validate().unwrap_err();
10600        assert!(
10601            matches!(
10602                err,
10603                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
10604                    if caixa == "cart" && versao == "v0.1"
10605            ),
10606            "got {err:?}"
10607        );
10608    }
10609
10610    #[test]
10611    fn accepts_canonical_membro_versao_forms() {
10612        // The four Cargo-shaped requirement forms `:deps :versao`
10613        // already accepts via `crate::parse_requirement` must pass the
10614        // membros gate without re-validating at the resolver layer.
10615        // Pin every leg so a future tightening of the canonical set
10616        // surfaces here as a test failure.
10617        for form in [
10618            "^0.1",      // caret — minor-range pin (the most common shape)
10619            "~0.1.2",    // tilde — patch-range pin
10620            "0.1.0",     // exact — single-version pin
10621            "*",         // wildcard — explicitly any-version (semver::VersionReq::STAR)
10622            ">=0.1, <2", // multi-range — comma-separated comparators
10623        ] {
10624            let mut s = three_member_spec();
10625            for m in &mut s.membros {
10626                m.versao = form.into();
10627            }
10628            s.validate()
10629                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
10630        }
10631    }
10632
10633    #[test]
10634    fn membro_versao_empty_takes_precedence_over_invalid() {
10635        // Order pin: the existing `MembroVersaoEmpty` diagnostic
10636        // (which doesn't try to parse) fires before the new
10637        // `MembroVersaoInvalid` parse-side diagnostic, so an empty
10638        // `:versao` keeps its narrower error message — `parse_requirement`
10639        // would also reject `""`, but the empty-string arm is the more
10640        // self-locating diagnostic for the author.
10641        let mut s = three_member_spec();
10642        s.membros[1].versao = String::new();
10643        let err = s.validate().unwrap_err();
10644        assert!(
10645            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
10646            "got {err:?}"
10647        );
10648    }
10649
10650    #[test]
10651    fn membro_versao_invalid_fires_before_duplicate_check() {
10652        // Order pin: a malformed requirement on a non-duplicate entry
10653        // surfaces *its own* diagnostic (which names the offending
10654        // `:versao` string), even when a later entry would otherwise
10655        // collapse onto an earlier name. The per-entry shape gate runs
10656        // inline before the duplicate-key insert, parallel to
10657        // `membros_validation_runs_before_contratos_membership_check`
10658        // and `duplicate_contrato_gate_runs_after_target_shape_check`.
10659        let mut s = three_member_spec();
10660        s.membros[0].versao = "^bad".into();
10661        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
10662        let err = s.validate().unwrap_err();
10663        assert!(
10664            matches!(
10665                err,
10666                AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
10667            ),
10668            "got {err:?}"
10669        );
10670    }
10671
10672    #[test]
10673    fn membro_versao_invalid_diagnostic_carries_offending_versao() {
10674        // The diagnostic-shape pin: the error names the offending
10675        // `:versao` value verbatim so the author can grep their
10676        // caixa.lisp without re-running the build, and carries a
10677        // non-empty `reason` from `semver::VersionReq::parse` so the
10678        // parser's own wording flows through to the diagnostic.
10679        let mut s = three_member_spec();
10680        s.membros[2].versao = "not-a-req".into();
10681        let err = s.validate().unwrap_err();
10682        let AplicacaoError::MembroVersaoInvalid {
10683            caixa,
10684            versao,
10685            reason,
10686        } = err
10687        else {
10688            panic!("expected MembroVersaoInvalid, got other variant");
10689        };
10690        assert_eq!(caixa, "payment");
10691        assert_eq!(versao, "not-a-req");
10692        assert!(
10693            !reason.is_empty(),
10694            "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
10695        );
10696    }
10697
10698    #[test]
10699    fn membro_versao_invalid_runs_before_contratos_check() {
10700        // A malformed `:versao` on any member must surface its own
10701        // diagnostic (which names *which* member to fix) before any
10702        // `:contratos` membership lookup raises `ContratoMemberMissing`.
10703        // The `:contratos` gate runs after `validate_membros`, so this
10704        // is structurally guaranteed — pin it explicitly so a future
10705        // refactor that reorders the gates surfaces here.
10706        let mut s = three_member_spec();
10707        s.membros[1].versao = "^^0.1".into();
10708        // Add a contrato whose `:para` doesn't exist — would normally
10709        // raise ContratoMemberMissing at the membership lookup, but
10710        // the membros gate must fire first.
10711        s.contratos
10712            .push(contract_http("cart", "phantom", "/never-reached"));
10713        let err = s.validate().unwrap_err();
10714        assert!(
10715            matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
10716            "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
10717        );
10718    }
10719
10720    #[test]
10721    fn membros_validation_runs_before_contratos_membership_check() {
10722        // If `:membros` carries a duplicate, the membership-collapse
10723        // would silently accept a `:contratos :para "phantom"` so long
10724        // as some entry hashes to "phantom". Pinning order: the
10725        // duplicate-membros error fires first, regardless of whether
10726        // contratos reference real members.
10727        let mut s = three_member_spec();
10728        s.membros = vec![
10729            membro("cart", "^0.1"),
10730            membro("cart", "^0.2"),
10731            membro("catalog", "^0.1"),
10732            membro("payment", "^0.1"),
10733        ];
10734        let err = s.validate().unwrap_err();
10735        assert!(
10736            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
10737            "got {err:?}"
10738        );
10739    }
10740
10741    #[test]
10742    fn distinct_membros_validate() {
10743        // Pin the happy-path: every `:membros` entry has a non-empty
10744        // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
10745        // The fixture already satisfies this; this test makes the
10746        // invariant explicit so a future refactor of the fixture can't
10747        // silently break the guarantee.
10748        three_member_spec().validate().unwrap();
10749    }
10750
10751    // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
10752
10753    #[test]
10754    fn rejects_membro_caixa_with_uppercase() {
10755        // The canonical "I copied the Servico's display name verbatim"
10756        // typo — caixa names are lowercase per K8s DNS-1123 label rule,
10757        // but author tools often round-trip a TitleCase or CamelCase
10758        // identifier from an ADR or a sketch. Pin the diagnostic names
10759        // the offending name and suggests the lower-cased fix in one
10760        // edit, mirroring the `rejects_entrada_host_with_uppercase`
10761        // gate's shape (c7d05ec).
10762        let mut s = three_member_spec();
10763        s.membros[1].caixa = "Cart".into();
10764        let err = s.validate().unwrap_err();
10765        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
10766            panic!("expected MembroCaixaInvalid, got other variant");
10767        };
10768        assert_eq!(caixa, "Cart");
10769        assert!(
10770            reason.contains("uppercase"),
10771            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
10772        );
10773        assert!(
10774            reason.contains("\"cart\""),
10775            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
10776        );
10777    }
10778
10779    #[test]
10780    fn rejects_membro_caixa_with_underscore() {
10781        // The canonical "I'm thinking of a Python module / Postgres
10782        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
10783        // label schema. K8s rejects `metadata.name: my_cart` at admission
10784        // time with an opaque `field is invalid` (no source-citing
10785        // diagnostic). The gate moves it to caixa-build time.
10786        let mut s = three_member_spec();
10787        s.membros[0].caixa = "my_cart".into();
10788        let err = s.validate().unwrap_err();
10789        assert!(
10790            matches!(
10791                err,
10792                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
10793                    if caixa == "my_cart" && reason.contains('_')
10794            ),
10795            "got {err:?}"
10796        );
10797    }
10798
10799    #[test]
10800    fn rejects_membro_caixa_with_dot() {
10801        // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
10802        // subdomain — even though K8s `metadata.name` itself accepts
10803        // dots (DNS-1123 subdomain rule), this string also lands as a
10804        // K8s Service name (DNS-1035 label — no dots) and as a label
10805        // value on identity-based Cilium selectors. The strictest floor
10806        // among the use sites wins. The "I want to namespace my member
10807        // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
10808        let mut s = three_member_spec();
10809        s.membros[2].caixa = "team.cart".into();
10810        let err = s.validate().unwrap_err();
10811        assert!(
10812            matches!(
10813                err,
10814                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
10815                    if caixa == "team.cart" && reason.contains('.')
10816            ),
10817            "got {err:?}"
10818        );
10819    }
10820
10821    #[test]
10822    fn rejects_membro_caixa_with_leading_hyphen() {
10823        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
10824        // with an alphanumeric. The K8s apiserver rejects `-cart`
10825        // outright; the renderer would emit a `metadata.name: "-cart"`
10826        // that fails admission far from the source caixa.lisp.
10827        let mut s = three_member_spec();
10828        s.membros[0].caixa = "-cart".into();
10829        let err = s.validate().unwrap_err();
10830        assert!(
10831            matches!(
10832                err,
10833                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
10834                    if caixa == "-cart" && reason.contains("start and end")
10835            ),
10836            "got {err:?}"
10837        );
10838    }
10839
10840    #[test]
10841    fn rejects_membro_caixa_with_trailing_hyphen() {
10842        // The symmetric arm of the boundary rule. Pin separately so
10843        // both ends of the label are covered against a future relaxation
10844        // that only checks one boundary.
10845        let mut s = three_member_spec();
10846        s.membros[1].caixa = "cart-".into();
10847        let err = s.validate().unwrap_err();
10848        assert!(
10849            matches!(
10850                err,
10851                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
10852                    if caixa == "cart-"
10853            ),
10854            "got {err:?}"
10855        );
10856    }
10857
10858    #[test]
10859    fn rejects_membro_caixa_with_unicode() {
10860        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
10861        // (`xn--…`) by the author before it reaches K8s. The byte-by-
10862        // byte ASCII validity check rejects multi-byte UTF-8 sequences
10863        // by the first byte that fails the `[a-z0-9-]` predicate.
10864        let mut s = three_member_spec();
10865        s.membros[2].caixa = "café".into();
10866        let err = s.validate().unwrap_err();
10867        assert!(
10868            matches!(
10869                err,
10870                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
10871                    if caixa == "café"
10872            ),
10873            "got {err:?}"
10874        );
10875    }
10876
10877    #[test]
10878    fn rejects_membro_caixa_with_whitespace() {
10879        // Whitespace is the canonical "I pasted from a sketch / doc"
10880        // footgun. The apiserver rejects every `metadata.name` value
10881        // carrying whitespace; pin the gate fires at the right boundary.
10882        let mut s = three_member_spec();
10883        s.membros[0].caixa = "my cart".into();
10884        let err = s.validate().unwrap_err();
10885        assert!(
10886            matches!(
10887                err,
10888                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
10889                    if caixa == "my cart"
10890            ),
10891            "got {err:?}"
10892        );
10893    }
10894
10895    #[test]
10896    fn rejects_membro_caixa_too_long() {
10897        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
10898        // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
10899        // exactly. The gate's reason names both the cap and the actual
10900        // length so the author can shorten in one edit.
10901        let mut s = three_member_spec();
10902        let too_long = "a".repeat(64);
10903        s.membros[1].caixa = too_long.clone();
10904        let err = s.validate().unwrap_err();
10905        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
10906            panic!("expected MembroCaixaInvalid");
10907        };
10908        assert_eq!(caixa, too_long);
10909        assert!(
10910            reason.contains("63") && reason.contains("64"),
10911            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
10912        );
10913    }
10914
10915    #[test]
10916    fn membro_caixa_max_length_validates() {
10917        // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
10918        // so a future tightening (e.g. dropping to 62) surfaces here as
10919        // a regression, mirroring `entrada_host_max_length_validates`
10920        // (c7d05ec).
10921        let mut s = three_member_spec();
10922        s.membros[2].caixa = "a".repeat(63);
10923        s.entrada.as_mut().unwrap().para = "a".repeat(63);
10924        // remove contratos referencing the renamed member; they'd
10925        // raise ContratoMemberMissing otherwise
10926        s.contratos
10927            .retain(|c| c.de != "payment" && c.para != "payment");
10928        s.validate().unwrap();
10929    }
10930
10931    #[test]
10932    fn accepts_canonical_membro_caixa_forms() {
10933        // The DNS-1123 label shapes a caixa author is realistically
10934        // going to write: single-word lowercase, hyphen-joined, ending
10935        // in a digit-suffixed version (`cart-v2`), starting with a
10936        // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
10937        // DNS-1035 which requires a letter at position 0), single-
10938        // character (`a` — boundary). Pin every leg so a future
10939        // tightening that bans (e.g.) digit-start identifiers surfaces
10940        // here.
10941        for form in [
10942            "checkout",
10943            "cart",
10944            "cart-v2",
10945            "a",
10946            "c0",
10947            "3rd-party-shim",
10948            "x-1-2-3-4",
10949        ] {
10950            let mut s = three_member_spec();
10951            // Renaming a member also requires updating downstream refs;
10952            // drop everything else and rebuild a minimal spec around
10953            // just the one renamed member.
10954            s.membros = vec![membro(form, "^0.1")];
10955            s.contratos = vec![];
10956            s.entrada = None;
10957            s.validate()
10958                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
10959        }
10960    }
10961
10962    #[test]
10963    fn membro_caixa_empty_takes_precedence_over_invalid() {
10964        // Order pin: the existing `MembroCaixaEmpty` diagnostic
10965        // (which doesn't try to parse) fires before the new
10966        // `MembroCaixaInvalid` parse-side diagnostic, so an empty
10967        // `:caixa` keeps its narrower error message — the new gate
10968        // would also reject `""`, but the empty-string arm is the more
10969        // self-locating diagnostic for the author. Mirrors the
10970        // `entrada_host_empty_takes_precedence_over_invalid` pin
10971        // (c7d05ec).
10972        let mut s = three_member_spec();
10973        s.membros[1].caixa = String::new();
10974        let err = s.validate().unwrap_err();
10975        assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
10976    }
10977
10978    #[test]
10979    fn membro_caixa_invalid_fires_before_versao_check() {
10980        // Order pin: an invalid-shape `:caixa` surfaces *its own*
10981        // diagnostic (which names the offending caixa name), even when
10982        // the same entry's `:versao` is also empty/invalid. The shape
10983        // gate runs first because the diagnostic is more self-locating —
10984        // an empty/invalid `:versao` on an invalid-shape caixa name is
10985        // a downstream-fix-after-the-caixa-rename concern.
10986        let mut s = three_member_spec();
10987        s.membros[1].caixa = "Cart".into();
10988        s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
10989        let err = s.validate().unwrap_err();
10990        assert!(
10991            matches!(
10992                err,
10993                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
10994            ),
10995            "got {err:?}"
10996        );
10997    }
10998
10999    #[test]
11000    fn membro_caixa_invalid_fires_before_duplicate_check() {
11001        // Order pin: a malformed-shape `:caixa` on an earlier entry
11002        // surfaces *its own* diagnostic, even when a later entry would
11003        // otherwise collapse onto a duplicate name. The per-entry shape
11004        // gate runs inline before the duplicate-key insert, parallel
11005        // to `membro_versao_invalid_fires_before_duplicate_check`.
11006        let mut s = three_member_spec();
11007        s.membros[0].caixa = "Catalog".into();
11008        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
11009        let err = s.validate().unwrap_err();
11010        assert!(
11011            matches!(
11012                err,
11013                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
11014            ),
11015            "got {err:?}"
11016        );
11017    }
11018
11019    #[test]
11020    fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
11021        // The diagnostic-shape pin: the error names the offending
11022        // `:caixa` value verbatim so the author can grep their
11023        // caixa.lisp without re-running the build, and carries a
11024        // non-empty `reason` naming the specific violation. Same
11025        // shape every typed-shape gate enshrines (c7d05ec's
11026        // `entrada_host_diagnostic_carries_offending_host`,
11027        // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
11028        let mut s = three_member_spec();
11029        s.membros[2].caixa = "BAD_NAME".into();
11030        let err = s.validate().unwrap_err();
11031        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
11032            panic!("expected MembroCaixaInvalid");
11033        };
11034        assert_eq!(caixa, "BAD_NAME");
11035        assert!(
11036            !reason.is_empty(),
11037            "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
11038        );
11039    }
11040
11041    #[test]
11042    fn rejects_contrato_with_unknown_de() {
11043        let mut s = three_member_spec();
11044        s.contratos.push(contract_http("phantom", "catalog", "/x"));
11045        let err = s.validate().unwrap_err();
11046        assert!(
11047            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
11048        );
11049    }
11050
11051    #[test]
11052    fn rejects_contrato_with_unknown_para() {
11053        let mut s = three_member_spec();
11054        s.contratos.push(contract_http("cart", "phantom", "/x"));
11055        let err = s.validate().unwrap_err();
11056        assert!(
11057            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
11058        );
11059    }
11060
11061    #[test]
11062    fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
11063        // The read-path pin: the phantom-`:de` refusal arm's
11064        // `ContratoMemberMissing.caixa` carrier must be observed through
11065        // the lifted [`WitContract::source`] accessor, not the raw
11066        // `.de.clone()` field-access `String`-carry. Peer of the sibling
11067        // per-`:contratos` self-loop arm's `.source().to_string()` /
11068        // `.world_ref().to_string()` `String`-carry sites the earlier
11069        // convergence lifted onto the same accessor pair. A future
11070        // silent detour that reintroduced the raw `.de.clone()` at the
11071        // wrap envelope while the shape-gate and membership lookup
11072        // routed through the accessor would surface here as a byte-equal
11073        // miss between the fired diagnostic's `caixa:` field and the
11074        // offending edge's `.source()` — pinning the accessor as the
11075        // sole read path across the phantom-name refusal arm's arg +
11076        // wrap-envelope emit surface.
11077        let mut s = three_member_spec();
11078        let phantom = contract_http("phantom", "catalog", "/x");
11079        s.contratos.push(phantom.clone());
11080        let err = s.validate().unwrap_err();
11081        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
11082            panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
11083        };
11084        assert_eq!(
11085            caixa,
11086            phantom.source(),
11087            "ContratoMemberMissing.caixa on the phantom-:de arm must \
11088             byte-equal WitContract::source — the wrap envelope must \
11089             route through the lifted accessor rather than the raw \
11090             .de.clone() field-access String-carry"
11091        );
11092    }
11093
11094    #[test]
11095    fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
11096        // The symmetric read-path pin on the `:para` phantom-name
11097        // refusal arm — same shape as the sibling `:de` pin above but
11098        // on the callee-Servico axis. Pins the wrap envelope's
11099        // `caixa:` field is observed through the lifted
11100        // [`WitContract::destination`] accessor, not the raw
11101        // `.para.clone()` field-access `String`-carry.
11102        let mut s = three_member_spec();
11103        let phantom = contract_http("cart", "phantom", "/x");
11104        s.contratos.push(phantom.clone());
11105        let err = s.validate().unwrap_err();
11106        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
11107            panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
11108        };
11109        assert_eq!(
11110            caixa,
11111            phantom.destination(),
11112            "ContratoMemberMissing.caixa on the phantom-:para arm must \
11113             byte-equal WitContract::destination — the wrap envelope \
11114             must route through the lifted accessor rather than the raw \
11115             .para.clone() field-access String-carry"
11116        );
11117    }
11118
11119    #[test]
11120    fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
11121        // The read-path pin on the `:de` DNS-1123-malformed shape-gate
11122        // refusal arm — the `validate_contrato_caixa` arg must be
11123        // observed through the lifted [`WitContract::source`] accessor,
11124        // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
11125        // value routes through the shared
11126        // [`crate::render::require_valid_dns_1123_label`] floor with the
11127        // accessor-projected value; the fired
11128        // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
11129        // the offending edge's `.source()`, pinning that the arg + the
11130        // downstream `caixa: caixa.to_string()` wrap route through the
11131        // same accessor's read path.
11132        let mut s = three_member_spec();
11133        let malformed = contract_http("BAD_NAME", "catalog", "/x");
11134        s.contratos.push(malformed.clone());
11135        let err = s.validate().unwrap_err();
11136        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
11137            panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
11138        };
11139        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
11140        assert_eq!(
11141            caixa,
11142            malformed.source(),
11143            "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
11144             byte-equal WitContract::source — the shape-gate arg + wrap \
11145             envelope must route through the lifted accessor rather \
11146             than the raw &c.de &String-borrow"
11147        );
11148    }
11149
11150    #[test]
11151    fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
11152        // Symmetric arm to the sibling `:de` malformed-shape pin above,
11153        // on the `:para` axis. Pins the shape-gate arg + wrap envelope
11154        // route through the lifted [`WitContract::destination`]
11155        // accessor. `:para` runs after the `:de` shape gate in the
11156        // canonical edge-direction order, so the `:de` value must be
11157        // well-shaped for the `:para` gate to fire — the `cart` :de is
11158        // canonical.
11159        let mut s = three_member_spec();
11160        let malformed = contract_http("cart", "BAD_NAME", "/x");
11161        s.contratos.push(malformed.clone());
11162        let err = s.validate().unwrap_err();
11163        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
11164            panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
11165        };
11166        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
11167        assert_eq!(
11168            caixa,
11169            malformed.destination(),
11170            "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
11171             byte-equal WitContract::destination — the shape-gate arg + \
11172             wrap envelope must route through the lifted accessor \
11173             rather than the raw &c.para &String-borrow"
11174        );
11175    }
11176
11177    // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
11178
11179    #[test]
11180    fn rejects_contrato_de_empty() {
11181        // `:de ""` previously fell through to `ContratoMemberMissing`
11182        // (with `caixa: ""`) because the validated `:membros :caixa`
11183        // set never contains the empty string. The narrower
11184        // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
11185        // the offending slot.
11186        let mut s = three_member_spec();
11187        s.contratos.push(contract_http("", "catalog", "/x"));
11188        let err = s.validate().unwrap_err();
11189        assert_eq!(
11190            err,
11191            AplicacaoError::ContratoCaixaEmpty {
11192                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
11193            },
11194            "got {err:?}"
11195        );
11196    }
11197
11198    #[test]
11199    fn rejects_contrato_para_empty() {
11200        // Symmetric arm to `:de ""` — `:para ""` previously fell
11201        // through to `ContratoMemberMissing { caixa: "" }`.
11202        let mut s = three_member_spec();
11203        s.contratos.push(contract_http("cart", "", "/x"));
11204        let err = s.validate().unwrap_err();
11205        assert_eq!(
11206            err,
11207            AplicacaoError::ContratoCaixaEmpty {
11208                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
11209            },
11210            "got {err:?}"
11211        );
11212    }
11213
11214    #[test]
11215    fn rejects_contrato_de_with_uppercase() {
11216        // The canonical "I copied the Servico's TitleCase display
11217        // name from an ADR" typo. Until this gate landed `:de "Cart"`
11218        // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
11219        // as "this caixa isn't in `:membros`" when the root cause is
11220        // "this `:de` value's shape can never legitimately match a
11221        // validated member (DNS-1123 labels are lowercase)". The
11222        // narrower diagnostic names the offending slot, the value
11223        // verbatim, and the parser-shaped reason.
11224        let mut s = three_member_spec();
11225        s.contratos.push(contract_http("Cart", "catalog", "/x"));
11226        let err = s.validate().unwrap_err();
11227        let AplicacaoError::ContratoCaixaInvalid {
11228            slot,
11229            caixa,
11230            reason,
11231        } = err
11232        else {
11233            panic!("expected ContratoCaixaInvalid, got other variant");
11234        };
11235        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
11236        assert_eq!(caixa, "Cart");
11237        assert!(
11238            reason.contains("uppercase"),
11239            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
11240        );
11241    }
11242
11243    #[test]
11244    fn rejects_contrato_para_with_underscore() {
11245        // The canonical "I'm thinking of a Python module" leak —
11246        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
11247        // Pin the `:para` axis surfaces the same diagnostic shape as
11248        // the `:de` axis on the underscore violation.
11249        let mut s = three_member_spec();
11250        s.contratos.push(contract_http("cart", "my_catalog", "/x"));
11251        let err = s.validate().unwrap_err();
11252        assert!(
11253            matches!(
11254                err,
11255                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
11256                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
11257            ),
11258            "got {err:?}"
11259        );
11260    }
11261
11262    #[test]
11263    fn rejects_contrato_de_with_dot() {
11264        // A `:contratos :de` value is a single DNS-1123 *label*, not
11265        // a subdomain — mirroring the `:membros :caixa` floor. The
11266        // strictest floor among the use sites wins.
11267        let mut s = three_member_spec();
11268        s.contratos
11269            .push(contract_http("team.cart", "catalog", "/x"));
11270        let err = s.validate().unwrap_err();
11271        assert!(
11272            matches!(
11273                err,
11274                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
11275                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
11276            ),
11277            "got {err:?}"
11278        );
11279    }
11280
11281    #[test]
11282    fn rejects_contrato_para_with_unicode() {
11283        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
11284        // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
11285        // validity check rejects multi-byte UTF-8 by the first
11286        // non-`[a-z0-9-]` byte.
11287        let mut s = three_member_spec();
11288        s.contratos.push(contract_http("cart", "café", "/x"));
11289        let err = s.validate().unwrap_err();
11290        assert!(
11291            matches!(
11292                err,
11293                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
11294                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
11295            ),
11296            "got {err:?}"
11297        );
11298    }
11299
11300    #[test]
11301    fn rejects_contrato_de_with_leading_hyphen() {
11302        // DNS-1123 boundary rule: labels must start and end with an
11303        // alphanumeric. K8s rejects `-cart` outright; the narrower
11304        // shape diagnostic now names the violation at caixa-build
11305        // time rather than the misframed membership-lookup arm.
11306        let mut s = three_member_spec();
11307        s.contratos.push(contract_http("-cart", "catalog", "/x"));
11308        let err = s.validate().unwrap_err();
11309        assert!(
11310            matches!(
11311                err,
11312                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
11313                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
11314            ),
11315            "got {err:?}"
11316        );
11317    }
11318
11319    #[test]
11320    fn contrato_de_empty_takes_precedence_over_invalid() {
11321        // Order pin: the `ContratoCaixaEmpty` arm fires before the
11322        // `ContratoCaixaInvalid` parse-side arm — same empty-first
11323        // cascade `validate_membro_caixa` / `validate_placement_cluster`
11324        // / `validate_entrada_host` already establish on their peer
11325        // name axes. The empty string is a structurally distinct
11326        // authoring footgun (the author left the field blank, vs.
11327        // typed a malformed value), so it gets its own diagnostic.
11328        let mut s = three_member_spec();
11329        s.contratos.push(contract_http("", "catalog", "/x"));
11330        let err = s.validate().unwrap_err();
11331        assert_eq!(
11332            err,
11333            AplicacaoError::ContratoCaixaEmpty {
11334                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
11335            }
11336        );
11337    }
11338
11339    #[test]
11340    fn contrato_de_shape_fires_before_para_shape() {
11341        // Per-axis order pin: within one `:contratos` entry, the `:de`
11342        // shape gate fires before the `:para` shape gate — same
11343        // edge-direction order the existing `ContratoMemberMissing` /
11344        // `ContratoSelfLoop` / target-dispatch checks use, so the
11345        // diagnostic for a contract with both `:de` and `:para`
11346        // malformed is stable. Authors fixing the surfaced `:de`
11347        // first will see `:para`'s diagnostic on re-run.
11348        let mut s = three_member_spec();
11349        s.contratos.push(contract_http("Cart", "Catalog", "/x"));
11350        let err = s.validate().unwrap_err();
11351        assert!(
11352            matches!(
11353                err,
11354                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
11355                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
11356            ),
11357            "got {err:?}"
11358        );
11359    }
11360
11361    #[test]
11362    fn contrato_shape_fires_before_membership_lookup() {
11363        // The load-bearing pin: an invalid-shape `:de` surfaces its
11364        // *own* diagnostic, not the misframed `ContratoMemberMissing`.
11365        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
11366        // an invalid-shape `:de` could never legitimately match any
11367        // member — the prior `ContratoMemberMissing` diagnostic was
11368        // a structural impossibility framed as a graph-membership
11369        // failure. The shape gate now routes every such input through
11370        // the narrower self-locating diagnostic.
11371        let mut s = three_member_spec();
11372        s.contratos.push(contract_http("Cart", "catalog", "/x"));
11373        let err = s.validate().unwrap_err();
11374        assert!(
11375            matches!(
11376                err,
11377                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
11378            ),
11379            "got {err:?}"
11380        );
11381        // And the symmetric case: an invalid-shape `:para` surfaces
11382        // its own diagnostic too, even when `:de` is well-shaped.
11383        let mut s = three_member_spec();
11384        s.contratos.push(contract_http("cart", "Catalog", "/x"));
11385        let err = s.validate().unwrap_err();
11386        assert!(
11387            matches!(
11388                err,
11389                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
11390            ),
11391            "got {err:?}"
11392        );
11393    }
11394
11395    #[test]
11396    fn contrato_shape_fires_before_self_edge_check() {
11397        // A `:de "Cart" :para "Cart"` entry is two distinct authoring
11398        // bugs: the shape violation (uppercase) and the self-edge
11399        // violation. The narrower per-axis shape diagnostic surfaces
11400        // first because fixing the shape may reveal that the author
11401        // also meant to point `:para` at a different member — the
11402        // self-edge framing is only useful once both endpoints have
11403        // valid shape.
11404        let mut s = three_member_spec();
11405        s.contratos.push(contract_http("Cart", "Cart", "/x"));
11406        let err = s.validate().unwrap_err();
11407        assert!(
11408            matches!(
11409                err,
11410                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
11411                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
11412            ),
11413            "got {err:?}"
11414        );
11415    }
11416
11417    #[test]
11418    fn contrato_well_shaped_phantom_still_raises_member_missing() {
11419        // Strict-improvement pin: a well-shaped `:de` that simply
11420        // isn't in `:membros` (a phantom reference — author meant
11421        // to add the member but didn't, or renamed and missed an
11422        // update) still surfaces `ContratoMemberMissing`, unchanged.
11423        // The shape gate only intercepts inputs that could never
11424        // legitimately match a validated member; legitimately-shaped
11425        // phantom references remain on the graph-membership axis.
11426        let mut s = three_member_spec();
11427        s.contratos
11428            .push(contract_http("phantom-shim", "catalog", "/x"));
11429        let err = s.validate().unwrap_err();
11430        assert!(
11431            matches!(
11432                err,
11433                AplicacaoError::ContratoMemberMissing { ref caixa }
11434                    if caixa == "phantom-shim"
11435            ),
11436            "got {err:?}"
11437        );
11438    }
11439
11440    #[test]
11441    fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
11442        // The diagnostic-shape pin: the error names the offending
11443        // slot (`:de` or `:para`) verbatim and the offending value
11444        // verbatim plus a non-empty parser-shaped reason, so the
11445        // author can grep their caixa.lisp for `:de "<name>"` /
11446        // `:para "<name>"` and fix it in one edit. Same diagnostic
11447        // shape as `MembroCaixaInvalid` (3f9d7a0) and
11448        // `PlacementClusterInvalid` (6c8c00b).
11449        let mut s = three_member_spec();
11450        s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
11451        let err = s.validate().unwrap_err();
11452        let AplicacaoError::ContratoCaixaInvalid {
11453            slot,
11454            caixa,
11455            reason,
11456        } = err
11457        else {
11458            panic!("expected ContratoCaixaInvalid, got {err:?}");
11459        };
11460        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
11461        assert_eq!(caixa, "BAD_NAME");
11462        assert!(
11463            !reason.is_empty(),
11464            "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
11465        );
11466    }
11467
11468    #[test]
11469    fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
11470        // Scalar-value pin: the two author-facing kebab-case labels the
11471        // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
11472        // admits on the `:contratos` per-entry endpoint-shape axis,
11473        // one arm per typed sub-slot. Mirrors the peer scalar-value
11474        // pin the sibling top-level M2 / M3 / Supervisor
11475        // author-facing-label consts carry
11476        // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
11477        // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
11478        // slot itself), so every altitude of the typed-slot algebra
11479        // shares the same "one canonical byte-string per arm"
11480        // discipline. A future rebrand (`:de` → `:from` matching the
11481        // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
11482        // sibling, `:para` → `:to` matching the same, or
11483        // `:de`/`:para` → `:source`/`:target` matching the WIT
11484        // world's `import`/`export` half-vocabulary) lands as an
11485        // edit to exactly one const, and every consumer that reaches
11486        // for the label picks it up at build time rather than at
11487        // runtime as a downstream `ContratoCaixaEmpty` /
11488        // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
11489        // diagnostic mismatch far from the rename's commit.
11490        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
11491        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
11492    }
11493
11494    #[test]
11495    fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
11496        // Production-through-const pin: the two per-axis labels the
11497        // per-`:contratos` entry endpoint-shape gate at
11498        // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
11499        // argument to [`validate_contrato_caixa`] route through the
11500        // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
11501        // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
11502        // future rebrand that reaches the const but not the gate (or
11503        // vice versa) surfaces here at build time rather than at
11504        // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
11505        // `slot: <stale-kebab-case>` diagnostic far from the rename's
11506        // commit. Mirror of the peer
11507        // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
11508        // pin (882f498) on the sibling M3 top-level slot axis.
11509        let mut s = three_member_spec();
11510        s.contratos.push(contract_http("", "catalog", "/x"));
11511        assert_eq!(
11512            s.validate().unwrap_err(),
11513            AplicacaoError::ContratoCaixaEmpty {
11514                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
11515            }
11516        );
11517        let mut s = three_member_spec();
11518        s.contratos.push(contract_http("cart", "", "/x"));
11519        assert_eq!(
11520            s.validate().unwrap_err(),
11521            AplicacaoError::ContratoCaixaEmpty {
11522                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
11523            }
11524        );
11525    }
11526
11527    #[test]
11528    fn accepts_canonical_contrato_caixa_forms() {
11529        // The DNS-1123 label shapes a caixa author is realistically
11530        // going to write on a `:contratos :de` / `:para`. Pin every
11531        // leg so a future tightening that bans (e.g.) digit-start
11532        // identifiers surfaces here, mirroring
11533        // `accepts_canonical_membro_caixa_forms` on the peer name
11534        // axis.
11535        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
11536            let mut s = three_member_spec();
11537            s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
11538            s.contratos = vec![contract_http("checkout", form, "/x")];
11539            s.entrada = None;
11540            s.validate().unwrap_or_else(|e| {
11541                panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
11542            });
11543
11544            let mut s = three_member_spec();
11545            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
11546            s.contratos = vec![contract_http(form, "catalog", "/x")];
11547            s.entrada = None;
11548            s.validate().unwrap_or_else(|e| {
11549                panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
11550            });
11551        }
11552    }
11553
11554    #[test]
11555    fn rejects_empty_wit() {
11556        let mut s = three_member_spec();
11557        s.contratos.push(WitContract {
11558            de: "cart".into(),
11559            para: "catalog".into(),
11560            wit: String::new(),
11561            endpoint: None,
11562            subject: None,
11563            slot: None,
11564        });
11565        let err = s.validate().unwrap_err();
11566        assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
11567    }
11568
11569    #[test]
11570    fn rejects_entrada_to_unknown_member() {
11571        let mut s = three_member_spec();
11572        s.entrada.as_mut().unwrap().para = "phantom".into();
11573        assert!(matches!(
11574            s.validate().unwrap_err(),
11575            AplicacaoError::EntradaMemberMissing { .. }
11576        ));
11577    }
11578
11579    // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
11580
11581    #[test]
11582    fn rejects_entrada_para_empty() {
11583        // `:para ""` previously fell through to
11584        // `EntradaMemberMissing { para: "" }` because the validated
11585        // `:membros :caixa` set never contains the empty string. The
11586        // narrower `EntradaParaEmpty` diagnostic now names the
11587        // offending slot directly — same empty-first cascade
11588        // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
11589        // `ContratoCaixaEmpty` establish on the peer name axes.
11590        let mut s = three_member_spec();
11591        s.entrada.as_mut().unwrap().para = String::new();
11592        let err = s.validate().unwrap_err();
11593        assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
11594    }
11595
11596    #[test]
11597    fn rejects_entrada_para_with_uppercase() {
11598        // The canonical "I copied the Servico's TitleCase display
11599        // name from an ADR" typo. Until this gate landed `:para "Cart"`
11600        // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
11601        // as "this caixa isn't in `:membros`" when the root cause is
11602        // "this `:para` value's shape can never legitimately match a
11603        // validated member (DNS-1123 labels are lowercase)". The
11604        // narrower diagnostic names the value verbatim plus the
11605        // parser-shaped reason.
11606        let mut s = three_member_spec();
11607        s.entrada.as_mut().unwrap().para = "Cart".into();
11608        let err = s.validate().unwrap_err();
11609        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
11610            panic!("expected EntradaParaInvalid, got other variant");
11611        };
11612        assert_eq!(para, "Cart");
11613        assert!(
11614            reason.contains("uppercase"),
11615            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
11616        );
11617    }
11618
11619    #[test]
11620    fn rejects_entrada_para_with_underscore() {
11621        // The canonical "I'm thinking of a Python module" leak —
11622        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
11623        let mut s = three_member_spec();
11624        s.entrada.as_mut().unwrap().para = "my_cart".into();
11625        let err = s.validate().unwrap_err();
11626        assert!(
11627            matches!(
11628                err,
11629                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
11630                    if para == "my_cart" && reason.contains('_')
11631            ),
11632            "got {err:?}"
11633        );
11634    }
11635
11636    #[test]
11637    fn rejects_entrada_para_with_dot() {
11638        // An `:entrada :para` value is a single DNS-1123 *label*, not
11639        // a subdomain — mirroring the `:membros :caixa` floor. The
11640        // strictest floor among the use sites wins.
11641        let mut s = three_member_spec();
11642        s.entrada.as_mut().unwrap().para = "team.cart".into();
11643        let err = s.validate().unwrap_err();
11644        assert!(
11645            matches!(
11646                err,
11647                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
11648                    if para == "team.cart" && reason.contains('.')
11649            ),
11650            "got {err:?}"
11651        );
11652    }
11653
11654    #[test]
11655    fn rejects_entrada_para_with_unicode() {
11656        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
11657        // (`xn--…`) before it reaches K8s.
11658        let mut s = three_member_spec();
11659        s.entrada.as_mut().unwrap().para = "café".into();
11660        let err = s.validate().unwrap_err();
11661        assert!(
11662            matches!(
11663                err,
11664                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
11665            ),
11666            "got {err:?}"
11667        );
11668    }
11669
11670    #[test]
11671    fn rejects_entrada_para_with_leading_hyphen() {
11672        // DNS-1123 boundary rule: labels must start and end with an
11673        // alphanumeric. K8s rejects `-cart` outright.
11674        let mut s = three_member_spec();
11675        s.entrada.as_mut().unwrap().para = "-cart".into();
11676        let err = s.validate().unwrap_err();
11677        assert!(
11678            matches!(
11679                err,
11680                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
11681                    if para == "-cart" && reason.contains("start and end")
11682            ),
11683            "got {err:?}"
11684        );
11685    }
11686
11687    #[test]
11688    fn rejects_entrada_para_with_trailing_hyphen() {
11689        // Symmetric boundary arm.
11690        let mut s = three_member_spec();
11691        s.entrada.as_mut().unwrap().para = "cart-".into();
11692        let err = s.validate().unwrap_err();
11693        assert!(
11694            matches!(
11695                err,
11696                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
11697                    if para == "cart-" && reason.contains("start and end")
11698            ),
11699            "got {err:?}"
11700        );
11701    }
11702
11703    #[test]
11704    fn rejects_entrada_para_too_long() {
11705        // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
11706        // bytes per label. K8s rejects longer names at admission on
11707        // every `metadata.name` axis.
11708        let mut s = three_member_spec();
11709        s.entrada.as_mut().unwrap().para = "a".repeat(64);
11710        let err = s.validate().unwrap_err();
11711        assert!(
11712            matches!(
11713                err,
11714                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
11715                    if para.len() == 64 && reason.contains("max length")
11716            ),
11717            "got {err:?}"
11718        );
11719    }
11720
11721    #[test]
11722    fn entrada_para_empty_takes_precedence_over_invalid() {
11723        // Order pin: the `EntradaParaEmpty` arm fires before the
11724        // `EntradaParaInvalid` parse-side arm — same empty-first
11725        // cascade `validate_membro_caixa` / `validate_placement_cluster`
11726        // / `validate_contrato_caixa` already establish.
11727        let mut s = three_member_spec();
11728        s.entrada.as_mut().unwrap().para = String::new();
11729        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
11730    }
11731
11732    #[test]
11733    fn entrada_para_shape_fires_before_membership_lookup() {
11734        // The load-bearing pin: an invalid-shape `:para` surfaces its
11735        // *own* diagnostic, not the misframed `EntradaMemberMissing`.
11736        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
11737        // an invalid-shape `:para` could never legitimately match any
11738        // member — the prior `EntradaMemberMissing` diagnostic framed
11739        // a structural impossibility as a graph-membership failure.
11740        let mut s = three_member_spec();
11741        s.entrada.as_mut().unwrap().para = "Cart".into();
11742        let err = s.validate().unwrap_err();
11743        assert!(
11744            matches!(
11745                err,
11746                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
11747            ),
11748            "got {err:?}"
11749        );
11750    }
11751
11752    #[test]
11753    fn entrada_para_shape_fires_before_host_gate() {
11754        // Per-`:entrada` order pin: the `:para` shape gate fires
11755        // before the `:host` gate, mirroring the existing
11756        // `entrada_host_member_missing_takes_precedence_over_host_invalid`
11757        // ordering where the member-lookup arm preceded the host gate.
11758        // The shape gate slots ahead of that, so a malformed `:para`
11759        // surfaces its own diagnostic even when `:host` is also wrong.
11760        let mut s = three_member_spec();
11761        let e = s.entrada.as_mut().unwrap();
11762        e.para = "Cart".into();
11763        e.host = "BAD HOST".into();
11764        let err = s.validate().unwrap_err();
11765        assert!(
11766            matches!(
11767                err,
11768                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
11769            ),
11770            "got {err:?}"
11771        );
11772    }
11773
11774    #[test]
11775    fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
11776        // Strict-improvement pin: a well-shaped `:para` that simply
11777        // isn't in `:membros` (a phantom reference — author meant to
11778        // add the member but didn't, or renamed and missed an
11779        // update) still surfaces `EntradaMemberMissing`, unchanged.
11780        // The shape gate only intercepts inputs that could never
11781        // legitimately match a validated member.
11782        let mut s = three_member_spec();
11783        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
11784        let err = s.validate().unwrap_err();
11785        assert!(
11786            matches!(
11787                err,
11788                AplicacaoError::EntradaMemberMissing { ref para }
11789                    if para == "phantom-shim"
11790            ),
11791            "got {err:?}"
11792        );
11793    }
11794
11795    #[test]
11796    fn entrada_para_invalid_diagnostic_carries_offending_para() {
11797        // The diagnostic-shape pin: the error names the offending
11798        // `:para` value verbatim plus a non-empty parser-shaped
11799        // reason, so the author can grep their caixa.lisp for
11800        // `:para "<name>"` and fix it in one edit. Same diagnostic
11801        // shape as `MembroCaixaInvalid` (3f9d7a0),
11802        // `PlacementClusterInvalid` (6c8c00b), and
11803        // `ContratoCaixaInvalid` (8d5af6b).
11804        let mut s = three_member_spec();
11805        s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
11806        let err = s.validate().unwrap_err();
11807        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
11808            panic!("expected EntradaParaInvalid, got {err:?}");
11809        };
11810        assert_eq!(para, "BAD_NAME");
11811        assert!(
11812            !reason.is_empty(),
11813            "EntradaParaInvalid `reason` must carry a parser-shaped wording"
11814        );
11815    }
11816
11817    #[test]
11818    fn accepts_canonical_entrada_para_forms() {
11819        // Positive-control sweep covering the DNS-1123 label shapes a
11820        // caixa author is realistically going to write on `:entrada
11821        // :para`. Pin every leg so a future tightening that bans
11822        // (e.g.) digit-start identifiers surfaces here, mirroring
11823        // `accepts_canonical_membro_caixa_forms` and
11824        // `accepts_canonical_contrato_caixa_forms` on the peer name
11825        // axes.
11826        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
11827            let mut s = three_member_spec();
11828            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
11829            s.contratos = vec![contract_http(form, "catalog", "/x")];
11830            s.entrada = Some(Entrada {
11831                host: "checkout.quero.cloud".into(),
11832                para: form.into(),
11833                paths: vec!["/api".into()],
11834                port: 8080,
11835            });
11836            s.validate().unwrap_or_else(|e| {
11837                panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
11838            });
11839        }
11840    }
11841
11842    #[test]
11843    fn rejects_replicated_without_clusters() {
11844        let mut s = three_member_spec();
11845        s.placement.clusters = vec![];
11846        assert!(matches!(
11847            s.validate().unwrap_err(),
11848            AplicacaoError::PlacementWithoutClusters { .. }
11849        ));
11850    }
11851
11852    #[test]
11853    fn rejects_sharded_without_key() {
11854        let mut s = three_member_spec();
11855        s.placement.estrategia = PlacementStrategy::Sharded;
11856        s.placement.shard_key = None;
11857        s.placement.clusters = vec!["rio".into()];
11858        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
11859    }
11860
11861    #[test]
11862    fn sharded_with_key_validates() {
11863        let mut s = three_member_spec();
11864        s.placement.estrategia = PlacementStrategy::Sharded;
11865        s.placement.shard_key = Some("$tenantId".into());
11866        s.validate().unwrap();
11867    }
11868
11869    #[test]
11870    fn round_trip_via_json_preserves_shape() {
11871        let s = three_member_spec();
11872        let json = serde_json::to_string(&s.membros).unwrap();
11873        let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
11874        assert_eq!(back, s.membros);
11875
11876        let json = serde_json::to_string(&s.contratos).unwrap();
11877        let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
11878        assert_eq!(back, s.contratos);
11879
11880        let json = serde_json::to_string(&s.placement).unwrap();
11881        let back: Placement = serde_json::from_str(&json).unwrap();
11882        assert_eq!(back, s.placement);
11883
11884        let json = serde_json::to_string(&s.entrada).unwrap();
11885        let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
11886        assert_eq!(back, s.entrada);
11887    }
11888
11889    #[test]
11890    fn rate_limit_round_trip_seconds() {
11891        let policy = MeshPolicy {
11892            rate_limit: Some(RateLimit {
11893                rate: 100,
11894                window: Duration::from_secs(1),
11895            }),
11896            ..Default::default()
11897        };
11898        let json = serde_json::to_string(&policy).unwrap();
11899        assert!(json.contains("\"100/s\""));
11900        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
11901        assert_eq!(back.rate_limit.unwrap().rate, 100);
11902        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
11903    }
11904
11905    #[test]
11906    fn rate_limit_round_trip_minutes() {
11907        let policy = MeshPolicy {
11908            rate_limit: Some(RateLimit {
11909                rate: 5000,
11910                window: Duration::from_secs(60),
11911            }),
11912            ..Default::default()
11913        };
11914        let json = serde_json::to_string(&policy).unwrap();
11915        assert!(json.contains("\"5000/m\""));
11916    }
11917
11918    #[test]
11919    fn circuit_breaker_round_trip() {
11920        let policy = MeshPolicy {
11921            circuit_breaker: Some(CircuitBreaker {
11922                max_failures: 5,
11923                window: Duration::from_secs(60),
11924            }),
11925            ..Default::default()
11926        };
11927        let json = serde_json::to_string(&policy).unwrap();
11928        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
11929        assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
11930        assert_eq!(
11931            back.circuit_breaker.unwrap().window,
11932            Duration::from_secs(60)
11933        );
11934    }
11935
11936    #[test]
11937    fn rejects_http_contrato_without_endpoint() {
11938        let mut s = three_member_spec();
11939        s.contratos.push(WitContract {
11940            de: "cart".into(),
11941            para: "catalog".into(),
11942            wit: "wasi:http/proxy".into(),
11943            endpoint: None,
11944            subject: None,
11945            slot: None,
11946        });
11947        let err = s.validate().unwrap_err();
11948        assert!(matches!(
11949            err,
11950            AplicacaoError::ContratoMissingTarget {
11951                expected: WitTarget::HTTP_FIELD_NAME,
11952                ..
11953            }
11954        ));
11955    }
11956
11957    #[test]
11958    fn rejects_http_contrato_with_subject() {
11959        let mut s = three_member_spec();
11960        s.contratos.push(WitContract {
11961            de: "cart".into(),
11962            para: "catalog".into(),
11963            wit: "wasi:http/proxy".into(),
11964            endpoint: Some("/x".into()),
11965            subject: Some("not.allowed.here".into()),
11966            slot: None,
11967        });
11968        let err = s.validate().unwrap_err();
11969        assert!(matches!(
11970            err,
11971            AplicacaoError::ContratoWrongTarget {
11972                expected: WitTarget::HTTP_FIELD_NAME,
11973                ..
11974            }
11975        ));
11976    }
11977
11978    #[test]
11979    fn rejects_pubsub_contrato_without_subject() {
11980        let mut s = three_member_spec();
11981        s.contratos.push(WitContract {
11982            de: "cart".into(),
11983            para: "catalog".into(),
11984            wit: "nats:pub-sub".into(),
11985            endpoint: None,
11986            subject: None,
11987            slot: None,
11988        });
11989        let err = s.validate().unwrap_err();
11990        assert!(matches!(
11991            err,
11992            AplicacaoError::ContratoMissingTarget {
11993                expected: WitTarget::PUBSUB_FIELD_NAME,
11994                ..
11995            }
11996        ));
11997    }
11998
11999    #[test]
12000    fn rejects_pubsub_contrato_with_endpoint() {
12001        let mut s = three_member_spec();
12002        s.contratos.push(WitContract {
12003            de: "cart".into(),
12004            para: "catalog".into(),
12005            wit: "kafka:topic".into(),
12006            endpoint: Some("/wrong".into()),
12007            subject: Some("topic.x".into()),
12008            slot: None,
12009        });
12010        let err = s.validate().unwrap_err();
12011        assert!(matches!(
12012            err,
12013            AplicacaoError::ContratoWrongTarget {
12014                expected: WitTarget::PUBSUB_FIELD_NAME,
12015                ..
12016            }
12017        ));
12018    }
12019
12020    #[test]
12021    fn rejects_store_contrato_without_slot() {
12022        let mut s = three_member_spec();
12023        s.contratos.push(WitContract {
12024            de: "cart".into(),
12025            para: "catalog".into(),
12026            wit: "wasi:keyvalue/store".into(),
12027            endpoint: None,
12028            subject: None,
12029            slot: None,
12030        });
12031        let err = s.validate().unwrap_err();
12032        assert!(matches!(
12033            err,
12034            AplicacaoError::ContratoMissingTarget {
12035                expected: WitTarget::STORE_FIELD_NAME,
12036                ..
12037            }
12038        ));
12039    }
12040
12041    // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
12042
12043    #[test]
12044    fn rejects_http_contrato_with_empty_endpoint() {
12045        // `Some("")` for an HTTP endpoint passes the presence check
12046        // (target() previously returned WitTarget::Http { endpoint: "" })
12047        // but renders as a `path: ""` Cilium L7 rule that matches no
12048        // traffic. Same value-shape footgun closed for :entrada :paths
12049        // entries (eb3456d).
12050        let mut s = three_member_spec();
12051        s.contratos.push(WitContract {
12052            de: "cart".into(),
12053            para: "catalog".into(),
12054            wit: "wasi:http/proxy".into(),
12055            endpoint: Some(String::new()),
12056            subject: None,
12057            slot: None,
12058        });
12059        let err = s.validate().unwrap_err();
12060        assert!(
12061            matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
12062                if de == "cart" && para == "catalog"),
12063            "got {err:?}"
12064        );
12065    }
12066
12067    #[test]
12068    fn rejects_http_contrato_with_relative_endpoint() {
12069        // Cilium L7 :path + Gateway API PathPrefix both require a
12070        // leading `/`. Same shape required of :entrada :paths
12071        // (eb3456d). Lifted into target() so every consumer of the
12072        // typed WitTarget view inherits the guarantee.
12073        let mut s = three_member_spec();
12074        s.contratos.push(WitContract {
12075            de: "cart".into(),
12076            para: "catalog".into(),
12077            wit: "wasi:http/proxy".into(),
12078            endpoint: Some("products/:id".into()),
12079            subject: None,
12080            slot: None,
12081        });
12082        let err = s.validate().unwrap_err();
12083        assert!(
12084            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
12085                if endpoint == "products/:id"),
12086            "got {err:?}"
12087        );
12088    }
12089
12090    #[test]
12091    fn rejects_pubsub_contrato_with_empty_subject() {
12092        // NATS / Kafka publish without a subject is a no-op subscribe;
12093        // never the author's intent. Same empty-string rejection as
12094        // :membros :caixa, :placement :clusters entries, :entrada
12095        // :paths entries — every value carried by every typed slot is
12096        // value-shape-checked at validate().
12097        let mut s = three_member_spec();
12098        s.contratos.push(WitContract {
12099            de: "cart".into(),
12100            para: "catalog".into(),
12101            wit: "nats:pub-sub".into(),
12102            endpoint: None,
12103            subject: Some(String::new()),
12104            slot: None,
12105        });
12106        let err = s.validate().unwrap_err();
12107        assert!(
12108            matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
12109                if de == "cart" && para == "catalog"),
12110            "got {err:?}"
12111        );
12112    }
12113
12114    #[test]
12115    fn rejects_store_contrato_with_empty_slot() {
12116        // An empty slot template addresses the bucket root, defeating
12117        // the per-key isolation the slot exists for — a footgun on
12118        // `wasi:keyvalue/store` whose closest analog is the empty
12119        // shard-key rejected on :placement Sharded (c7c7799).
12120        let mut s = three_member_spec();
12121        s.contratos.push(WitContract {
12122            de: "cart".into(),
12123            para: "catalog".into(),
12124            wit: "wasi:keyvalue/store".into(),
12125            endpoint: None,
12126            subject: None,
12127            slot: Some(String::new()),
12128        });
12129        let err = s.validate().unwrap_err();
12130        assert!(
12131            matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
12132                if de == "cart" && para == "catalog"),
12133            "got {err:?}"
12134        );
12135    }
12136
12137    #[test]
12138    fn http_contrato_root_endpoint_validates() {
12139        // Pin the boundary case: a single-`/` endpoint is the catch-all
12140        // form the Gateway HTTPRoute renderer falls back to when
12141        // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
12142        // must remain a valid contrato endpoint too.
12143        let mut s = three_member_spec();
12144        s.contratos.push(contract_http("cart", "catalog", "/"));
12145        s.validate().unwrap();
12146    }
12147
12148    // ── :contratos :endpoint value-shape gate ────────────────────────────
12149    //
12150    // Mirrors the `:entrada :paths` value-shape suite on the peer
12151    // HTTP-path axis. Until this gate landed `WitContract::target()`
12152    // only refused the empty string + the missing-leading-`/` form
12153    // (c4213a4); a structurally invalid endpoint passed validate and
12154    // landed verbatim as a Cilium L7 `path:` rule
12155    // (caixa-mesh/src/lib.rs:311) that either silently dropped all
12156    // traffic or was rejected at apply time by Cilium policy admission.
12157    // Every authoring footgun the K8s Gateway API webhook / Cilium
12158    // policy validator would catch on admission now becomes a caixa-
12159    // build-time `ContratoEndpointInvalid` with the offending
12160    // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
12161    // shape as `EntradaPathInvalid` on the sibling axis; same shared
12162    // predicate (`crate::render::is_gateway_api_http_path`) ensures
12163    // drift between the two axes' rule enforcement is a build error
12164    // at the predicate.
12165
12166    fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
12167        // Fresh spec per call so the would-be-duplicate edge
12168        // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
12169        // `three_member_spec`'s pre-existing
12170        // `(cart, catalog, …, /products/:id)` entry — only the
12171        // endpoint payload differs.
12172        let mut s = three_member_spec();
12173        s.contratos.push(contract_http("cart", "catalog", ep));
12174        s.validate().unwrap_err()
12175    }
12176
12177    #[test]
12178    fn rejects_http_contrato_endpoint_with_query() {
12179        // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
12180        // silently rendered as a Cilium L7 `path: "/charge?token=X"`
12181        // rule the L7 matcher would never satisfy.
12182        let err = contrato_endpoint_err("/charge?token=X");
12183        assert!(
12184            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12185                if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
12186            "got {err:?}"
12187        );
12188    }
12189
12190    #[test]
12191    fn rejects_http_contrato_endpoint_with_fragment() {
12192        let err = contrato_endpoint_err("/charge#frag");
12193        assert!(
12194            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12195                if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
12196            "got {err:?}"
12197        );
12198    }
12199
12200    #[test]
12201    fn rejects_http_contrato_endpoint_with_whitespace() {
12202        let err = contrato_endpoint_err("/foo bar");
12203        assert!(
12204            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12205                if endpoint == "/foo bar" && reason.contains("whitespace")),
12206            "got {err:?}"
12207        );
12208    }
12209
12210    #[test]
12211    fn rejects_http_contrato_endpoint_with_control_char() {
12212        let err = contrato_endpoint_err("/api/\x01bar");
12213        assert!(
12214            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12215                if endpoint == "/api/\x01bar" && reason.contains("control character")),
12216            "got {err:?}"
12217        );
12218    }
12219
12220    #[test]
12221    fn rejects_http_contrato_endpoint_with_non_ascii() {
12222        let err = contrato_endpoint_err("/api/café");
12223        assert!(
12224            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12225                if endpoint == "/api/café" && reason.contains("non-ASCII")),
12226            "got {err:?}"
12227        );
12228    }
12229
12230    #[test]
12231    fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
12232        let err = contrato_endpoint_err("/api//cart");
12233        assert!(
12234            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12235                if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
12236            "got {err:?}"
12237        );
12238    }
12239
12240    #[test]
12241    fn rejects_http_contrato_endpoint_with_dot_segment() {
12242        let err = contrato_endpoint_err("/api/./cart");
12243        assert!(
12244            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12245                if endpoint == "/api/./cart" && reason.contains("`.` segment")),
12246            "got {err:?}"
12247        );
12248    }
12249
12250    #[test]
12251    fn rejects_http_contrato_endpoint_with_parent_segment() {
12252        // Path-traversal in a contrato endpoint is the canonical
12253        // "L7 rule that the workload's HTTP server's path-resolution
12254        // logic interprets differently than the policy enforcer"
12255        // footgun. Rejected outright at validate time.
12256        let err = contrato_endpoint_err("/api/../etc");
12257        assert!(
12258            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12259                if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
12260            "got {err:?}"
12261        );
12262    }
12263
12264    #[test]
12265    fn rejects_http_contrato_endpoint_too_long() {
12266        // 1025-byte endpoint — one over the Gateway API
12267        // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
12268        // path matcher has no inherent length limit but the policy
12269        // CR itself rides through the K8s apiserver, which enforces
12270        // ConfigMap-shaped limits; sharing the Gateway API cap is the
12271        // conservative floor.
12272        let big = format!("/api/{}", "a".repeat(1020));
12273        assert_eq!(big.len(), 1025);
12274        let err = contrato_endpoint_err(&big);
12275        assert!(
12276            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12277                if endpoint == &big && reason.contains("max length of 1024")),
12278            "got {err:?}"
12279        );
12280    }
12281
12282    #[test]
12283    fn http_contrato_endpoint_max_length_validates() {
12284        // 1024-byte endpoint — exactly the cap. Boundary pin: drift
12285        // in the cap surfaces here and at
12286        // `rejects_http_contrato_endpoint_too_long` simultaneously,
12287        // mirroring `entrada_path_max_length_validates` on the peer
12288        // axis.
12289        let big = format!("/api/{}", "a".repeat(1019));
12290        assert_eq!(big.len(), 1024);
12291        let mut s = three_member_spec();
12292        s.contratos.push(contract_http("cart", "catalog", &big));
12293        s.validate().unwrap();
12294    }
12295
12296    #[test]
12297    fn http_contrato_endpoint_accepts_canonical_forms() {
12298        // Positive-set sweep: every canonical HTTP-path shape the
12299        // sibling `:entrada :paths` axis accepts (the bare-root `/`,
12300        // plain paths, hidden-file-style `.config` segments distinct
12301        // from the `.` segment, digit-bearing segments, the canonical
12302        // route-template `:param` form, trailing-slash form,
12303        // percent-encoded segments, the `/foo..bar` interior-`..`-
12304        // substring forms that are NOT `..` segments) must remain a
12305        // valid contrato endpoint too. Drift between this list and
12306        // the entrada path positive sweep surfaces at the shared
12307        // `is_gateway_api_http_path` substrate-side suite — one
12308        // source of truth. Uses a fresh `(payment, catalog)` edge so
12309        // none of the swept endpoints collide with the pre-existing
12310        // `(cart, catalog, /products/:id)` / `(cart, payment,
12311        // /charge)` entries in `three_member_spec`.
12312        for ep in [
12313            "/",
12314            "/charge",
12315            "/v1/charge",
12316            "/api/.config",
12317            "/products/:id",
12318            "/api/cart/",
12319            "/api/caf%C3%A9",
12320            "/foo..bar",
12321            "/...",
12322        ] {
12323            let mut s = three_member_spec();
12324            s.contratos.push(contract_http("payment", "catalog", ep));
12325            s.validate()
12326                .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
12327        }
12328    }
12329
12330    #[test]
12331    fn contrato_endpoint_empty_takes_precedence_over_invalid() {
12332        // Ordering pin: `ContratoEndpointEmpty` is the more self-
12333        // locating diagnostic on `""` and must lead — the value-
12334        // shape gate is only reached after the empty-check fires.
12335        // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
12336        // on the peer axis.
12337        let mut s = three_member_spec();
12338        s.contratos.push(WitContract {
12339            de: "cart".into(),
12340            para: "catalog".into(),
12341            wit: "wasi:http/proxy".into(),
12342            endpoint: Some(String::new()),
12343            subject: None,
12344            slot: None,
12345        });
12346        let err = s.validate().unwrap_err();
12347        assert!(
12348            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
12349            "got {err:?}"
12350        );
12351    }
12352
12353    #[test]
12354    fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
12355        // Ordering pin: an endpoint without a leading `/` surfaces the
12356        // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
12357        // value-shape gate is only consulted on endpoints that already
12358        // satisfy the absolute-prefix invariant. Mirrors
12359        // `entrada_path_not_absolute_takes_precedence_over_invalid`.
12360        let err = contrato_endpoint_err("bad path");
12361        assert!(
12362            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
12363                if endpoint == "bad path"),
12364            "got {err:?}"
12365        );
12366    }
12367
12368    #[test]
12369    fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
12370        // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
12371        // `:para` + a non-empty reason flow through verbatim so the
12372        // author can grep their caixa.lisp for the offending contrato
12373        // block and fix it in one edit. Same shape as
12374        // `entrada_path_diagnostic_carries_offending_path`.
12375        let err = contrato_endpoint_err("/api?q=1");
12376        match err {
12377            AplicacaoError::ContratoEndpointInvalid {
12378                de,
12379                para,
12380                endpoint,
12381                reason,
12382            } => {
12383                assert_eq!(de, "cart");
12384                assert_eq!(para, "catalog");
12385                assert_eq!(endpoint, "/api?q=1");
12386                assert!(!reason.is_empty(), "reason field must be non-empty");
12387            }
12388            other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
12389        }
12390    }
12391
12392    #[test]
12393    fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
12394        // The compounding theorem: every &str inside a WitTarget
12395        // returned by target() is non-empty (and absolute, for Http).
12396        // Renderers downstream of typed_view() can rely on this
12397        // without re-checking — the type system carries the proof.
12398        let http = contract_http("cart", "catalog", "/x");
12399        match http.target().unwrap() {
12400            WitTarget::Http { endpoint } => {
12401                assert!(!endpoint.is_empty());
12402                assert!(endpoint.starts_with('/'));
12403            }
12404            other => panic!("expected Http, got {other:?}"),
12405        }
12406        let nats = WitContract {
12407            de: "a".into(),
12408            para: "b".into(),
12409            wit: "nats:pub-sub".into(),
12410            endpoint: None,
12411            subject: Some("topic.x".into()),
12412            slot: None,
12413        };
12414        match nats.target().unwrap() {
12415            WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
12416            other => panic!("expected PubSub, got {other:?}"),
12417        }
12418        let kv = WitContract {
12419            de: "a".into(),
12420            para: "b".into(),
12421            wit: "wasi:keyvalue/store".into(),
12422            endpoint: None,
12423            subject: None,
12424            slot: Some("checkout/$orderId".into()),
12425        };
12426        match kv.target().unwrap() {
12427            WitTarget::Store { slot } => assert!(!slot.is_empty()),
12428            other => panic!("expected Store, got {other:?}"),
12429        }
12430    }
12431
12432    #[test]
12433    fn target_diagnostic_names_offending_endpoint_value() {
12434        // When the malformed endpoint string is non-trivial, the
12435        // diagnostic carries the actual value back to the author —
12436        // not a generic "endpoint malformed" error.
12437        let bad = WitContract {
12438            de: "src".into(),
12439            para: "dst".into(),
12440            wit: "wasi:http/proxy".into(),
12441            endpoint: Some("api/v1/charge".into()),
12442            subject: None,
12443            slot: None,
12444        };
12445        match bad.target().unwrap_err() {
12446            AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
12447                assert_eq!(de, "src");
12448                assert_eq!(para, "dst");
12449                assert_eq!(endpoint, "api/v1/charge");
12450            }
12451            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
12452        }
12453    }
12454
12455    #[test]
12456    fn rejects_unknown_wit_with_target_set() {
12457        let mut s = three_member_spec();
12458        s.contratos.push(WitContract {
12459            de: "cart".into(),
12460            para: "catalog".into(),
12461            wit: "custom:exchange".into(),
12462            endpoint: Some("/leaked".into()),
12463            subject: None,
12464            slot: None,
12465        });
12466        let err = s.validate().unwrap_err();
12467        assert!(matches!(
12468            err,
12469            AplicacaoError::ContratoWrongTarget {
12470                expected: WitTarget::CAPABILITY_EXPECTED,
12471                ..
12472            }
12473        ));
12474    }
12475
12476    #[test]
12477    fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
12478        // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
12479        // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
12480        // fourth arm of the same "which payload field name goes in the
12481        // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
12482        // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
12483        // consts cover on the peer HTTP / PubSub / Store arms
12484        // (`wit_target_field_name_pins_per_variant`). Until this lift
12485        // landed the byte-string sat twice — once inline in the
12486        // [`WitContract::target`] Capability-arm rejection at the
12487        // production dispatch, once in `rejects_unknown_wit_with_target_set`
12488        // pinning against the same literal — with no compile-time link
12489        // between them. Same "one canonical declaration, next to the
12490        // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
12491        // lift established for the payload-less arm's human-readable
12492        // label axis; this test is the shape peer of
12493        // `wit_target_label_pins_per_variant`'s Capability-arm assertion
12494        // pair (routes-through-const + scalar-value pin) on the
12495        // wrong-target diagnostic-scalar axis.
12496        //
12497        // Fail-before-pass-after was verified locally by mutating the
12498        // const declaration to `"capability"` — the scalar-value pin
12499        // below fires (`"capability" != "none"`) and the routes-through
12500        // assertion below still holds (production and const walk in
12501        // lockstep), which is the correct behavior: a rename on the
12502        // const drifts here first, not at a downstream consumer.
12503        assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
12504
12505        let mut s = three_member_spec();
12506        s.contratos.push(WitContract {
12507            de: "cart".into(),
12508            para: "catalog".into(),
12509            wit: "custom:exchange".into(),
12510            endpoint: Some("/leaked".into()),
12511            subject: None,
12512            slot: None,
12513        });
12514        match s.validate().unwrap_err() {
12515            AplicacaoError::ContratoWrongTarget { expected, .. } => {
12516                assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
12517            }
12518            other => panic!("expected ContratoWrongTarget, got {other:?}"),
12519        }
12520    }
12521
12522    #[test]
12523    fn unknown_wit_capability_only_validates() {
12524        let mut s = three_member_spec();
12525        s.contratos.push(WitContract {
12526            de: "cart".into(),
12527            para: "catalog".into(),
12528            // A WIT world we haven't yet shaped — accept it as a typed
12529            // capability edge so authors aren't blocked while the WIT
12530            // registry catches up. No payload field may be carried.
12531            wit: "custom:exchange".into(),
12532            endpoint: None,
12533            subject: None,
12534            slot: None,
12535        });
12536        s.validate().unwrap();
12537        let added = s.contratos.last().unwrap();
12538        assert_eq!(added.target().unwrap(), WitTarget::Capability);
12539    }
12540
12541    #[test]
12542    fn target_typed_view_round_trips_each_shape() {
12543        let http = contract_http("cart", "catalog", "/products/:id");
12544        assert_eq!(
12545            http.target().unwrap(),
12546            WitTarget::Http {
12547                endpoint: "/products/:id"
12548            }
12549        );
12550        let nats = WitContract {
12551            de: "a".into(),
12552            para: "b".into(),
12553            wit: "nats:pub-sub".into(),
12554            endpoint: None,
12555            subject: Some("topic.x".into()),
12556            slot: None,
12557        };
12558        assert_eq!(
12559            nats.target().unwrap(),
12560            WitTarget::PubSub { subject: "topic.x" }
12561        );
12562        let kv = WitContract {
12563            de: "a".into(),
12564            para: "b".into(),
12565            wit: "wasi:keyvalue/store".into(),
12566            endpoint: None,
12567            subject: None,
12568            slot: Some("checkout/$orderId".into()),
12569        };
12570        assert_eq!(
12571            kv.target().unwrap(),
12572            WitTarget::Store {
12573                slot: "checkout/$orderId"
12574            }
12575        );
12576    }
12577
12578    #[test]
12579    fn wit_contract_kind_predicates() {
12580        let http = contract_http("a", "b", "/x");
12581        assert!(http.is_http());
12582        assert!(!http.is_pubsub());
12583        assert!(!http.is_store());
12584        assert!(!http.is_capability());
12585
12586        let nats = WitContract {
12587            de: "a".into(),
12588            para: "b".into(),
12589            wit: "nats:pub-sub".into(),
12590            endpoint: None,
12591            subject: Some("topic.x".into()),
12592            slot: None,
12593        };
12594        assert!(nats.is_pubsub());
12595        assert!(!nats.is_http());
12596        assert!(!nats.is_capability());
12597
12598        let kv = WitContract {
12599            de: "a".into(),
12600            para: "b".into(),
12601            wit: "wasi:keyvalue/store".into(),
12602            endpoint: None,
12603            subject: None,
12604            slot: Some("checkout/$orderId".into()),
12605        };
12606        assert!(kv.is_store());
12607        assert!(!kv.is_http());
12608        assert!(!kv.is_capability());
12609
12610        // Fourth arm on the paired closed-set predicate family: the
12611        // payload-less capability edge that projects to the payload-
12612        // less [`WitTarget::Capability`] arm under [`WitContract::target`].
12613        // Extends the 3-arm predicate sweep this test opened to cover
12614        // the closed 4-way partition [`WitContract::is_capability`]
12615        // closes on the pre-projection WIT-shape axis, matched with the
12616        // sibling post-projection [`WitTarget`]-side `IsVariant`-derived
12617        // 4-arm predicate set.
12618        let cap = WitContract {
12619            de: "a".into(),
12620            para: "b".into(),
12621            wit: "custom:capability-only".into(),
12622            endpoint: None,
12623            subject: None,
12624            slot: None,
12625        };
12626        assert!(cap.is_capability());
12627        assert!(!cap.is_http());
12628        assert!(!cap.is_pubsub());
12629        assert!(!cap.is_store());
12630    }
12631
12632    // ── :contratos :wit value-shape gate ─────────────────────────────────
12633    //
12634    // Mirrors the `:contratos :endpoint` value-shape suite on the peer
12635    // dispatch-discriminator axis. Until this gate landed
12636    // `WitContract::target()` accepted any non-empty string and
12637    // silently demoted unrecognized shapes to a capability-only L4
12638    // edge — the canonical "I thought I had L7 HTTP routing, got
12639    // L4-only" footgun. Every authoring footgun the WIT registry's
12640    // own grammar rejects (uppercase, hyphen-for-colon typo,
12641    // whitespace, empty package, doubled `@`, …) now becomes a
12642    // caixa-build-time `ContratoWitInvalid` with the offending
12643    // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
12644    // as `ContratoEndpointInvalid` on the sibling axis; same shared
12645    // predicate (`crate::render::is_wit_world_ref`) ensures drift
12646    // between any two axes' rule enforcement is a build error at the
12647    // predicate, not piecemeal across renderers.
12648
12649    fn contrato_wit_err(wit: &str) -> AplicacaoError {
12650        // Fresh spec per call so the new contract doesn't collide on
12651        // identity with `three_member_spec`'s pre-existing entries.
12652        // The new edge uses `(payment, catalog)` — a pair the fixture
12653        // doesn't already declare — with no payload field set, so the
12654        // wit-shape gate fires before any payload-shape arm.
12655        let mut s = three_member_spec();
12656        s.contratos.push(WitContract {
12657            de: "payment".into(),
12658            para: "catalog".into(),
12659            wit: wit.into(),
12660            endpoint: None,
12661            subject: None,
12662            slot: None,
12663        });
12664        s.validate().unwrap_err()
12665    }
12666
12667    #[test]
12668    fn rejects_wit_with_uppercase_namespace() {
12669        // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
12670        // didn't match the lowercase `wasi:http/` prefix is_http() keys
12671        // off, so the dispatch fell through to the capability arm and
12672        // the contract silently rendered as an L4-only Cilium edge.
12673        // The new gate surfaces the uppercase typo at validate time
12674        // with the offending `:wit` named.
12675        let err = contrato_wit_err("WASI:http/proxy");
12676        assert!(
12677            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12678                if wit == "WASI:http/proxy" && reason.contains("lowercase")),
12679            "got {err:?}"
12680        );
12681    }
12682
12683    #[test]
12684    fn rejects_wit_with_hyphen_for_colon_typo() {
12685        // The canonical "I forgot the `:` separator" typo — pre-gate
12686        // this passed as Capability silently, so the renderer emitted
12687        // an L4-only policy where the author expected L7 HTTP rules.
12688        let err = contrato_wit_err("wasi-http/proxy");
12689        assert!(
12690            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12691                if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
12692            "got {err:?}"
12693        );
12694    }
12695
12696    #[test]
12697    fn rejects_wit_with_multiple_colons() {
12698        // Doubled `:` — the namespace/package split has nowhere to
12699        // anchor, so the dispatch silently demotes to Capability.
12700        let err = contrato_wit_err("wasi:http:proxy");
12701        assert!(
12702            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12703                if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
12704            "got {err:?}"
12705        );
12706    }
12707
12708    #[test]
12709    fn rejects_wit_with_empty_package() {
12710        // `wasi:` — namespace alone with no package. Pre-gate this
12711        // failed neither the is_http nor is_pubsub nor is_store
12712        // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
12713        // a bare `wasi:`), so it silently demoted to Capability.
12714        let err = contrato_wit_err("wasi:");
12715        assert!(
12716            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12717                if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
12718            "got {err:?}"
12719        );
12720    }
12721
12722    #[test]
12723    fn rejects_wit_with_underscore() {
12724        // Underscore — WIT identifiers are kebab-case, same rule
12725        // DNS-1123 enforces on its peer axes. The diagnostic carries
12726        // the explicit "use `-` instead" remediation.
12727        let err = contrato_wit_err("wasi:http_proxy");
12728        assert!(
12729            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12730                if wit == "wasi:http_proxy" && reason.contains('_')),
12731            "got {err:?}"
12732        );
12733    }
12734
12735    #[test]
12736    fn rejects_wit_with_whitespace() {
12737        // Whitespace mid-token — the prefix check matches but the
12738        // package-and-onward parse silently demoted to Capability.
12739        let err = contrato_wit_err("wasi:http proxy");
12740        assert!(
12741            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12742                if wit == "wasi:http proxy" && reason.contains("whitespace")),
12743            "got {err:?}"
12744        );
12745    }
12746
12747    #[test]
12748    fn rejects_wit_with_non_ascii() {
12749        // Un-percent-encoded non-ASCII byte — the canonical "I copied
12750        // the package name from a doc with smart quotes / accented
12751        // characters" footgun.
12752        let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
12753        assert!(
12754            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12755                if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
12756            "got {err:?}"
12757        );
12758    }
12759
12760    #[test]
12761    fn rejects_wit_with_consecutive_hyphens() {
12762        // `pub--sub` — WIT identifiers join words with single hyphens.
12763        let err = contrato_wit_err("nats:pub--sub");
12764        assert!(
12765            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12766                if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
12767            "got {err:?}"
12768        );
12769    }
12770
12771    #[test]
12772    fn rejects_wit_with_trailing_at_no_version() {
12773        // `wasi:http/proxy@` — the version-suffix author started to
12774        // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
12775        // parser would reject this; surface it at validate time.
12776        let err = contrato_wit_err("wasi:http/proxy@");
12777        assert!(
12778            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12779                if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
12780            "got {err:?}"
12781        );
12782    }
12783
12784    #[test]
12785    fn rejects_wit_too_long() {
12786        // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
12787        // The legitimate-shape arms all pass (lowercase, single `:`,
12788        // kebab-case identifiers); only the cap arm fires. Surfaces
12789        // the paste-from-binary / accidental-multi-line-blob landing
12790        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
12791        // on the peer axis.
12792        let big = format!("wasi:{}", "a".repeat(124));
12793        assert_eq!(big.len(), 129);
12794        let err = contrato_wit_err(&big);
12795        assert!(
12796            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12797                if wit == &big && reason.contains("max length of 128")),
12798            "got {err:?}"
12799        );
12800    }
12801
12802    #[test]
12803    fn wit_max_length_validates() {
12804        // 128-byte WIT reference — exactly the cap. Boundary pin:
12805        // drift in the cap surfaces here and at `rejects_wit_too_long`
12806        // simultaneously, mirroring
12807        // `http_contrato_endpoint_max_length_validates` on the peer
12808        // axis.
12809        let big = format!("wasi:{}", "a".repeat(123));
12810        assert_eq!(big.len(), 128);
12811        let mut s = three_member_spec();
12812        s.contratos.push(WitContract {
12813            de: "payment".into(),
12814            para: "catalog".into(),
12815            wit: big,
12816            endpoint: None,
12817            subject: None,
12818            slot: None,
12819        });
12820        s.validate().unwrap();
12821    }
12822
12823    #[test]
12824    fn wit_accepts_canonical_forms_at_aplicacao_layer() {
12825        // Positive-set sweep through the AplicacaoSpec::validate
12826        // surface (rather than the substrate-side predicate directly)
12827        // — pins every shape the existing test fixtures + the
12828        // checkout-aplicacao example carry, so the gate's accept-set
12829        // matches the substrate's emit-set. Drift between this list
12830        // and `render::tests::wit_world_ref_accepts_canonical_forms`
12831        // surfaces at the substrate layer's positive sweep — one
12832        // source of truth for the rule.
12833        for wit in [
12834            "wasi:http/proxy",
12835            "wasi:keyvalue/store",
12836            "nats:pub-sub",
12837            "kafka:topic",
12838            "custom:exchange",
12839            "pleme:cap/audit",
12840            "wasi:http/proxy@0.2.0",
12841        ] {
12842            // Payload field paired to the dispatched WIT shape so the
12843            // shape-↔-target arm doesn't fire instead of the wit-shape
12844            // arm we're exercising. Routes off the same
12845            // `wit_shape_is_http` / `wit_shape_is_pubsub` /
12846            // `wit_shape_is_store` free functions the production
12847            // `WitContract::is_http` / `is_pubsub` / `is_store`
12848            // methods delegate to (both consult the lifted
12849            // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
12850            // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
12851            // future prefix addition to the routing accept-set
12852            // reaches this test's payload-dispatch arm by
12853            // construction — no per-test-site drift can hide a
12854            // shape-→-target-slot mismatch that would silently
12855            // demote a canonical `:wit` value to the
12856            // `(None, None, None)` capability-only arm and let the
12857            // `AplicacaoSpec::validate` positive sweep pass on a
12858            // shape it should exercise as HTTP / pub-sub / store.
12859            let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
12860                (Some("/x".into()), None, None)
12861            } else if wit_shape_is_pubsub(wit) {
12862                (None, Some("topic.x".into()), None)
12863            } else if wit_shape_is_store(wit) {
12864                (None, None, Some("bucket/$key".into()))
12865            } else {
12866                (None, None, None)
12867            };
12868            let mut s = three_member_spec();
12869            s.contratos.push(WitContract {
12870                de: "payment".into(),
12871                para: "catalog".into(),
12872                wit: wit.into(),
12873                endpoint,
12874                subject,
12875                slot,
12876            });
12877            s.validate()
12878                .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
12879        }
12880    }
12881
12882    #[test]
12883    fn wit_shape_predicates_accept_canonical_prefix_set() {
12884        // Positive-set sweep pinning every prefix in
12885        // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
12886        // WIT_STORE_SHAPE_PREFIXES against the three free-function
12887        // dispatch predicates. The six prefixes are the load-bearing
12888        // routing keys the substrate's WIT-shape dispatch consults
12889        // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
12890        // key/value-store-slot admission); any drift between the
12891        // free-function accept-set and this list surfaces here
12892        // rather than at apply time as a silent
12893        // shape-→-capability-only demotion.
12894        assert!(wit_shape_is_http("wasi:http/proxy"));
12895        assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
12896        assert!(wit_shape_is_http("http:incoming"));
12897
12898        assert!(wit_shape_is_pubsub("nats:pub-sub"));
12899        assert!(wit_shape_is_pubsub("kafka:topic"));
12900
12901        assert!(wit_shape_is_store("wasi:keyvalue/store"));
12902        assert!(wit_shape_is_store("kv:cache/session"));
12903    }
12904
12905    #[test]
12906    fn wit_shape_predicates_reject_uncanonical_forms() {
12907        // Negative-set pin: the six canonical prefixes are
12908        // lowercase-only (mirrors the `is_wit_world_ref` substrate
12909        // predicate's lowercase invariant — see its docstring on the
12910        // "I thought I had L7 HTTP routing, got L4-only" footgun).
12911        // The empty string, an uppercase-prefixed form, a hyphen-
12912        // instead-of-colon typo, and a bare kebab identifier all miss
12913        // every shape arm — reachable-by-construction only via the
12914        // `is_wit_world_ref` gate that admission-checks the `:wit`
12915        // value first, but pinned here so any future
12916        // free-function change (e.g. a case-insensitive
12917        // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
12918        // this unit level.
12919        for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
12920            assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
12921            assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
12922            assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
12923        }
12924    }
12925
12926    #[test]
12927    fn wit_shape_predicates_partition_canonical_set() {
12928        // Every canonical prefix routes to exactly one shape arm —
12929        // the three prefix sets are pairwise disjoint. Pins the
12930        // routing property [`WitContract::target`] relies on: an
12931        // `is_http()` return of `true` guarantees `is_pubsub()` and
12932        // `is_store()` return `false`, so the shape-→-target-slot
12933        // dispatch (endpoint vs subject vs slot) is unambiguous.
12934        // Drift (e.g. a future `"kv:"` moved into the HTTP set
12935        // without removal from the store set) would silently route
12936        // one prefix to two arms and the first-matching-arm order
12937        // becomes load-bearing — this pin surfaces it as a build
12938        // error instead.
12939        for prefix in WIT_HTTP_SHAPE_PREFIXES {
12940            let sample = format!("{prefix}x");
12941            assert!(wit_shape_is_http(&sample));
12942            assert!(!wit_shape_is_pubsub(&sample));
12943            assert!(!wit_shape_is_store(&sample));
12944        }
12945        for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
12946            let sample = format!("{prefix}x");
12947            assert!(!wit_shape_is_http(&sample));
12948            assert!(wit_shape_is_pubsub(&sample));
12949            assert!(!wit_shape_is_store(&sample));
12950        }
12951        for prefix in WIT_STORE_SHAPE_PREFIXES {
12952            let sample = format!("{prefix}x");
12953            assert!(!wit_shape_is_http(&sample));
12954            assert!(!wit_shape_is_pubsub(&sample));
12955            assert!(wit_shape_is_store(&sample));
12956        }
12957    }
12958
12959    #[test]
12960    fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
12961        // Positive pin: [`wit_shape_matches`] is exactly the
12962        // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
12963        // parameterized on the accept-set. Two-prefix accept-set,
12964        // one-prefix accept-set, and empty accept-set (which must
12965        // reject everything, including the empty string — an empty
12966        // `any()` fold returns `false`) all pinned so a future
12967        // reimplementation that swaps `starts_with` for `contains`,
12968        // `==`, or a case-folded comparator surfaces at unit-test
12969        // time.
12970        let two = &["wasi:http/", "http:"];
12971        assert!(wit_shape_matches("wasi:http/proxy", two));
12972        assert!(wit_shape_matches("http:incoming", two));
12973        assert!(!wit_shape_matches("wasi:keyvalue/store", two));
12974
12975        let one = &["nats:"];
12976        assert!(wit_shape_matches("nats:pub-sub", one));
12977        assert!(!wit_shape_matches("kafka:topic", one));
12978
12979        // Empty accept-set matches nothing — the identity element
12980        // for the disjunctive `any()` fold across the prefix set.
12981        // Reachable via a future `wit_shape_is_<name>` const paired
12982        // to a still-empty prefix table on a nascent shape-arm draft.
12983        let empty: &[&str] = &[];
12984        assert!(!wit_shape_matches("wasi:http/proxy", empty));
12985        assert!(!wit_shape_matches("", empty));
12986
12987        // starts_with, not contains: a prefix embedded mid-string
12988        // never matches. Pins the routing invariant [`WitContract::target`]
12989        // relies on (an authored `:wit "custom:wasi:http/"` string
12990        // does not silently route through the HTTP arm just because
12991        // it happens to contain the canonical HTTP prefix).
12992        assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
12993    }
12994
12995    #[test]
12996    fn wit_shape_predicates_delegate_to_wit_shape_matches() {
12997        // Equivalence pin: each per-shape predicate is exactly
12998        // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
12999        // every canonical prefix + the empty string + one negative
13000        // sample against every peer so a future predicate that grew
13001        // its own inline `iter().any(starts_with)` (rather than
13002        // delegating through the lifted combinator) drifts loudly here
13003        // — the peer-const table's contents must agree with the
13004        // predicate's accept-set by construction.
13005        let samples = [
13006            String::new(),
13007            "wasi:http/proxy".to_string(),
13008            "http:incoming".to_string(),
13009            "nats:pub-sub".to_string(),
13010            "kafka:topic".to_string(),
13011            "wasi:keyvalue/store".to_string(),
13012            "kv:cache/session".to_string(),
13013            "custom-shape".to_string(),
13014            "WASI:HTTP/proxy".to_string(),
13015        ];
13016        for wit in &samples {
13017            assert_eq!(
13018                wit_shape_is_http(wit),
13019                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
13020                "wit_shape_is_http drifted from combinator on {wit:?}",
13021            );
13022            assert_eq!(
13023                wit_shape_is_pubsub(wit),
13024                wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
13025                "wit_shape_is_pubsub drifted from combinator on {wit:?}",
13026            );
13027            assert_eq!(
13028                wit_shape_is_store(wit),
13029                wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
13030                "wit_shape_is_store drifted from combinator on {wit:?}",
13031            );
13032        }
13033    }
13034
13035    #[test]
13036    fn wit_contract_shape_methods_delegate_to_free_functions() {
13037        // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
13038        // `is_store` are `&self` conveniences on top of the free
13039        // functions — for every canonical prefix the method's return
13040        // matches its free-function peer. Sweeps the union of the
13041        // three prefix sets so a future method that grew its own
13042        // inline prefix logic (rather than delegating) drifts loudly
13043        // here on the first prefix the free function accepts and the
13044        // method doesn't.
13045        for shape_set in [
13046            WIT_HTTP_SHAPE_PREFIXES,
13047            WIT_PUBSUB_SHAPE_PREFIXES,
13048            WIT_STORE_SHAPE_PREFIXES,
13049        ] {
13050            for prefix in shape_set {
13051                let c = WitContract {
13052                    de: "cart".into(),
13053                    para: "catalog".into(),
13054                    wit: format!("{prefix}x"),
13055                    endpoint: None,
13056                    subject: None,
13057                    slot: None,
13058                };
13059                assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
13060                assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
13061                assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
13062                assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
13063            }
13064        }
13065        // Capability-arm delegation sweep: two representative
13066        // Capability-shaped `:wit` values (a bare non-prefix-matching
13067        // WIT world, the deliberately-shaped empty string
13068        // [`WitContract::is_capability`]'s docstring calls out as
13069        // syntactically Capability). Extends the free-function
13070        // delegation pin onto the fourth arm so a future
13071        // [`WitContract::is_capability`] rewrite that grew an inline
13072        // prefix-set scan (rather than delegating through
13073        // [`wit_shape_is_capability`]) drifts loudly here on the first
13074        // Capability-shaped sample.
13075        for wit in ["custom:capability-only", ""] {
13076            let c = WitContract {
13077                de: "cart".into(),
13078                para: "catalog".into(),
13079                wit: wit.into(),
13080                endpoint: None,
13081                subject: None,
13082                slot: None,
13083            };
13084            assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
13085        }
13086    }
13087
13088    #[test]
13089    fn wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis() {
13090        // 4-way partition-witness pin on the raw `&str` axis: for every
13091        // canonical prefix in the three payload-arm accept-sets,
13092        // exactly one of the four [`wit_shape_is_http`] /
13093        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
13094        // [`wit_shape_is_capability`] free functions returns `true` and
13095        // the other three return `false` — the four-arm partition
13096        // witness that locks the free-function WIT-shape-classifier
13097        // family into a partition of the `:contratos :wit` axis
13098        // load-bearing. Peer of the sibling [`WitContract`]-surface
13099        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
13100        // partition pin — extends the discipline onto the raw `&str`
13101        // axis so any future arm addition (a hypothetical
13102        // `wasi:sockets/*` transport-layer shape, an `oci:*`
13103        // capability-import carrier per the sibling
13104        // [`wit_shape_matches`] docstring's trajectory bullet) that
13105        // landed on one of the payload-arm free functions without
13106        // shrinking [`wit_shape_is_capability`]'s accept-set surfaces
13107        // here as two arms returning `true` simultaneously at
13108        // caixa-core build time rather than a silent per-consumer
13109        // misclassification at renderer emit time.
13110        for shape_set in [
13111            WIT_HTTP_SHAPE_PREFIXES,
13112            WIT_PUBSUB_SHAPE_PREFIXES,
13113            WIT_STORE_SHAPE_PREFIXES,
13114        ] {
13115            for prefix in shape_set {
13116                let wit = format!("{prefix}x");
13117                let hits = [
13118                    wit_shape_is_http(&wit),
13119                    wit_shape_is_pubsub(&wit),
13120                    wit_shape_is_store(&wit),
13121                    wit_shape_is_capability(&wit),
13122                ]
13123                .iter()
13124                .filter(|&&b| b)
13125                .count();
13126                assert_eq!(
13127                    hits,
13128                    1,
13129                    "raw-&str WIT-shape 4-way predicate partition must \
13130                     admit exactly one arm per canonical prefix; got {hits} \
13131                     hits at wit={wit:?} (is_http={}, is_pubsub={}, is_store={}, \
13132                     is_capability={})",
13133                    wit_shape_is_http(&wit),
13134                    wit_shape_is_pubsub(&wit),
13135                    wit_shape_is_store(&wit),
13136                    wit_shape_is_capability(&wit),
13137                );
13138            }
13139        }
13140        // Capability-arm sweep on the raw `&str` axis: two
13141        // representative Capability-shaped `:wit` values (a bare non-
13142        // prefix-matching WIT world, the deliberately-shaped empty
13143        // string the pure classifier still admits per
13144        // [`wit_shape_is_capability`]'s docstring). Both must land on
13145        // the fourth arm exclusively so the partition witness holds
13146        // across the full 4-arm closure on the raw `&str` axis.
13147        for wit in ["custom:capability-only", ""] {
13148            let hits = [
13149                wit_shape_is_http(wit),
13150                wit_shape_is_pubsub(wit),
13151                wit_shape_is_store(wit),
13152                wit_shape_is_capability(wit),
13153            ]
13154            .iter()
13155            .filter(|&&b| b)
13156            .count();
13157            assert_eq!(
13158                hits, 1,
13159                "raw-&str WIT-shape 4-way predicate partition must \
13160                 admit exactly one arm on Capability-shaped wit={wit:?}"
13161            );
13162            assert!(
13163                wit_shape_is_capability(wit),
13164                "wit={wit:?} must project onto the Capability arm on the raw-&str axis"
13165            );
13166        }
13167    }
13168
13169    #[test]
13170    fn wit_shape_is_capability_composes_through_payload_arm_predicate_negation() {
13171        // Composition-witness pin: [`wit_shape_is_capability`] is the
13172        // exact-inverse disjunction of the sibling payload-arm free-
13173        // function trio [`wit_shape_is_http`] / [`wit_shape_is_pubsub`]
13174        // / [`wit_shape_is_store`]. A future reimplementation that
13175        // grew its own prefix-set scan (e.g. inlining a fourth
13176        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does
13177        // not own today) rather than delegating to the sibling trio
13178        // would drift loudly here — the composition contract binds the
13179        // fourth-arm free-function predicate to the exact-inverse of
13180        // the three payload-arm free-function predicates, so any
13181        // rebrand of any prefix-set const flows through
13182        // [`wit_shape_is_capability`] by construction without a
13183        // coordinated per-consumer rewrite. Peer of the sibling
13184        // [`WitContract`]-surface
13185        // [`wit_contract_is_capability_composes_through_shape_predicate_negation`]
13186        // composition pin — extends the discipline onto the raw
13187        // `&str` axis.
13188        let mut cases: Vec<String> = Vec::new();
13189        for shape_set in [
13190            WIT_HTTP_SHAPE_PREFIXES,
13191            WIT_PUBSUB_SHAPE_PREFIXES,
13192            WIT_STORE_SHAPE_PREFIXES,
13193        ] {
13194            for prefix in shape_set {
13195                cases.push(format!("{prefix}x"));
13196            }
13197        }
13198        cases.push("custom:capability-only".to_string());
13199        cases.push(String::new());
13200        for wit in cases {
13201            assert_eq!(
13202                wit_shape_is_capability(&wit),
13203                !wit_shape_is_http(&wit) && !wit_shape_is_pubsub(&wit) && !wit_shape_is_store(&wit),
13204                "wit_shape_is_capability must equal \
13205                 !wit_shape_is_http() && !wit_shape_is_pubsub() && !wit_shape_is_store() \
13206                 at wit={wit:?}"
13207            );
13208        }
13209    }
13210
13211    #[test]
13212    fn wit_shape_classifier_family_is_const_fn() {
13213        // Fail-before-pass-after pin on the 4-arm free-function WIT-
13214        // shape classifier family's `const`-eval posture. Each of the
13215        // four peer classifiers ([`wit_shape_is_http`] /
13216        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
13217        // [`wit_shape_is_capability`]) and the underlying combinator
13218        // [`wit_shape_matches`] must be `pub const fn` — any future
13219        // accidental downgrade to non-`const` fails the `const fn`
13220        // wrappers below at caixa-core build time with E0015
13221        // (`cannot call non-const function`), strictly stronger than
13222        // a runtime `assert!` and strictly stronger than the module-
13223        // scope `const _: () = assert!(…)` pins immediately after the
13224        // classifier declarations (those anchor specific accept-set
13225        // truth-table entries; this pin anchors the `const` posture
13226        // itself via `const fn` wrappers that are only well-formed
13227        // when the callee is itself `const fn`).
13228        //
13229        // Verified fail-before-pass-after by locally reverting
13230        // `pub const fn` → `pub fn` on each classifier and observing
13231        // E0015 at every corresponding wrapper call site (build
13232        // error, no test-time surface), then restoring `pub const fn`
13233        // and observing the pin pass at test time. Peer of the
13234        // sibling M3
13235        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
13236        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
13237        // M2
13238        // [`child_spec_restart_accessor_is_const_fn`] /
13239        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
13240        // and M3
13241        // [`placement_estrategia_accessor_is_const_fn`] /
13242        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
13243        // sibling `const`-eval-surface-pass axes.
13244        const fn matches_via_const_fn(wit: &str, prefixes: &[&str]) -> bool {
13245            wit_shape_matches(wit, prefixes)
13246        }
13247        const fn http_via_const_fn(wit: &str) -> bool {
13248            wit_shape_is_http(wit)
13249        }
13250        const fn pubsub_via_const_fn(wit: &str) -> bool {
13251            wit_shape_is_pubsub(wit)
13252        }
13253        const fn store_via_const_fn(wit: &str) -> bool {
13254            wit_shape_is_store(wit)
13255        }
13256        const fn capability_via_const_fn(wit: &str) -> bool {
13257            wit_shape_is_capability(wit)
13258        }
13259        // Sweep one canonical accept-set sample per arm plus the
13260        // payload-less/empty capability samples, asserting the
13261        // wrapper and direct dispatches agree byte-for-byte across
13262        // the closed 4-arm partition.
13263        let cases: [(&str, bool, bool, bool, bool); 6] = [
13264            ("wasi:http/proxy", true, false, false, false),
13265            ("http:incoming", true, false, false, false),
13266            ("nats:events", false, true, false, false),
13267            ("kafka:topic", false, true, false, false),
13268            ("wasi:keyvalue/store", false, false, true, false),
13269            ("kv:cache", false, false, true, false),
13270        ];
13271        for (wit, is_http, is_pubsub, is_store, _is_capability) in cases {
13272            assert_eq!(
13273                matches_via_const_fn(wit, WIT_HTTP_SHAPE_PREFIXES),
13274                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
13275                "wit_shape_matches const fn wrapper disagrees at wit={wit:?}",
13276            );
13277            assert_eq!(http_via_const_fn(wit), wit_shape_is_http(wit));
13278            assert_eq!(pubsub_via_const_fn(wit), wit_shape_is_pubsub(wit));
13279            assert_eq!(store_via_const_fn(wit), wit_shape_is_store(wit));
13280            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
13281            assert_eq!(wit_shape_is_http(wit), is_http);
13282            assert_eq!(wit_shape_is_pubsub(wit), is_pubsub);
13283            assert_eq!(wit_shape_is_store(wit), is_store);
13284        }
13285        // Payload-less capability arm (the 4th partition arm).
13286        let capability_samples: [&str; 3] =
13287            ["wasi:filesystem/preopens", "custom:capability-only", ""];
13288        for wit in capability_samples {
13289            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
13290            assert!(wit_shape_is_capability(wit));
13291            assert!(!wit_shape_is_http(wit));
13292            assert!(!wit_shape_is_pubsub(wit));
13293            assert!(!wit_shape_is_store(wit));
13294        }
13295    }
13296
13297    #[test]
13298    fn wit_shape_matches_composes_through_bytes_starts_with_across_boundary_lengths() {
13299        // Composition-witness pin: [`wit_shape_matches`] agrees with
13300        // the reference `prefixes.iter().any(|p| wit.starts_with(p))`
13301        // dispatch (the prior non-`const` implementation) across
13302        // boundary lengths — empty `wit`, empty prefix, one-byte
13303        // slack, prefix longer than `wit`, one-byte trailing slack.
13304        // The rewrite to a byte-level manual starts_with loop (the
13305        // enabler for the `pub const fn` posture) must not change any
13306        // truth-table entry on the canonical accept-set — this pin
13307        // sweeps a targeted boundary corpus and asserts byte-for-byte
13308        // agreement, locking the const-fn rewrite's semantics against
13309        // the prior iterator body by construction.
13310        let prefixes = &["wasi:http/", "http:"][..];
13311        let cases: [(&str, bool); 12] = [
13312            ("wasi:http/proxy", true),
13313            ("wasi:http/", true), // exact-length match on prefix
13314            ("wasi:http", false), // one byte short
13315            ("http:", true),
13316            ("http:incoming", true),
13317            ("http", false), // one byte short
13318            ("", false),
13319            ("wasi:https/proxy", false),
13320            ("nats:events", false),
13321            ("HTTPS:", false), // uppercase — no case-fold in classifier
13322            ("wasi:HTTP/proxy", false),
13323            ("wasi:http", false),
13324        ];
13325        for (wit, expected) in cases {
13326            assert_eq!(
13327                wit_shape_matches(wit, prefixes),
13328                expected,
13329                "wit_shape_matches disagrees with reference at wit={wit:?}",
13330            );
13331            // Byte-equal to the iterator body it replaced.
13332            let via_iter = prefixes.iter().any(|p| wit.starts_with(p));
13333            assert_eq!(
13334                wit_shape_matches(wit, prefixes),
13335                via_iter,
13336                "wit_shape_matches must byte-equal iter().any(starts_with) at wit={wit:?}",
13337            );
13338        }
13339        // Empty prefix set → always false regardless of `wit`.
13340        let empty: &[&str] = &[];
13341        assert!(!wit_shape_matches("", empty));
13342        assert!(!wit_shape_matches("wasi:http/proxy", empty));
13343        // Empty prefix inside a non-empty set → always true (every
13344        // string starts with the empty string, matching the
13345        // iterator body's semantics on `str::starts_with("")`).
13346        let contains_empty: &[&str] = &["nats:", ""];
13347        assert!(wit_shape_matches("", contains_empty));
13348        assert!(wit_shape_matches("wasi:http/proxy", contains_empty));
13349    }
13350
13351    #[test]
13352    fn wit_contract_is_capability_partitions_the_wit_shape_space() {
13353        // 4-way partition-witness pin: for every canonical prefix in
13354        // the payload-arm accept-sets, exactly one of the four
13355        // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
13356        // [`WitContract::is_store`] / [`WitContract::is_capability`]
13357        // predicates returns `true` and the other three return `false`
13358        // — the four-arm partition witness that locks the substrate's
13359        // WIT-shape-space closure on the pre-projection axis load-
13360        // bearing. A future arm addition (a hypothetical fourth
13361        // payload-shape prefix set, a `wasi:sockets/*` transport-layer
13362        // shape) that landed on one of the payload-arm predicates
13363        // without shrinking [`WitContract::is_capability`]'s accept-set
13364        // would surface here as two arms returning `true` simultaneously
13365        // — a partition-witness break the pin catches at caixa-core
13366        // build time rather than a silent per-consumer misclassification
13367        // at renderer emit time. Peer of the sibling `WitTarget`-side
13368        // [`tests::wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`]
13369        // partition-witness pin on the post-projection payload-scalar
13370        // arm-set — extends the discipline onto the pre-projection
13371        // 4-arm shape-space.
13372        for shape_set in [
13373            WIT_HTTP_SHAPE_PREFIXES,
13374            WIT_PUBSUB_SHAPE_PREFIXES,
13375            WIT_STORE_SHAPE_PREFIXES,
13376        ] {
13377            for prefix in shape_set {
13378                let c = WitContract {
13379                    de: "cart".into(),
13380                    para: "catalog".into(),
13381                    wit: format!("{prefix}x"),
13382                    endpoint: None,
13383                    subject: None,
13384                    slot: None,
13385                };
13386                let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
13387                    .iter()
13388                    .filter(|&&b| b)
13389                    .count();
13390                assert_eq!(
13391                    hits,
13392                    1,
13393                    "WitContract WIT-shape 4-way predicate partition must \
13394                     admit exactly one arm per canonical prefix; got {hits} \
13395                     hits at wit={:?} (is_http={}, is_pubsub={}, is_store={}, \
13396                     is_capability={})",
13397                    c.wit,
13398                    c.is_http(),
13399                    c.is_pubsub(),
13400                    c.is_store(),
13401                    c.is_capability(),
13402                );
13403            }
13404        }
13405        // Capability-arm sweep: two representative capability shapes
13406        // (a bare WIT world outside the three payload-arm prefix sets,
13407        // and the deliberately-shaped empty string that
13408        // [`crate::render::is_wit_world_ref`] rejects at
13409        // [`WitContract::target`] time but which the pure classifier
13410        // still admits — see the method docstring's "purely syntactic
13411        // classification" note). Both must land on the fourth arm
13412        // exclusively, so the partition witness holds across the full
13413        // 4-arm closure.
13414        for wit in ["custom:capability-only", ""] {
13415            let c = WitContract {
13416                de: "cart".into(),
13417                para: "catalog".into(),
13418                wit: wit.into(),
13419                endpoint: None,
13420                subject: None,
13421                slot: None,
13422            };
13423            let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
13424                .iter()
13425                .filter(|&&b| b)
13426                .count();
13427            assert_eq!(
13428                hits, 1,
13429                "WitContract WIT-shape 4-way predicate partition must \
13430                 admit exactly one arm on Capability-shaped wit={wit:?}"
13431            );
13432            assert!(
13433                c.is_capability(),
13434                "wit={wit:?} must project onto the Capability arm"
13435            );
13436        }
13437    }
13438
13439    #[test]
13440    fn wit_contract_is_capability_composes_through_shape_predicate_negation() {
13441        // Composition-witness pin: [`WitContract::is_capability`] is the
13442        // exact-inverse disjunction of the sibling payload-arm predicate
13443        // trio [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
13444        // [`WitContract::is_store`]. A future reimplementation that
13445        // grew its own prefix-set scan (e.g. inlining a fourth
13446        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does not
13447        // own today) rather than delegating to the sibling trio would
13448        // drift loudly here — the composition contract binds the
13449        // fourth-arm predicate to the exact-inverse of the three
13450        // payload-arm predicates, so any rebrand of any prefix-set const
13451        // flows through this method by construction without a
13452        // coordinated per-consumer rewrite. Sweeps the union of the
13453        // three payload-arm prefix sets plus two Capability-shaped
13454        // shapes (a bare non-prefix-matching WIT world, the deliberately-
13455        // empty string the pure classifier still admits per the method
13456        // docstring's "purely syntactic classification" note).
13457        let mut cases: Vec<String> = Vec::new();
13458        for shape_set in [
13459            WIT_HTTP_SHAPE_PREFIXES,
13460            WIT_PUBSUB_SHAPE_PREFIXES,
13461            WIT_STORE_SHAPE_PREFIXES,
13462        ] {
13463            for prefix in shape_set {
13464                cases.push(format!("{prefix}x"));
13465            }
13466        }
13467        cases.push("custom:capability-only".to_string());
13468        cases.push(String::new());
13469        for wit in cases {
13470            let c = WitContract {
13471                de: "cart".into(),
13472                para: "catalog".into(),
13473                wit: wit.clone(),
13474                endpoint: None,
13475                subject: None,
13476                slot: None,
13477            };
13478            assert_eq!(
13479                c.is_capability(),
13480                !c.is_http() && !c.is_pubsub() && !c.is_store(),
13481                "WitContract::is_capability must equal \
13482                 !is_http() && !is_pubsub() && !is_store() at wit={wit:?}"
13483            );
13484        }
13485    }
13486
13487    #[test]
13488    fn wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant() {
13489        // Cross-projection-witness pin: whenever [`WitContract::target`]
13490        // succeeds, the pre-projection [`WitContract::is_capability`]
13491        // classification agrees with the post-projection
13492        // [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
13493        // predicate — the 4-arm typed partition on the substrate's
13494        // typed-view surface (7f6aa98 IsVariant lift) and the peer 4-arm
13495        // partition on the pre-projection axis line up by construction.
13496        // A future divergence between the two axes (a peer
13497        // [`WitTarget`] variant addition that landed on the typed-view
13498        // surface without a peer prefix-set + [`WitContract`] predicate
13499        // extension, or vice versa) would surface here at caixa-core
13500        // build time rather than a silent per-consumer split at renderer
13501        // emit time. Peer of the sibling pre-/post-projection
13502        // agreement pins the payload-carrier trio
13503        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
13504        // [`WitContract::slot`] on pre-projection; [`WitTarget::http_endpoint`]
13505        // / [`WitTarget::pubsub_subject`] / [`WitTarget::store_slot`] on
13506        // post-projection — b11bb49 trio lift) already carry across the
13507        // three payload arms — this pin closes the pair on the fourth
13508        // payload-less arm.
13509        let http = WitContract {
13510            de: "cart".into(),
13511            para: "catalog".into(),
13512            wit: "wasi:http/proxy".into(),
13513            endpoint: Some("/x".into()),
13514            subject: None,
13515            slot: None,
13516        };
13517        assert!(!http.is_capability());
13518        assert!(!http.target().unwrap().is_capability());
13519
13520        let nats = WitContract {
13521            de: "cart".into(),
13522            para: "catalog".into(),
13523            wit: "nats:pub-sub".into(),
13524            endpoint: None,
13525            subject: Some("events.x".into()),
13526            slot: None,
13527        };
13528        assert!(!nats.is_capability());
13529        assert!(!nats.target().unwrap().is_capability());
13530
13531        let kv = WitContract {
13532            de: "cart".into(),
13533            para: "catalog".into(),
13534            wit: "wasi:keyvalue/store".into(),
13535            endpoint: None,
13536            subject: None,
13537            slot: Some("checkout/$orderId".into()),
13538        };
13539        assert!(!kv.is_capability());
13540        assert!(!kv.target().unwrap().is_capability());
13541
13542        let cap = WitContract {
13543            de: "cart".into(),
13544            para: "catalog".into(),
13545            wit: "custom:capability-only".into(),
13546            endpoint: None,
13547            subject: None,
13548            slot: None,
13549        };
13550        assert!(cap.is_capability());
13551        assert!(cap.target().unwrap().is_capability());
13552    }
13553
13554    #[test]
13555    fn wit_contract_pre_projection_accessor_family_is_const_fn() {
13556        // Fail-before-pass-after pin on the [`WitContract`] pre-
13557        // projection accessor family's `const`-eval-surface posture.
13558        // Each of the three per-`:contratos` byte-string scalar
13559        // accessors ([`WitContract::source`] / [`WitContract::destination`]
13560        // / [`WitContract::world_ref`], each projecting through
13561        // `String::as_str` — const-stable since Rust 1.87, well within
13562        // the workspace MSRV) and each of the four peer WIT-shape
13563        // predicates ([`WitContract::is_http`] /
13564        // [`WitContract::is_pubsub`] / [`WitContract::is_store`] /
13565        // [`WitContract::is_capability`], each composing
13566        // `wit_shape_is_<arm>(self.world_ref())` on the `pub const fn`
13567        // free-function classifier family the sibling
13568        // [`wit_shape_classifier_family_is_const_fn`] pin already
13569        // anchors on the raw `&str → bool` axis) must be `pub const fn`
13570        // — any future accidental downgrade to non-`const` fails the
13571        // `const fn` wrappers below at caixa-core build time with E0015
13572        // (`cannot call non-const function`), strictly stronger than a
13573        // runtime `assert!` and strictly stronger than a
13574        // module-scope `const _: () = assert!(…)` pin (which cannot be
13575        // formed on a `&WitContract` fixture because the type's
13576        // `String` / `Option<String>` carriers rule out `const`-context
13577        // construction; the `const fn` wrapper is the load-bearing
13578        // shape that side-steps the destructor-in-const restriction on
13579        // the value axis while still pinning the `const`-fn posture on
13580        // the callee).
13581        //
13582        // Peer of the sibling free-function classifier pin
13583        // [`wit_shape_classifier_family_is_const_fn`] (d46420c) on the
13584        // raw `&str → bool` axis — this pin extends the same
13585        // `const`-eval-surface discipline onto the peer method surface
13586        // that composes through those free-function classifiers, and
13587        // simultaneously onto the underlying per-`:contratos`
13588        // byte-string scalar-accessor trio each predicate reads
13589        // through. Sibling of the peer M3
13590        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
13591        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
13592        // M2
13593        // [`child_spec_restart_accessor_is_const_fn`] /
13594        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
13595        // and M3
13596        // [`placement_estrategia_accessor_is_const_fn`] /
13597        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
13598        // sibling `const`-eval-surface-pass axes.
13599        const fn source_via_const_fn(c: &WitContract) -> &str {
13600            c.source()
13601        }
13602        const fn destination_via_const_fn(c: &WitContract) -> &str {
13603            c.destination()
13604        }
13605        const fn world_ref_via_const_fn(c: &WitContract) -> &str {
13606            c.world_ref()
13607        }
13608        const fn is_http_via_const_fn(c: &WitContract) -> bool {
13609            c.is_http()
13610        }
13611        const fn is_pubsub_via_const_fn(c: &WitContract) -> bool {
13612            c.is_pubsub()
13613        }
13614        const fn is_store_via_const_fn(c: &WitContract) -> bool {
13615            c.is_store()
13616        }
13617        const fn is_capability_via_const_fn(c: &WitContract) -> bool {
13618            c.is_capability()
13619        }
13620        // Sweep one canonical accept-set sample per WIT-shape arm plus
13621        // a payload-less capability sample, asserting the wrapper and
13622        // direct dispatches agree byte-for-byte across the closed
13623        // 4-arm partition on both the scalar-accessor trio and the
13624        // WIT-shape-predicate family.
13625        for (wit, is_http, is_pubsub, is_store, is_capability) in [
13626            ("wasi:http/proxy", true, false, false, false),
13627            ("http:incoming", true, false, false, false),
13628            ("nats:events", false, true, false, false),
13629            ("kafka:topic", false, true, false, false),
13630            ("wasi:keyvalue/store", false, false, true, false),
13631            ("kv:cache", false, false, true, false),
13632            ("custom:capability-only", false, false, false, true),
13633            ("", false, false, false, true),
13634        ] {
13635            let c = WitContract {
13636                de: "cart".into(),
13637                para: "catalog".into(),
13638                wit: wit.into(),
13639                endpoint: None,
13640                subject: None,
13641                slot: None,
13642            };
13643            assert_eq!(source_via_const_fn(&c), c.source());
13644            assert_eq!(destination_via_const_fn(&c), c.destination());
13645            assert_eq!(world_ref_via_const_fn(&c), c.world_ref());
13646            assert_eq!(is_http_via_const_fn(&c), c.is_http());
13647            assert_eq!(is_pubsub_via_const_fn(&c), c.is_pubsub());
13648            assert_eq!(is_store_via_const_fn(&c), c.is_store());
13649            assert_eq!(is_capability_via_const_fn(&c), c.is_capability());
13650            assert_eq!(c.source(), "cart");
13651            assert_eq!(c.destination(), "catalog");
13652            assert_eq!(c.world_ref(), wit);
13653            assert_eq!(c.is_http(), is_http);
13654            assert_eq!(c.is_pubsub(), is_pubsub);
13655            assert_eq!(c.is_store(), is_store);
13656            assert_eq!(c.is_capability(), is_capability);
13657        }
13658    }
13659
13660    #[test]
13661    fn wit_contract_identity_projection_accessor_is_const_fn() {
13662        // Fail-before-pass-after pin on the [`WitContract::identity`]
13663        // six-arm composite-projection accessor's `const`-eval-surface
13664        // posture. The accessor projects the typed edge's six identity
13665        // arms (`:de` / `:para` / `:wit` / `:endpoint` / `:subject` /
13666        // `:slot`) as a borrowed [`ContratoIdentity<'_>`] six-tuple —
13667        // every callee is itself `pub const fn` ([`WitContract::source`]
13668        // / [`WitContract::destination`] / [`WitContract::world_ref`]
13669        // through `String::as_str`, const-stable since Rust 1.87;
13670        // [`WitContract::endpoint`] / [`WitContract::subject`] /
13671        // [`WitContract::slot`] through the sibling `match &self
13672        // .<field> { Some(s) => Some(s.as_str()), None => None }` shape
13673        // 0650f64 closed the const-eval surface on) and the tuple
13674        // constructor from borrowed-reference / `Option`-of-borrowed-
13675        // reference arms is trivially const. Any future accidental
13676        // downgrade fails the `identity_via_const_fn` wrapper at
13677        // caixa-core build time with E0015 (`cannot call non-const
13678        // method`), strictly stronger than a runtime `assert!` and
13679        // strictly stronger than a module-scope `const _: () =
13680        // assert!(…)` pin (which cannot be formed on a `&WitContract`
13681        // fixture because the type's `String` / `Option<String>`
13682        // carriers rule out `const`-context value construction; the
13683        // `const fn` wrapper is the load-bearing shape that side-steps
13684        // the destructor-in-const restriction on the value axis while
13685        // still pinning the `const`-fn posture on the callee — mirror
13686        // of the sibling
13687        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
13688        // pin's discipline verbatim on the peer scalar-accessor
13689        // surface).
13690        //
13691        // Peer of the sibling
13692        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
13693        // (279823b) pin on the six per-`:contratos` scalar-accessor
13694        // callees this composite-projection reads through — where that
13695        // pin anchors the const-eval surface at the six individual
13696        // scalar-accessor arms, this pin extends the same posture onto
13697        // the composite six-tuple projection every consumer that dedups
13698        // typed edges on the [`ContratoIdentity`] axis keys off (the
13699        // [`AplicacaoSpec::validate`]-side duplicate-`:contratos`
13700        // scanner + its BTreeMap dedup key; a future per-Aplicacao CR
13701        // materializer's per-edge identity-based admission webhook; a
13702        // future L7 policy-emitter that shards CNPs by identity-tuple
13703        // rather than by name). Same fail-before-pass-after wrapper
13704        // discipline as the peer M2 / M3 accessor-family pins on the
13705        // sibling `const`-eval-surface passes.
13706        const fn identity_via_const_fn(c: &WitContract) -> ContratoIdentity<'_> {
13707            c.identity()
13708        }
13709        // Sweep one canonical WIT-shape sample per payload-carrier arm
13710        // plus a payload-less capability sample so the pin exercises
13711        // both `Some(_)`-carrying and `None`-carrying arms on all three
13712        // `Option<String>` payload-carrier axes (`:endpoint` / `:subject`
13713        // / `:slot`) — every wrapper dispatch must agree byte-for-byte
13714        // with the direct method call on every arm of the closed WIT-
13715        // shape partition.
13716        for (wit, endpoint, subject, slot) in [
13717            ("wasi:http/proxy", Some("/checkout"), None, None),
13718            ("http:incoming", Some("/api"), None, None),
13719            ("nats:events", None, Some("orders.placed"), None),
13720            ("kafka:topic", None, Some("orders.stream"), None),
13721            ("wasi:keyvalue/store", None, None, Some("carts/{id}")),
13722            ("kv:cache", None, None, Some("session/{token}")),
13723            ("custom:capability-only", None, None, None),
13724        ] {
13725            let c = WitContract {
13726                de: "cart".into(),
13727                para: "catalog".into(),
13728                wit: wit.into(),
13729                endpoint: endpoint.map(str::to_string),
13730                subject: subject.map(str::to_string),
13731                slot: slot.map(str::to_string),
13732            };
13733            assert_eq!(identity_via_const_fn(&c), c.identity());
13734            assert_eq!(
13735                c.identity(),
13736                ("cart", "catalog", wit, endpoint, subject, slot,),
13737            );
13738        }
13739    }
13740
13741    #[test]
13742    fn m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn() {
13743        // Fail-before-pass-after pin on the four M3 mesh-slot
13744        // `String → &str` scalar accessors ([`Membro::nome`] /
13745        // [`Membro::versao_requirement`] on the per-`:membros` axis,
13746        // [`Entrada::hostname`] / [`Entrada::destination`] on the
13747        // per-`:entrada` axis) — each projects the typed slot's
13748        // [`String`] storage through the `pub const fn`
13749        // [`String::as_str`] (const-stable since Rust 1.87, well
13750        // within the workspace MSRV) and any future accidental
13751        // downgrade to non-`const` fails the corresponding
13752        // `<name>_via_const_fn` wrapper at caixa-core build time with
13753        // E0015 (`cannot call non-const method`), strictly stronger
13754        // than a runtime `assert!` and strictly stronger than a
13755        // module-scope `const _: () = assert!(…)` pin (which cannot
13756        // be formed on `&Membro` / `&Entrada` fixtures because the
13757        // types' `String` carriers rule out `const`-context value
13758        // construction; the `const fn` wrapper is the load-bearing
13759        // shape that side-steps the destructor-in-const restriction
13760        // on the value axis while still pinning the `const`-fn
13761        // posture on the callee — mirror of the sibling
13762        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
13763        // (279823b) pin on the per-`:contratos` axis). Peer of the
13764        // sibling per-M2/M3/universal-axis `String → &str` accessor
13765        // family pins on the sibling `const`-eval-surface passes
13766        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
13767        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
13768        // typed-newtype wrapper,
13769        // [`crate::supervisor::ChildSpec::nome`] /
13770        // [`crate::supervisor::ChildSpec::versao_requirement`] at the
13771        // M2 supervisor-tree axis,
13772        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
13773        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
13774        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
13775        // axis, and the sibling per-`:contratos`
13776        // [`WitContract::source`] / [`WitContract::destination`] /
13777        // [`WitContract::world_ref`] trio at 279823b).
13778        const fn membro_nome_via_const_fn(m: &Membro) -> &str {
13779            m.nome()
13780        }
13781        const fn membro_versao_via_const_fn(m: &Membro) -> &str {
13782            m.versao_requirement()
13783        }
13784        const fn entrada_hostname_via_const_fn(e: &Entrada) -> &str {
13785            e.hostname()
13786        }
13787        const fn entrada_destination_via_const_fn(e: &Entrada) -> &str {
13788            e.destination()
13789        }
13790        for (caixa, versao) in [
13791            ("cart", "^0.1"),
13792            ("catalog-v2", "~0.2.3"),
13793            ("checkout", "*"),
13794        ] {
13795            let m = Membro {
13796                caixa: caixa.into(),
13797                versao: versao.into(),
13798            };
13799            assert_eq!(membro_nome_via_const_fn(&m), m.nome());
13800            assert_eq!(membro_versao_via_const_fn(&m), m.versao_requirement());
13801            assert_eq!(m.nome(), caixa);
13802            assert_eq!(m.versao_requirement(), versao);
13803        }
13804        for (host, para) in [
13805            ("cart.example.com", "cart"),
13806            ("api.checkout.io", "checkout"),
13807        ] {
13808            let e = Entrada {
13809                host: host.into(),
13810                para: para.into(),
13811                paths: vec![],
13812                port: DEFAULT_SERVICO_PORT,
13813            };
13814            assert_eq!(entrada_hostname_via_const_fn(&e), e.hostname());
13815            assert_eq!(entrada_destination_via_const_fn(&e), e.destination());
13816            assert_eq!(e.hostname(), host);
13817            assert_eq!(e.destination(), para);
13818        }
13819    }
13820
13821    #[test]
13822    fn m3_option_string_scalar_accessor_family_is_const_fn() {
13823        // Fail-before-pass-after pin on the five M3 mesh-slot
13824        // `Option<String> → Option<&str>` scalar accessors
13825        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
13826        // [`WitContract::slot`] on the per-`:contratos` HTTP /
13827        // pub-sub / key-value payload-carrier trio,
13828        // [`Placement::shard_key`] / [`Placement::affinity`] on the
13829        // per-`:placement` Akka-sharding-key + Adaptive-compression-
13830        // hint pair). Each accessor destructures the typed slot's
13831        // `Option<String>` storage through the `match &self.<field> {
13832        // Some(s) => Some(s.as_str()), None => None }` shape —
13833        // routing through [`String::as_str`] (const-stable since Rust
13834        // 1.87, well within the workspace MSRV) rather than the
13835        // non-const [`Option::as_deref`] the pre-lift bodies carried
13836        // — and any future accidental downgrade to non-`const` fails
13837        // the corresponding `<name>_via_const_fn` wrapper at
13838        // caixa-core build time with E0015 (`cannot call non-const
13839        // method`), strictly stronger than a runtime `assert!` and
13840        // strictly stronger than a module-scope `const _: () =
13841        // assert!(…)` pin (which cannot be formed on `&WitContract`
13842        // / `&Placement` fixtures because the types' `String` /
13843        // `Option<String>` carriers rule out `const`-context value
13844        // construction; the `const fn` wrapper is the load-bearing
13845        // shape that side-steps the destructor-in-const restriction
13846        // on the value axis while still pinning the `const`-fn
13847        // posture on the callee — mirror of the sibling
13848        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
13849        // (279823b) and
13850        // [`m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn`]
13851        // (29c5d7e) pins on the peer `String → &str` axes at the same
13852        // structs).
13853        //
13854        // Peer of the sibling per-`Caixa` `Option<String> →
13855        // Option<&str>` accessor family pin
13856        // [`crate::manifest::tests::caixa_option_string_scalar_accessor_family_is_const_fn`]
13857        // on the top-level manifest's optional universal-axis surface
13858        // (`:licenca` / `:repositorio` / `:descricao` / `:edicao` /
13859        // `:restart-window`).
13860        const fn wit_endpoint_via_const_fn(w: &WitContract) -> Option<&str> {
13861            w.endpoint()
13862        }
13863        const fn wit_subject_via_const_fn(w: &WitContract) -> Option<&str> {
13864            w.subject()
13865        }
13866        const fn wit_slot_via_const_fn(w: &WitContract) -> Option<&str> {
13867            w.slot()
13868        }
13869        const fn placement_shard_key_via_const_fn(p: &Placement) -> Option<&str> {
13870            p.shard_key()
13871        }
13872        const fn placement_affinity_via_const_fn(p: &Placement) -> Option<&str> {
13873            p.affinity()
13874        }
13875        // Sweep every closed shape-arm partition on the
13876        // per-`:contratos` payload-carrier trio: HTTP (`:endpoint`
13877        // Some, sibling pair None), pub-sub (`:subject` Some, sibling
13878        // pair None), key-value (`:slot` Some, sibling pair None),
13879        // and Capability (all three None) so each accessor's
13880        // Some/None arm carries a pin through the const dispatch.
13881        for (wit, endpoint, subject, slot) in [
13882            ("wasi:http/proxy", Some("/api"), None, None),
13883            ("nats:pub-sub", None, Some("orders.paid"), None),
13884            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
13885            ("custom:capability-only", None, None, None),
13886        ] {
13887            let c = WitContract {
13888                de: "cart".into(),
13889                para: "catalog".into(),
13890                wit: wit.into(),
13891                endpoint: endpoint.map(str::to_string),
13892                subject: subject.map(str::to_string),
13893                slot: slot.map(str::to_string),
13894            };
13895            assert_eq!(wit_endpoint_via_const_fn(&c), c.endpoint());
13896            assert_eq!(wit_subject_via_const_fn(&c), c.subject());
13897            assert_eq!(wit_slot_via_const_fn(&c), c.slot());
13898            assert_eq!(c.endpoint(), endpoint);
13899            assert_eq!(c.subject(), subject);
13900            assert_eq!(c.slot(), slot);
13901        }
13902        // Sweep both `Some`/`None` arms on each per-`:placement`
13903        // optional-scalar so the shard-key + affinity pair carries a
13904        // const-dispatch pin on both arms.
13905        for (shard_key, affinity) in [
13906            (Some("tenantId"), Some("data-locality")),
13907            (Some("$tenantId"), None),
13908            (None, Some("low-latency")),
13909            (None, None),
13910        ] {
13911            let p = Placement {
13912                estrategia: PlacementStrategy::default(),
13913                clusters: vec![],
13914                affinity: affinity.map(str::to_string),
13915                shard_key: shard_key.map(str::to_string),
13916            };
13917            assert_eq!(placement_shard_key_via_const_fn(&p), p.shard_key());
13918            assert_eq!(placement_affinity_via_const_fn(&p), p.affinity());
13919            assert_eq!(p.shard_key(), shard_key);
13920            assert_eq!(p.affinity(), affinity);
13921        }
13922    }
13923
13924    #[test]
13925    fn m3_placement_entrada_slice_return_accessor_pair_is_const_fn() {
13926        // Fail-before-pass-after pin on the two M3-mesh-slot inner-
13927        // composite `Vec → &[String]` slice-return accessors on
13928        // [`Placement::clusters`] and [`Entrada::paths`]. Each
13929        // destructures the typed slot's `Vec<String>` storage through
13930        // the `pub const fn` [`Vec::as_slice`] (const-stable since Rust
13931        // 1.66, well within the workspace MSRV) — any future accidental
13932        // downgrade to non-`const` fails the corresponding
13933        // `<name>_via_const_fn` wrapper at caixa-core build time with
13934        // E0015 (`cannot call non-const method`), strictly stronger
13935        // than a runtime `assert!`. Sibling of the peer
13936        // [`m3_aplicacao_spec_reference_return_accessor_family_is_const_fn`]
13937        // pin on the outer-`AplicacaoSpec` reference-return family
13938        // (`:membros` / `:contratos` slice-return + `:politicas` /
13939        // `:placement` / `:entrada` composite-reference), and of the
13940        // peer M2 slice-return axis pins
13941        // [`crate::supervisor::tests::supervisor_children_slice_return_accessor_is_const_fn`]
13942        // (on `SupervisorSpec::children`) and
13943        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
13944        // (on `UpgradeFromEntry::instructions`). Together the four
13945        // pins close the last unlifted reference-return accessor
13946        // family across the substrate primitive.
13947        const fn placement_clusters_via_const_fn(p: &Placement) -> &[String] {
13948            p.clusters()
13949        }
13950        const fn entrada_paths_via_const_fn(e: &Entrada) -> &[String] {
13951            e.paths()
13952        }
13953        // Sweep both the empty-Vec (no author-declared entries) and
13954        // the populated-Vec arms on every slice-return accessor so
13955        // each carries a const-dispatch pin on both arms.
13956        let p_empty = Placement {
13957            estrategia: PlacementStrategy::default(),
13958            clusters: vec![],
13959            affinity: None,
13960            shard_key: None,
13961        };
13962        let p_full = Placement {
13963            estrategia: PlacementStrategy::default(),
13964            clusters: vec!["prod-a".into(), "prod-b".into()],
13965            affinity: None,
13966            shard_key: None,
13967        };
13968        assert_eq!(
13969            placement_clusters_via_const_fn(&p_empty),
13970            p_empty.clusters()
13971        );
13972        assert_eq!(placement_clusters_via_const_fn(&p_full), p_full.clusters());
13973        assert!(p_empty.clusters().is_empty());
13974        assert_eq!(p_full.clusters(), &["prod-a", "prod-b"]);
13975        let e_empty = Entrada {
13976            host: "web.example.com".into(),
13977            para: "web".into(),
13978            paths: vec![],
13979            port: DEFAULT_SERVICO_PORT,
13980        };
13981        let e_full = Entrada {
13982            host: "web.example.com".into(),
13983            para: "web".into(),
13984            paths: vec!["/api".into(), "/health".into()],
13985            port: DEFAULT_SERVICO_PORT,
13986        };
13987        assert_eq!(entrada_paths_via_const_fn(&e_empty), e_empty.paths());
13988        assert_eq!(entrada_paths_via_const_fn(&e_full), e_full.paths());
13989        assert!(e_empty.paths().is_empty());
13990        assert_eq!(e_full.paths(), &["/api", "/health"]);
13991    }
13992
13993    #[test]
13994    fn m3_aplicacao_spec_reference_return_accessor_family_is_const_fn() {
13995        // Fail-before-pass-after pin on the five outer-`AplicacaoSpec`
13996        // reference-return accessors — the two `Vec → &[T]` slice-
13997        // return accessors on [`AplicacaoSpec::membros`] and
13998        // [`AplicacaoSpec::contratos`] (each routes through the
13999        // `pub const fn` [`Vec::as_slice`], const-stable since Rust
14000        // 1.66), the two `&Composite` composite-reference accessors
14001        // on [`AplicacaoSpec::politicas`] and
14002        // [`AplicacaoSpec::placement`] (each routes through a raw
14003        // `&self.<field>` borrow, trivially const), and the one
14004        // `Option<&Composite>` optional-composite-reference accessor
14005        // on [`AplicacaoSpec::entrada`] (routes through the
14006        // `pub const fn` [`Option::as_ref`], const-stable since Rust
14007        // 1.83). Any future accidental downgrade to non-`const` fails
14008        // the corresponding `<name>_via_const_fn` wrapper at caixa-
14009        // core build time with E0015 (`cannot call non-const
14010        // method`), strictly stronger than a runtime `assert!`.
14011        // Sibling of the peer inner-composite pin
14012        // [`m3_placement_entrada_slice_return_accessor_pair_is_const_fn`]
14013        // on the `Placement::clusters` + `Entrada::paths` slice-
14014        // return pair, and of the peer M2 axis pins on
14015        // [`crate::supervisor::SupervisorSpec::children`] and
14016        // [`crate::upgrade::UpgradeFromEntry::instructions`].
14017        const fn aplicacao_membros_via_const_fn(s: &AplicacaoSpec) -> &[Membro] {
14018            s.membros()
14019        }
14020        const fn aplicacao_contratos_via_const_fn(s: &AplicacaoSpec) -> &[WitContract] {
14021            s.contratos()
14022        }
14023        const fn aplicacao_politicas_via_const_fn(s: &AplicacaoSpec) -> &MeshPolicy {
14024            s.politicas()
14025        }
14026        const fn aplicacao_placement_via_const_fn(s: &AplicacaoSpec) -> &Placement {
14027            s.placement()
14028        }
14029        const fn aplicacao_entrada_via_const_fn(s: &AplicacaoSpec) -> Option<&Entrada> {
14030            s.entrada()
14031        }
14032        // Construct both a minimal "no :entrada" (internal-only
14033        // mesh) and a full "with :entrada" (external-gateway)
14034        // fixture so the family pins both the `None`-arm (author-
14035        // omitted `:entrada`) and the `Some`-arm (author-declared
14036        // `:entrada`) on the optional-composite axis.
14037        let membro = Membro {
14038            caixa: "web".into(),
14039            versao: "^0.1".into(),
14040        };
14041        let entrada_full = Entrada {
14042            host: "web.example.com".into(),
14043            para: "web".into(),
14044            paths: vec!["/api".into()],
14045            port: DEFAULT_SERVICO_PORT,
14046        };
14047        let internal_only = AplicacaoSpec {
14048            membros: vec![membro.clone()],
14049            contratos: vec![],
14050            politicas: MeshPolicy::default(),
14051            placement: Placement::default(),
14052            entrada: None,
14053        };
14054        let with_entrada = AplicacaoSpec {
14055            membros: vec![membro],
14056            contratos: vec![],
14057            politicas: MeshPolicy::default(),
14058            placement: Placement::default(),
14059            entrada: Some(entrada_full),
14060        };
14061        assert_eq!(
14062            aplicacao_membros_via_const_fn(&internal_only),
14063            internal_only.membros()
14064        );
14065        assert_eq!(
14066            aplicacao_membros_via_const_fn(&with_entrada),
14067            with_entrada.membros()
14068        );
14069        assert_eq!(
14070            aplicacao_contratos_via_const_fn(&internal_only),
14071            internal_only.contratos()
14072        );
14073        assert!(std::ptr::eq(
14074            aplicacao_politicas_via_const_fn(&internal_only),
14075            internal_only.politicas(),
14076        ));
14077        assert!(std::ptr::eq(
14078            aplicacao_placement_via_const_fn(&internal_only),
14079            internal_only.placement(),
14080        ));
14081        assert!(aplicacao_entrada_via_const_fn(&internal_only).is_none());
14082        match (
14083            aplicacao_entrada_via_const_fn(&with_entrada),
14084            with_entrada.entrada(),
14085        ) {
14086            (Some(a), Some(b)) => assert!(std::ptr::eq(a, b)),
14087            _ => panic!(
14088                "aplicacao_entrada_via_const_fn must agree with \
14089                 AplicacaoSpec::entrada on the Some-arm reference"
14090            ),
14091        }
14092    }
14093
14094    #[test]
14095    fn target_projected_returns_byte_equal_typed_view_across_all_four_arms() {
14096        // Load-bearing contract pin: on every canonical
14097        // `(:wit, :endpoint/:subject/:slot)` shape the substrate admits,
14098        // [`WitContract::target_projected`] returns byte-equal to
14099        // [`WitContract::target`]`().unwrap()` — the post-validation
14100        // projection accessor is a thin panicking wrapper over the
14101        // pre-validation validator, no extra work in the projection
14102        // path. Any future divergence (a validator-side normalization
14103        // the projection doesn't route through, an accessor-side
14104        // caching layer the validator doesn't populate) would surface
14105        // here at caixa-core build time rather than a silent per-consumer
14106        // split at renderer emit time. Sweeps the closed 4-arm
14107        // [`WitTarget`] partition ([`WitTarget::Http`] /
14108        // [`WitTarget::PubSub`] / [`WitTarget::Store`] /
14109        // [`WitTarget::Capability`]) so every arm carries a byte-equality
14110        // pin on the two-accessor pair.
14111        for (wit, endpoint, subject, slot) in [
14112            ("wasi:http/proxy", Some("/x"), None, None),
14113            ("nats:pub-sub", None, Some("events.x"), None),
14114            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
14115            ("custom:capability-only", None, None, None),
14116        ] {
14117            let c = WitContract {
14118                de: "cart".into(),
14119                para: "catalog".into(),
14120                wit: wit.into(),
14121                endpoint: endpoint.map(str::to_string),
14122                subject: subject.map(str::to_string),
14123                slot: slot.map(str::to_string),
14124            };
14125            assert_eq!(
14126                c.target_projected(),
14127                c.target().unwrap(),
14128                "target_projected must return byte-equal to target().unwrap() at wit={wit:?}"
14129            );
14130        }
14131    }
14132
14133    #[test]
14134    #[should_panic(expected = "validated by typed_view")]
14135    fn target_projected_panics_with_canonical_message_on_unvalidated_contract() {
14136        // Panic-path pin: [`WitContract::target_projected`] threads the
14137        // canonical [`WitContract::PROJECTED_INVARIANT_MSG`] byte-string
14138        // through its expect-panic when called on a contract whose
14139        // (`:wit`, payload) shape has not been crossed by
14140        // [`AplicacaoSpec::validate`] — a contract with a structurally-
14141        // invalid `:wit` (hyphen-for-colon typo) that would surface
14142        // [`AplicacaoError::ContratoWitInvalid`] at the validator gate.
14143        // A future rebrand on the panic-message axis would land at one
14144        // caixa-core edit on [`WitContract::PROJECTED_INVARIANT_MSG`]
14145        // and this pin's [`should_panic(expected = …)`] literal would
14146        // migrate alongside — the pin catches drift between the const
14147        // and the accessor's `expect(…)` call by construction.
14148        let c = WitContract {
14149            de: "cart".into(),
14150            para: "catalog".into(),
14151            // Hyphen-for-colon typo: `WitContract::target` returns
14152            // [`AplicacaoError::ContratoWitInvalid`] on this shape,
14153            // driving the [`WitContract::target_projected`] expect-panic.
14154            wit: "wasi-http/proxy".into(),
14155            endpoint: Some("/x".into()),
14156            subject: None,
14157            slot: None,
14158        };
14159        let _ = c.target_projected();
14160    }
14161
14162    #[test]
14163    fn target_projected_invariant_msg_matches_prior_inline_call_site_literal() {
14164        // Byte-equivalence pin: [`WitContract::PROJECTED_INVARIANT_MSG`]
14165        // carries the exact byte-string the two prior open-coded
14166        // `.target().expect("validated by typed_view")` production
14167        // consumers threaded through inline before this lift converged
14168        // them onto [`WitContract::target_projected`] — the caixa-mesh
14169        // per-`(:de, :para)` CNP L7 introspection branch at
14170        // `caixa-mesh/src/lib.rs:2825` and the caixa-feira `feira app
14171        // graph` per-`:contratos` payload-column printer at
14172        // `caixa-feira/src/cmd/app.rs:110`. Locks the panic-message
14173        // byte-string load-bearing so a well-meaning const-side rebrand
14174        // that didn't carry a matched pin migration would surface here
14175        // at caixa-core build time rather than a silent per-consumer
14176        // panic-message drift at cluster-apply time. Peer of the
14177        // sibling [`WitTarget::CAPABILITY_LABEL`] /
14178        // [`WitTarget::CAPABILITY_EXPECTED`] /
14179        // [`WitTarget::CAPABILITY_GRAPH_LABEL`] byte-equivalence pins on
14180        // the paired payload-less-arm scalar-const family.
14181        assert_eq!(
14182            WitContract::PROJECTED_INVARIANT_MSG,
14183            "validated by typed_view"
14184        );
14185    }
14186
14187    #[test]
14188    fn empty_wit_takes_precedence_over_invalid() {
14189        // Ordering pin: `EmptyWit` is the more self-locating
14190        // diagnostic on `""` and must lead — the value-shape gate is
14191        // only reached after the empty-check fires. Mirrors
14192        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
14193        // the peer payload axis.
14194        let mut s = three_member_spec();
14195        s.contratos.push(WitContract {
14196            de: "payment".into(),
14197            para: "catalog".into(),
14198            wit: String::new(),
14199            endpoint: None,
14200            subject: None,
14201            slot: None,
14202        });
14203        let err = s.validate().unwrap_err();
14204        assert!(
14205            matches!(err, AplicacaoError::EmptyWit { .. }),
14206            "got {err:?}"
14207        );
14208    }
14209
14210    #[test]
14211    fn wit_invalid_fires_before_payload_shape_arm() {
14212        // Ordering pin: a malformed `:wit` surfaces *its own*
14213        // diagnostic (which names the offending wit verbatim) before
14214        // any payload-field check — a contrato whose wit is
14215        // structurally invalid AND carries a wrong target field
14216        // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
14217        // because the dispatch on the wit is what decides which
14218        // payload field is "right" in the first place. Without this
14219        // ordering, the author would see "wrong target field" for a
14220        // wit that hasn't even been parsed, which doesn't name the
14221        // root cause.
14222        let mut s = three_member_spec();
14223        s.contratos.push(WitContract {
14224            de: "payment".into(),
14225            para: "catalog".into(),
14226            // Hyphen-for-colon typo + endpoint set: pre-gate this
14227            // raised `ContratoWrongTarget { expected: "none" }` (the
14228            // Capability arm rejecting the endpoint), masking the
14229            // real authoring mistake (the wit isn't `wasi:http/proxy`).
14230            wit: "wasi-http/proxy".into(),
14231            endpoint: Some("/x".into()),
14232            subject: None,
14233            slot: None,
14234        });
14235        let err = s.validate().unwrap_err();
14236        assert!(
14237            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
14238                if wit == "wasi-http/proxy"),
14239            "got {err:?}"
14240        );
14241    }
14242
14243    #[test]
14244    fn wit_invalid_diagnostic_carries_offending_wit() {
14245        // Diagnostic-shape pin — the offending `:wit` + `:de` +
14246        // `:para` + a non-empty reason flow through verbatim so the
14247        // author can grep their caixa.lisp for the offending contrato
14248        // block and fix it in one edit. Same shape as
14249        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
14250        let err = contrato_wit_err("WASI:HTTP/proxy");
14251        match err {
14252            AplicacaoError::ContratoWitInvalid {
14253                de,
14254                para,
14255                wit,
14256                reason,
14257            } => {
14258                assert_eq!(de, "payment");
14259                assert_eq!(para, "catalog");
14260                assert_eq!(wit, "WASI:HTTP/proxy");
14261                assert!(!reason.is_empty(), "reason field must be non-empty");
14262            }
14263            other => panic!("expected ContratoWitInvalid, got {other:?}"),
14264        }
14265    }
14266
14267    // ── :contratos :subject value-shape gate ─────────────────────────────
14268    //
14269    // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
14270    // suites on the peer payload axes. Until this gate landed
14271    // `WitContract::target()` only refused the empty string; a
14272    // structurally invalid subject silently passed validate and the
14273    // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
14274    // Subject'` on publish / subscribe, or as a silent message drop,
14275    // far from the source caixa.lisp. Every authoring footgun the
14276    // NATS server's subject parser would catch on admission now
14277    // becomes a caixa-build-time `ContratoSubjectInvalid` with the
14278    // offending `:subject` + `:de` + `:para` named verbatim. Same
14279    // diagnostic shape as `ContratoEndpointInvalid` /
14280    // `ContratoWitInvalid` on the peer payload axes; same shared
14281    // predicate (`crate::render::is_nats_subject`) ensures drift
14282    // between any two axes' rule enforcement is a build error at the
14283    // predicate, not piecemeal across renderers.
14284
14285    fn contrato_subject_err(subject: &str) -> AplicacaoError {
14286        // Fresh spec per call so the new contract doesn't collide on
14287        // identity with `three_member_spec`'s pre-existing entries.
14288        // The new edge uses `(payment, catalog)` — a pair the fixture
14289        // doesn't already declare — with `:wit "nats:pub-sub"` and the
14290        // varying `:subject`, so the subject-shape gate fires cleanly
14291        // after the wit-shape gate (which `"nats:pub-sub"` passes).
14292        let mut s = three_member_spec();
14293        s.contratos.push(WitContract {
14294            de: "payment".into(),
14295            para: "catalog".into(),
14296            wit: "nats:pub-sub".into(),
14297            endpoint: None,
14298            subject: Some(subject.into()),
14299            slot: None,
14300        });
14301        s.validate().unwrap_err()
14302    }
14303
14304    #[test]
14305    fn rejects_pubsub_contrato_subject_with_whitespace() {
14306        // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
14307        // landed at the NATS server as a malformed subject the parser
14308        // rejects with `-ERR 'Invalid Subject'`. Now caught at the
14309        // source caixa.lisp.
14310        let err = contrato_subject_err("foo bar");
14311        assert!(
14312            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14313                if subject == "foo bar" && reason.contains("whitespace")),
14314            "got {err:?}"
14315        );
14316    }
14317
14318    #[test]
14319    fn rejects_pubsub_contrato_subject_with_control_char() {
14320        let err = contrato_subject_err("foo\x01bar");
14321        assert!(
14322            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14323                if subject == "foo\x01bar" && reason.contains("control character")),
14324            "got {err:?}"
14325        );
14326    }
14327
14328    #[test]
14329    fn rejects_pubsub_contrato_subject_with_non_ascii() {
14330        // Un-percent-encoded non-ASCII byte — the canonical "I copied
14331        // the subject from a doc with smart quotes / accented
14332        // characters" footgun.
14333        let err = contrato_subject_err("foo.caf\u{e9}");
14334        assert!(
14335            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14336                if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
14337            "got {err:?}"
14338        );
14339    }
14340
14341    #[test]
14342    fn rejects_pubsub_contrato_subject_with_leading_dot() {
14343        // Empty leading token — NATS rejects.
14344        let err = contrato_subject_err(".foo");
14345        assert!(
14346            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14347                if subject == ".foo" && reason.contains("must not start with `.`")),
14348            "got {err:?}"
14349        );
14350    }
14351
14352    #[test]
14353    fn rejects_pubsub_contrato_subject_with_trailing_dot() {
14354        // Empty trailing token — NATS rejects. The remediation
14355        // (use `>` instead) is in the reason string.
14356        let err = contrato_subject_err("foo.");
14357        assert!(
14358            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14359                if subject == "foo." && reason.contains("must not end with `.`")),
14360            "got {err:?}"
14361        );
14362    }
14363
14364    #[test]
14365    fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
14366        // The canonical "I forgot to fill in the middle segment"
14367        // typo — `"foo..bar"`. NATS rejects empty tokens.
14368        let err = contrato_subject_err("foo..bar");
14369        assert!(
14370            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14371                if subject == "foo..bar" && reason.contains("consecutive `.`")),
14372            "got {err:?}"
14373        );
14374    }
14375
14376    #[test]
14377    fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
14378        // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
14379        // as the final segment. Pre-gate this passed as a typed edge
14380        // and surfaced at runtime as a NATS subscribe rejection.
14381        let err = contrato_subject_err("foo.>.bar");
14382        assert!(
14383            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14384                if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
14385            "got {err:?}"
14386        );
14387    }
14388
14389    #[test]
14390    fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
14391        // `foo*.bar` — NATS wildcards are standalone tokens. The
14392        // remediation is in the reason string.
14393        let err = contrato_subject_err("foo*.bar");
14394        assert!(
14395            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14396                if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
14397            "got {err:?}"
14398        );
14399    }
14400
14401    #[test]
14402    fn rejects_pubsub_contrato_subject_with_invalid_char() {
14403        // `foo,bar` — comma is not a valid NATS subject character.
14404        // Pinned separately from the wildcard arms so the invalid-
14405        // character diagnostic is in force.
14406        let err = contrato_subject_err("foo,bar");
14407        assert!(
14408            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14409                if subject == "foo,bar" && reason.contains("invalid character")),
14410            "got {err:?}"
14411        );
14412    }
14413
14414    #[test]
14415    fn rejects_pubsub_contrato_subject_too_long() {
14416        // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
14417        // The legitimate-shape arms all pass (one all-`a` token, no
14418        // `.`, no wildcards); only the cap arm fires. Surfaces the
14419        // paste-from-binary / accidental-multi-line-blob landing
14420        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
14421        // on the peer axis.
14422        let big = "a".repeat(257);
14423        assert_eq!(big.len(), 257);
14424        let err = contrato_subject_err(&big);
14425        assert!(
14426            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14427                if subject == &big && reason.contains("max length of 256")),
14428            "got {err:?}"
14429        );
14430    }
14431
14432    #[test]
14433    fn pubsub_contrato_subject_max_length_validates() {
14434        // 256-byte subject — exactly the cap. Boundary pin: drift in
14435        // the cap surfaces here and at
14436        // `rejects_pubsub_contrato_subject_too_long` simultaneously,
14437        // mirroring `http_contrato_endpoint_max_length_validates` and
14438        // `wit_max_length_validates` on the peer axes.
14439        let big = "a".repeat(256);
14440        assert_eq!(big.len(), 256);
14441        let mut s = three_member_spec();
14442        s.contratos.push(WitContract {
14443            de: "payment".into(),
14444            para: "catalog".into(),
14445            wit: "nats:pub-sub".into(),
14446            endpoint: None,
14447            subject: Some(big),
14448            slot: None,
14449        });
14450        s.validate().unwrap();
14451    }
14452
14453    #[test]
14454    fn pubsub_contrato_subject_accepts_canonical_forms() {
14455        // Positive-set sweep: every canonical NATS subject shape the
14456        // substrate-side `is_nats_subject` predicate accepts (the
14457        // multi-dot `events.order.charged`, the snake_case / kebab-
14458        // case / mixed-case tokens, the digit-bearing tokens, the
14459        // single-token wildcard `*` at every segment position, and
14460        // the trailing `>` multi-token wildcard) must remain a valid
14461        // contrato subject too. Drift between this list and the
14462        // substrate-side `nats_subject_accepts_canonical_forms` sweep
14463        // surfaces at the shared predicate — one source of truth.
14464        // Uses a fresh `(payment, catalog)` edge so none of the swept
14465        // subjects collide with the pre-existing entries in
14466        // `three_member_spec`.
14467        for subject in [
14468            "checkout.events.charge.failed",
14469            "rio.events.order.charged",
14470            "orders",
14471            "orders.123",
14472            "snake_case.token",
14473            "kebab-case.token",
14474            "MixedCase.Token",
14475            "orders.*.charged",
14476            "*.events.*",
14477            "orders.>",
14478        ] {
14479            let mut s = three_member_spec();
14480            s.contratos.push(WitContract {
14481                de: "payment".into(),
14482                para: "catalog".into(),
14483                wit: "nats:pub-sub".into(),
14484                endpoint: None,
14485                subject: Some(subject.into()),
14486                slot: None,
14487            });
14488            s.validate()
14489                .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
14490        }
14491    }
14492
14493    #[test]
14494    fn contrato_subject_empty_takes_precedence_over_invalid() {
14495        // Ordering pin: `ContratoSubjectEmpty` is the more self-
14496        // locating diagnostic on `""` and must lead — the value-shape
14497        // gate is only reached after the empty-check fires. Mirrors
14498        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
14499        // the peer payload axis.
14500        let mut s = three_member_spec();
14501        s.contratos.push(WitContract {
14502            de: "payment".into(),
14503            para: "catalog".into(),
14504            wit: "nats:pub-sub".into(),
14505            endpoint: None,
14506            subject: Some(String::new()),
14507            slot: None,
14508        });
14509        let err = s.validate().unwrap_err();
14510        assert!(
14511            matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
14512            "got {err:?}"
14513        );
14514    }
14515
14516    #[test]
14517    fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
14518        // Diagnostic-shape pin — the offending `:subject` + `:de` +
14519        // `:para` + a non-empty reason flow through verbatim so the
14520        // author can grep their caixa.lisp for the offending contrato
14521        // block and fix it in one edit. Same shape as
14522        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
14523        // and `wit_invalid_diagnostic_carries_offending_wit`.
14524        let err = contrato_subject_err("foo..bar");
14525        match err {
14526            AplicacaoError::ContratoSubjectInvalid {
14527                de,
14528                para,
14529                subject,
14530                reason,
14531            } => {
14532                assert_eq!(de, "payment");
14533                assert_eq!(para, "catalog");
14534                assert_eq!(subject, "foo..bar");
14535                assert!(!reason.is_empty(), "reason field must be non-empty");
14536            }
14537            other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
14538        }
14539    }
14540
14541    #[test]
14542    fn target_view_pubsub_subject_passes_through_to_typed_view() {
14543        // The compounding theorem on the pub-sub axis: every
14544        // `WitTarget::PubSub { subject }` returned by `target()` carries
14545        // a NATS-server-accepted subject. Renderers downstream of
14546        // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
14547        // NATS Stream/Consumer CR emitter, the future `feira app graph`
14548        // view's subject labeller) can rely on this without re-checking
14549        // — the type system carries the proof. Mirrors
14550        // `target_view_payload_is_guaranteed_nonempty_after_target_call`
14551        // on the peer axes.
14552        let nats = WitContract {
14553            de: "a".into(),
14554            para: "b".into(),
14555            wit: "nats:pub-sub".into(),
14556            endpoint: None,
14557            subject: Some("orders.events.*.charged".into()),
14558            slot: None,
14559        };
14560        match nats.target().unwrap() {
14561            WitTarget::PubSub { subject } => {
14562                assert_eq!(subject, "orders.events.*.charged");
14563            }
14564            other => panic!("expected PubSub, got {other:?}"),
14565        }
14566    }
14567
14568    // ── :contratos :slot value-shape gate ────────────────────────────────
14569    //
14570    // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
14571    // (63e18a0) value-shape suites on the peer payload axes. Until this
14572    // gate landed `WitContract::target()` only refused the empty string
14573    // for the Store arm; a structurally invalid slot (raw whitespace,
14574    // control character, non-ASCII byte, paste-from-binary multi-line
14575    // blob) silently passed validate and surfaced at runtime as a
14576    // per-backend kv write rejection or a silent next-read corruption,
14577    // far from the source caixa.lisp with no field naming which
14578    // `:contratos` edge carried the typo. Every authoring footgun the
14579    // kv backend intersection-floor would catch on write now becomes a
14580    // caixa-build-time `ContratoSlotInvalid` with the offending
14581    // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
14582    // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
14583    // peer payload axes; same shared predicate
14584    // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
14585    // any two axes' rule enforcement is a build error at the
14586    // predicate, not piecemeal across renderers. Closes the typed
14587    // payload-axis value-shape trajectory across all three legs of the
14588    // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
14589
14590    fn contrato_slot_err(slot: &str) -> AplicacaoError {
14591        // Fresh spec per call so the new contract doesn't collide on
14592        // identity with `three_member_spec`'s pre-existing entries
14593        // and doesn't close a synchronous cycle the cycle detector
14594        // would reject before the slot-shape gate fires. The new edge
14595        // uses `(payment, catalog)` — a pair the fixture doesn't
14596        // already declare in either direction (the fixture carries
14597        // `cart -> catalog` and `cart -> payment`, so `payment ->
14598        // catalog` doesn't form a cycle on the sync subgraph) — with
14599        // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
14600        // slot-shape gate fires cleanly after the wit-shape gate
14601        // (which `"wasi:keyvalue/store"` passes). Same edge pair the
14602        // peer `contrato_subject_err` helper uses (63e18a0).
14603        let mut s = three_member_spec();
14604        s.contratos.push(WitContract {
14605            de: "payment".into(),
14606            para: "catalog".into(),
14607            wit: "wasi:keyvalue/store".into(),
14608            endpoint: None,
14609            subject: None,
14610            slot: Some(slot.into()),
14611        });
14612        s.validate().unwrap_err()
14613    }
14614
14615    #[test]
14616    fn rejects_store_contrato_slot_with_whitespace() {
14617        // Fail-before-pass-after pin — pre-gate `"check out/$order"`
14618        // silently landed at the kv backend with whitespace whose
14619        // runtime behavior varies unpredictably across backends (etcd
14620        // accepts, Redis accepts then breaks on next CLI op, DynamoDB
14621        // rejects on write). Now caught at the source caixa.lisp.
14622        let err = contrato_slot_err("check out/$order");
14623        assert!(
14624            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
14625                if slot == "check out/$order" && reason.contains("whitespace")),
14626            "got {err:?}"
14627        );
14628    }
14629
14630    #[test]
14631    fn rejects_store_contrato_slot_with_tab() {
14632        // Tab byte arm-pinned separately from the space arm so a
14633        // future relaxation that admits one but not the other surfaces
14634        // here.
14635        let err = contrato_slot_err("check\tout");
14636        assert!(
14637            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
14638                if slot == "check\tout" && reason.contains("whitespace")),
14639            "got {err:?}"
14640        );
14641    }
14642
14643    #[test]
14644    fn rejects_store_contrato_slot_with_control_char() {
14645        // SOH (0x01) — distinct from the whitespace arm. Redis admits
14646        // and corrupts on RESP protocol framing; DynamoDB rejects on
14647        // write.
14648        let err = contrato_slot_err("checkout/\x01order");
14649        assert!(
14650            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
14651                if slot == "checkout/\x01order" && reason.contains("control character")),
14652            "got {err:?}"
14653        );
14654    }
14655
14656    #[test]
14657    fn rejects_store_contrato_slot_with_newline() {
14658        // Embedded newline — the canonical "the paste-from-binary slug
14659        // spans multiple lines" footgun. Distinct from the whitespace
14660        // arm because `\n` is a control character (0x0A).
14661        let err = contrato_slot_err("checkout\norder");
14662        assert!(
14663            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
14664                if slot == "checkout\norder" && reason.contains("control character")),
14665            "got {err:?}"
14666        );
14667    }
14668
14669    #[test]
14670    fn rejects_store_contrato_slot_with_non_ascii() {
14671        // Un-percent-encoded non-ASCII byte — the canonical "I copied
14672        // the slot from a doc with accented characters" footgun. Each
14673        // kv backend re-encodes non-ASCII differently (etcd preserves
14674        // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
14675        // rejects), so the typed slot's value set is the intersection-
14676        // floor every backend admits identically (printable ASCII).
14677        let err = contrato_slot_err("ch\u{e9}ckout/$order");
14678        assert!(
14679            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
14680                if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
14681            "got {err:?}"
14682        );
14683    }
14684
14685    #[test]
14686    fn rejects_store_contrato_slot_too_long() {
14687        // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
14688        // legitimate-shape arms all pass (a single all-`a` token, no
14689        // separators); only the cap arm fires. Surfaces the paste-
14690        // from-binary / accidental-multi-line-blob landing footgun.
14691        // Mirrors `rejects_pubsub_contrato_subject_too_long` and
14692        // `rejects_http_contrato_endpoint_too_long` on the peer
14693        // payload axes.
14694        let big = "a".repeat(513);
14695        assert_eq!(big.len(), 513);
14696        let err = contrato_slot_err(&big);
14697        assert!(
14698            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
14699                if slot == &big && reason.contains("max length of 512")),
14700            "got {err:?}"
14701        );
14702    }
14703
14704    #[test]
14705    fn store_contrato_slot_max_length_validates() {
14706        // 512-byte slot — exactly the cap. Boundary pin: drift in the
14707        // cap surfaces here and at `rejects_store_contrato_slot_too_long`
14708        // simultaneously, mirroring
14709        // `pubsub_contrato_subject_max_length_validates` and
14710        // `http_contrato_endpoint_max_length_validates` on the peer
14711        // payload axes.
14712        let big = "a".repeat(512);
14713        assert_eq!(big.len(), 512);
14714        let mut s = three_member_spec();
14715        s.contratos.push(WitContract {
14716            de: "payment".into(),
14717            para: "catalog".into(),
14718            wit: "wasi:keyvalue/store".into(),
14719            endpoint: None,
14720            subject: None,
14721            slot: Some(big),
14722        });
14723        s.validate().unwrap();
14724    }
14725
14726    #[test]
14727    fn store_contrato_slot_accepts_canonical_forms() {
14728        // Positive-set sweep: every canonical kv slot template the
14729        // substrate-side `is_wasi_keyvalue_slot` predicate accepts
14730        // (single-token identifiers, path-namespaced `$`-templates,
14731        // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
14732        // snake_case / kebab-case / MixedCase tokens, digit-bearing
14733        // tokens, percent-encoded fragments) must remain valid
14734        // contrato slots too. Drift between this list and the
14735        // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
14736        // surfaces at the shared predicate — one source of truth.
14737        // Uses a fresh `(payment, catalog)` edge so none of the swept
14738        // slots collide with the pre-existing entries in
14739        // `three_member_spec`.
14740        for slot in [
14741            "checkout",
14742            "checkout/$orderId",
14743            "users:{tenant}/{id}",
14744            "session.<sid>",
14745            "session.tokens.<sid>",
14746            "snake_case_key",
14747            "kebab-case-key",
14748            "MixedCase",
14749            "shard0",
14750            "v2/key",
14751            "users/caf%C3%A9",
14752        ] {
14753            let mut s = three_member_spec();
14754            s.contratos.push(WitContract {
14755                de: "payment".into(),
14756                para: "catalog".into(),
14757                wit: "wasi:keyvalue/store".into(),
14758                endpoint: None,
14759                subject: None,
14760                slot: Some(slot.into()),
14761            });
14762            s.validate()
14763                .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
14764        }
14765    }
14766
14767    #[test]
14768    fn contrato_slot_empty_takes_precedence_over_invalid() {
14769        // Ordering pin: `ContratoSlotEmpty` is the more self-locating
14770        // diagnostic on `""` and must lead — the value-shape gate is
14771        // only reached after the empty-check fires. Mirrors
14772        // `contrato_subject_empty_takes_precedence_over_invalid` and
14773        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
14774        // the peer payload axes.
14775        let mut s = three_member_spec();
14776        s.contratos.push(WitContract {
14777            de: "payment".into(),
14778            para: "catalog".into(),
14779            wit: "wasi:keyvalue/store".into(),
14780            endpoint: None,
14781            subject: None,
14782            slot: Some(String::new()),
14783        });
14784        let err = s.validate().unwrap_err();
14785        assert!(
14786            matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
14787            "got {err:?}"
14788        );
14789    }
14790
14791    #[test]
14792    fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
14793        // Diagnostic-shape pin — the offending `:slot` + `:de` +
14794        // `:para` + a non-empty reason flow through verbatim so the
14795        // author can grep their caixa.lisp for the offending contrato
14796        // block and fix it in one edit. Same shape as
14797        // `contrato_subject_invalid_diagnostic_carries_offending_subject`
14798        // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
14799        // on the peer payload axes.
14800        let err = contrato_slot_err("check out/$order");
14801        match err {
14802            AplicacaoError::ContratoSlotInvalid {
14803                de,
14804                para,
14805                slot,
14806                reason,
14807            } => {
14808                assert_eq!(de, "payment");
14809                assert_eq!(para, "catalog");
14810                assert_eq!(slot, "check out/$order");
14811                assert!(!reason.is_empty(), "reason field must be non-empty");
14812            }
14813            other => panic!("expected ContratoSlotInvalid, got {other:?}"),
14814        }
14815    }
14816
14817    #[test]
14818    fn target_view_store_slot_passes_through_to_typed_view() {
14819        // The compounding theorem on the store axis: every
14820        // `WitTarget::Store { slot }` returned by `target()` carries a
14821        // kv-backend-accepted slot template. Renderers downstream of
14822        // `typed_view()` (the future per-Servico `:capabilities
14823        // wasi:keyvalue/store` axis emitter, the future `feira app
14824        // graph` view's slot labeller, the future kv-provider CR
14825        // materializer) can rely on this without re-checking — the
14826        // type system carries the proof. Mirrors
14827        // `target_view_pubsub_subject_passes_through_to_typed_view` on
14828        // the peer payload axis.
14829        let store = WitContract {
14830            de: "a".into(),
14831            para: "b".into(),
14832            wit: "wasi:keyvalue/store".into(),
14833            endpoint: None,
14834            subject: None,
14835            slot: Some("checkout/$orderId".into()),
14836        };
14837        match store.target().unwrap() {
14838            WitTarget::Store { slot } => {
14839                assert_eq!(slot, "checkout/$orderId");
14840            }
14841            other => panic!("expected Store, got {other:?}"),
14842        }
14843    }
14844
14845    #[test]
14846    fn rejects_self_loop_in_synchronous_contratos() {
14847        // A synchronous self-edge (`cart → cart` over HTTP) is now
14848        // rejected by the dedicated `ContratoSelfLoop` gate — a precise
14849        // "this edge is degenerate" diagnostic — rather than incidentally
14850        // by the cycle detector framing it as a `["cart", "cart"]`
14851        // multi-node deadlock.
14852        let mut s = three_member_spec();
14853        s.contratos.push(contract_http("cart", "cart", "/loop"));
14854        let err = s.validate().unwrap_err();
14855        match err {
14856            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
14857                assert_eq!(caixa, "cart");
14858                assert_eq!(wit, "wasi:http/proxy");
14859            }
14860            other => panic!("expected ContratoSelfLoop, got {other:?}"),
14861        }
14862    }
14863
14864    #[test]
14865    fn rejects_self_loop_in_pubsub_contratos() {
14866        // The cycle detector excludes pub-sub edges (acyclic by
14867        // construction), so before the explicit gate a `nats:pub-sub`
14868        // self-edge silently validated and rendered a self-allow CNP.
14869        // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
14870        let mut s = three_member_spec();
14871        s.contratos.push(WitContract {
14872            de: "payment".into(),
14873            para: "payment".into(),
14874            wit: "nats:pub-sub".into(),
14875            endpoint: None,
14876            subject: Some("rio.events.payment".into()),
14877            slot: None,
14878        });
14879        let err = s.validate().unwrap_err();
14880        match err {
14881            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
14882                assert_eq!(caixa, "payment");
14883                assert_eq!(wit, "nats:pub-sub");
14884            }
14885            other => panic!("expected ContratoSelfLoop, got {other:?}"),
14886        }
14887    }
14888
14889    #[test]
14890    fn self_loop_fires_before_payload_shape_check() {
14891        // The structural "this edge can't exist" error precedes the
14892        // narrower payload-shape diagnostics: a self-edge carrying an
14893        // otherwise-malformed endpoint still reports ContratoSelfLoop,
14894        // not ContratoEndpointInvalid.
14895        let mut s = three_member_spec();
14896        s.contratos.push(WitContract {
14897            de: "cart".into(),
14898            para: "cart".into(),
14899            wit: "wasi:http/proxy".into(),
14900            endpoint: Some("not-absolute".into()),
14901            subject: None,
14902            slot: None,
14903        });
14904        match s.validate().unwrap_err() {
14905            AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
14906            other => panic!("expected ContratoSelfLoop, got {other:?}"),
14907        }
14908    }
14909
14910    #[test]
14911    fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
14912        // A self-edge naming a non-member reports the more fundamental
14913        // ContratoMemberMissing first (the member doesn't exist), so the
14914        // self-loop gate is reached only once both endpoints resolve.
14915        let mut s = three_member_spec();
14916        s.contratos.push(contract_http("ghost", "ghost", "/loop"));
14917        match s.validate().unwrap_err() {
14918            AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
14919            other => panic!("expected ContratoMemberMissing, got {other:?}"),
14920        }
14921    }
14922
14923    #[test]
14924    fn rejects_two_node_synchronous_cycle() {
14925        let mut s = three_member_spec();
14926        // existing edges: cart → catalog, cart → payment
14927        // adding catalog → cart closes a 2-cycle on the HTTP subgraph
14928        s.contratos
14929            .push(contract_http("catalog", "cart", "/refresh"));
14930        let err = s.validate().unwrap_err();
14931        match err {
14932            AplicacaoError::ContratoCycle { cycle } => {
14933                // Cycle traversal should mention both endpoints, with
14934                // the back-edge target appearing as both first and last
14935                // element to close the loop.
14936                assert!(cycle.len() >= 3);
14937                assert_eq!(cycle.first(), cycle.last());
14938                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
14939                assert!(body.contains("cart"));
14940                assert!(body.contains("catalog"));
14941            }
14942            other => panic!("expected ContratoCycle, got {other:?}"),
14943        }
14944    }
14945
14946    #[test]
14947    fn rejects_three_node_synchronous_cycle() {
14948        let mut s = three_member_spec();
14949        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
14950        s.contratos = vec![
14951            contract_http("catalog", "cart", "/x"),
14952            contract_http("cart", "payment", "/y"),
14953            contract_http("payment", "catalog", "/z"),
14954        ];
14955        let err = s.validate().unwrap_err();
14956        match err {
14957            AplicacaoError::ContratoCycle { cycle } => {
14958                assert_eq!(cycle.first(), cycle.last());
14959                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
14960                assert_eq!(body.len(), 3);
14961                assert!(body.contains("cart"));
14962                assert!(body.contains("catalog"));
14963                assert!(body.contains("payment"));
14964            }
14965            other => panic!("expected ContratoCycle, got {other:?}"),
14966        }
14967    }
14968
14969    #[test]
14970    fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
14971        // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
14972        // "acyclic by construction" — so a cycle whose closing edge
14973        // is pub-sub should NOT raise ContratoCycle.
14974        let mut s = three_member_spec();
14975        s.contratos = vec![
14976            contract_http("catalog", "cart", "/x"),
14977            contract_http("cart", "payment", "/y"),
14978            // Closing edge is pub-sub — async; not a sync deadlock.
14979            WitContract {
14980                de: "payment".into(),
14981                para: "catalog".into(),
14982                wit: "nats:pub-sub".into(),
14983                endpoint: None,
14984                subject: Some("checkout.events.charge.completed".into()),
14985                slot: None,
14986            },
14987        ];
14988        s.validate().expect("pub-sub edge breaks the sync cycle");
14989    }
14990
14991    #[test]
14992    fn store_edge_counts_as_synchronous_for_cycle_detection() {
14993        // wasi:keyvalue/store is request/response; a cycle through one
14994        // *is* a sync deadlock, just like HTTP.
14995        let mut s = three_member_spec();
14996        s.contratos = vec![
14997            contract_http("catalog", "cart", "/x"),
14998            WitContract {
14999                de: "cart".into(),
15000                para: "catalog".into(),
15001                wit: "wasi:keyvalue/store".into(),
15002                endpoint: None,
15003                subject: None,
15004                slot: Some("session/$id".into()),
15005            },
15006        ];
15007        let err = s.validate().unwrap_err();
15008        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
15009    }
15010
15011    #[test]
15012    fn capability_edge_counts_as_synchronous_for_cycle_detection() {
15013        // Capability-only edges (unknown WIT shape, no payload) default
15014        // to synchronous — safer; authors with truly async capability
15015        // semantics can model them as pub-sub explicitly.
15016        let mut s = three_member_spec();
15017        s.contratos = vec![
15018            contract_http("catalog", "cart", "/x"),
15019            WitContract {
15020                de: "cart".into(),
15021                para: "catalog".into(),
15022                wit: "custom:exchange".into(),
15023                endpoint: None,
15024                subject: None,
15025                slot: None,
15026            },
15027        ];
15028        let err = s.validate().unwrap_err();
15029        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
15030    }
15031
15032    #[test]
15033    fn long_acyclic_chain_validates() {
15034        // A long sync chain (no back-edges) must validate even when
15035        // every node is reachable from the first.
15036        let mut s = three_member_spec();
15037        s.membros = vec![
15038            membro("a", "^0.1"),
15039            membro("b", "^0.1"),
15040            membro("c", "^0.1"),
15041            membro("d", "^0.1"),
15042            membro("e", "^0.1"),
15043        ];
15044        s.contratos = vec![
15045            contract_http("a", "b", "/1"),
15046            contract_http("b", "c", "/2"),
15047            contract_http("c", "d", "/3"),
15048            contract_http("d", "e", "/4"),
15049        ];
15050        s.entrada.as_mut().unwrap().para = "a".into();
15051        s.validate().unwrap();
15052    }
15053
15054    #[test]
15055    fn diamond_acyclic_validates() {
15056        // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
15057        let mut s = three_member_spec();
15058        s.membros = vec![
15059            membro("a", "^0.1"),
15060            membro("b", "^0.1"),
15061            membro("c", "^0.1"),
15062            membro("d", "^0.1"),
15063        ];
15064        s.contratos = vec![
15065            contract_http("a", "b", "/1"),
15066            contract_http("a", "c", "/2"),
15067            contract_http("b", "d", "/3"),
15068            contract_http("c", "d", "/4"),
15069        ];
15070        s.entrada.as_mut().unwrap().para = "a".into();
15071        s.validate().unwrap();
15072    }
15073
15074    // ── duplicate-`:contratos` build-error gate ──────────────────────────
15075
15076    #[test]
15077    fn rejects_duplicate_http_contrato() {
15078        // Fail-before-pass-after pin: the fixture's `cart → catalog`
15079        // HTTP edge appears once. Push an identical entry — same
15080        // (de, para, wit, endpoint) — and validate() must reject it.
15081        // Until this gate landed the typed surface accepted the
15082        // duplicate silently and caixa-mesh's `cilium_network_policies`
15083        // emitted two ``CiliumNetworkPolicy`` objects with identical
15084        // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
15085        // admission rejects on `kubectl apply` far from the source.
15086        let mut s = three_member_spec();
15087        s.contratos
15088            .push(contract_http("cart", "catalog", "/products/:id"));
15089        let err = s.validate().unwrap_err();
15090        assert!(
15091            matches!(
15092                err,
15093                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
15094                    if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
15095            ),
15096            "got {err:?}"
15097        );
15098    }
15099
15100    #[test]
15101    fn rejects_duplicate_pubsub_contrato() {
15102        // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
15103        // edges with identical (de, para, subject) are degenerate;
15104        // pin that the typed surface refuses both at validate time.
15105        let mut s = three_member_spec();
15106        let pubsub = WitContract {
15107            de: "payment".into(),
15108            para: "cart".into(),
15109            wit: "nats:pub-sub".into(),
15110            endpoint: None,
15111            subject: Some("checkout.events.charge.failed".into()),
15112            slot: None,
15113        };
15114        s.contratos.push(pubsub.clone());
15115        s.contratos.push(pubsub);
15116        let err = s.validate().unwrap_err();
15117        assert!(
15118            matches!(
15119                err,
15120                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
15121                    if de == "payment" && para == "cart" && wit == "nats:pub-sub"
15122            ),
15123            "got {err:?}"
15124        );
15125    }
15126
15127    #[test]
15128    fn rejects_duplicate_store_contrato() {
15129        // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
15130        // edges with identical (de, para, slot) collapse to one mesh-
15131        // policy edge; pin the build error.
15132        let mut s = three_member_spec();
15133        let store = WitContract {
15134            de: "cart".into(),
15135            para: "payment".into(),
15136            wit: "wasi:keyvalue/store".into(),
15137            endpoint: None,
15138            subject: None,
15139            slot: Some("checkout/$orderId".into()),
15140        };
15141        // Drop the conflicting HTTP `cart → payment` edge from the
15142        // fixture so the duplicate-store pair is the only one
15143        // distinguishable on this pair.
15144        s.contratos
15145            .retain(|c| !(c.de == "cart" && c.para == "payment"));
15146        s.contratos.push(store.clone());
15147        s.contratos.push(store);
15148        let err = s.validate().unwrap_err();
15149        assert!(
15150            matches!(
15151                err,
15152                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
15153                    if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
15154            ),
15155            "got {err:?}"
15156        );
15157    }
15158
15159    #[test]
15160    fn rejects_duplicate_capability_contrato() {
15161        // Same gate on the pure-capability axis (no payload selector).
15162        // Two contracts with identical (de, para, wit) and no
15163        // endpoint/subject/slot are duplicate edges; pin so a future
15164        // `target_label` change can't accidentally collapse the
15165        // capability arm into a None-shaped key that compares equal
15166        // to a populated one.
15167        let mut s = three_member_spec();
15168        let capability = WitContract {
15169            de: "cart".into(),
15170            para: "catalog".into(),
15171            wit: "pleme:cap/audit".into(),
15172            endpoint: None,
15173            subject: None,
15174            slot: None,
15175        };
15176        s.contratos.push(capability.clone());
15177        s.contratos.push(capability);
15178        let err = s.validate().unwrap_err();
15179        match err {
15180            AplicacaoError::ContratoDuplicate {
15181                de,
15182                para,
15183                wit,
15184                target,
15185            } => {
15186                assert_eq!(de, "cart");
15187                assert_eq!(para, "catalog");
15188                assert_eq!(wit, "pleme:cap/audit");
15189                assert!(
15190                    target.contains("capability"),
15191                    "capability-edge duplicate diagnostic must surface the \
15192                     no-payload shape (got target = {target:?})"
15193                );
15194            }
15195            other => panic!("expected ContratoDuplicate, got {other:?}"),
15196        }
15197    }
15198
15199    #[test]
15200    fn accepts_distinct_http_paths_between_same_pair() {
15201        // Negative pin: two HTTP contracts cart → catalog at distinct
15202        // endpoints (`/products/:id` and `/search`) are *not*
15203        // duplicates — they're distinct typed edges differing on the
15204        // payload axis. The duplicate-gate must not over-match here,
15205        // since the cart-calls-catalog-on-multiple-paths shape is the
15206        // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
15207        // example: cart calls catalog at /products/:id, payment at
15208        // /charge — same shape extends to two paths on one para).
15209        let mut s = three_member_spec();
15210        s.contratos
15211            .push(contract_http("cart", "catalog", "/search"));
15212        s.validate()
15213            .expect("distinct endpoints between same (de, para) must validate");
15214    }
15215
15216    #[test]
15217    fn accepts_same_endpoint_on_different_pairs() {
15218        // Negative pin: the same `/charge` endpoint reused on two
15219        // different (de, para) pairs is two distinct edges, not a
15220        // duplicate. Pinning this shape so the gate's identity key
15221        // includes both `de` and `para` (not just `(wit, endpoint)`).
15222        let mut s = three_member_spec();
15223        s.contratos
15224            .push(contract_http("payment", "catalog", "/charge"));
15225        s.validate()
15226            .expect("same endpoint reused on distinct (de, para) must validate");
15227    }
15228
15229    #[test]
15230    fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
15231        // Pin the diagnostic shape: the duplicate-edge error names
15232        // *which* target field carried the conflict, so the author
15233        // doesn't have to re-grep the source caixa.lisp to find it.
15234        // Same self-locating diagnostic discipline as
15235        // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
15236        let mut s = three_member_spec();
15237        s.contratos
15238            .push(contract_http("cart", "catalog", "/products/:id"));
15239        let err = s.validate().unwrap_err();
15240        let msg = format!("{err}");
15241        assert!(
15242            msg.contains("\"/products/:id\""),
15243            "duplicate-contrato diagnostic must name the offending \
15244             :endpoint payload (got: {msg:?})"
15245        );
15246        assert!(
15247            msg.contains("cart") && msg.contains("catalog"),
15248            "diagnostic must name both endpoints of the duplicate edge \
15249             (got: {msg:?})"
15250        );
15251    }
15252
15253    #[test]
15254    fn duplicate_contrato_gate_runs_after_membership_check() {
15255        // Order pin: a duplicate contract whose `:de` is *also* not in
15256        // `:membros` surfaces the membership error first — the
15257        // missing-member diagnostic is more locating than the
15258        // duplicate-edge one (the author has to fix the membership
15259        // before the duplicate is meaningful). Same ordering
15260        // discipline as `membros_validation_runs_before_contratos_membership_check`.
15261        let mut s = three_member_spec();
15262        s.contratos.push(contract_http("phantom", "catalog", "/x"));
15263        s.contratos.push(contract_http("phantom", "catalog", "/x"));
15264        let err = s.validate().unwrap_err();
15265        assert!(
15266            matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
15267            "membership-missing must fire before duplicate-edge (got {err:?})"
15268        );
15269    }
15270
15271    #[test]
15272    fn duplicate_contrato_gate_runs_after_target_shape_check() {
15273        // Order pin: a contract with a malformed target (e.g. an HTTP
15274        // wit world with an empty :endpoint) surfaces the target-shape
15275        // error first, not the duplicate one. Even when two such
15276        // malformed entries are identical, the per-contract `target()`
15277        // check fires inside the loop *before* the duplicate-key
15278        // insert, so the diagnostic remains the most-locating one.
15279        let mut s = three_member_spec();
15280        let malformed = WitContract {
15281            de: "cart".into(),
15282            para: "catalog".into(),
15283            wit: "wasi:http/proxy".into(),
15284            endpoint: Some(String::new()),
15285            subject: None,
15286            slot: None,
15287        };
15288        s.contratos.push(malformed.clone());
15289        s.contratos.push(malformed);
15290        let err = s.validate().unwrap_err();
15291        assert!(
15292            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
15293            "endpoint-empty must fire before duplicate-edge (got {err:?})"
15294        );
15295    }
15296
15297    #[test]
15298    fn wit_target_label_pins_per_variant_format() {
15299        // Label format is the single source of truth every duplicate-
15300        // `:contratos` diagnostic + every future `feira app graph`
15301        // consumer routes through. Pin the shape per variant so a
15302        // future edit to `WitTarget::label` (e.g. a JSON emitter that
15303        // strips the leading `:`, or a rename from `endpoint` →
15304        // `path`) surfaces as a red-red test rather than as a silent
15305        // downstream diagnostic drift. Together with the exhaustive
15306        // `match` on `WitTarget` inside `label()`, adding a future
15307        // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
15308        // peer, per-edge WIT registry variants) is a compile error at
15309        // the label site — not a fall-through into the `Capability`
15310        // "no payload" default the prior raw-field-probe helper
15311        // silently landed on.
15312        assert_eq!(
15313            WitTarget::Http {
15314                endpoint: "/charge",
15315            }
15316            .label(),
15317            "\
15318:endpoint \"/charge\""
15319        );
15320        assert_eq!(
15321            WitTarget::PubSub {
15322                subject: "events.checkout.paid",
15323            }
15324            .label(),
15325            "\
15326:subject \"events.checkout.paid\""
15327        );
15328        assert_eq!(
15329            WitTarget::Store {
15330                slot: "checkout/$order",
15331            }
15332            .label(),
15333            "\
15334:slot \"checkout/$order\""
15335        );
15336        assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
15337        // Capability-arm label routes through the lifted
15338        // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
15339        // declaration per arm, next to the variant" discipline the
15340        // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
15341        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
15342        // consts already carry extends to the payload-less arm; the
15343        // byte-string equality pin below plus this label-routes-
15344        // through-the-const pin make a future rebrand on either the
15345        // const declaration or the `label()` template a build error
15346        // here rather than a downstream consumer surprise.
15347        assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
15348        assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
15349    }
15350
15351    #[test]
15352    fn wit_target_display_routes_through_label_helper() {
15353        // Fail-before-pass-after pin on the fourth (and only remaining)
15354        // typed-shape-discriminator axis to converge onto the
15355        // three-path-convergence discipline the sibling M3
15356        // [`PlacementStrategy`] (0a2f653) and M2
15357        // [`crate::supervisor::RestartStrategy`] /
15358        // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
15359        // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
15360        // through [`WitTarget::label`], so every consumer reaching for
15361        // `format!("{v}")` on a typed payload target lands on the same
15362        // stable author-facing byte-string [`WitTarget::label`] returns
15363        // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
15364        // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
15365        // `:contratos` gate seeds via [`WitTarget::label`] at
15366        // aplicacao.rs:5491 already threads through.
15367        //
15368        // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
15369        // through to the `Debug` derive's structural output
15370        // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
15371        // rather than the [`WitTarget::label`] helper's stable byte-
15372        // string (`:endpoint "/charge"` — the author-facing `:contratos`
15373        // keyword form). Every future consumer that reaches for
15374        // `format!("{target}")` — the canonical shape every user-facing
15375        // pretty-print site on the sibling typed-enum axes
15376        // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
15377        // [`crate::supervisor::RestartPolicy`]) already uses — would
15378        // silently land under a different byte-string than the
15379        // [`WitTarget::label`] callers that the duplicate-`:contratos`
15380        // diagnostic already threads through, with the mismatch
15381        // surfacing as a downstream diagnostic / graph / audit line
15382        // reading one spelling while the substrate's own gate emitted
15383        // another.
15384        //
15385        // Pin the routing here so a future
15386        // `impl std::fmt::Display for WitTarget<'_>` reimplementation
15387        // that hand-rolls the per-arm formatting instead of delegating
15388        // to [`WitTarget::label`] fails at caixa-core build time.
15389        for variant in [
15390            WitTarget::Http {
15391                endpoint: "/charge",
15392            },
15393            WitTarget::PubSub {
15394                subject: "events.checkout.paid",
15395            },
15396            WitTarget::Store {
15397                slot: "checkout/$order",
15398            },
15399            WitTarget::Capability,
15400        ] {
15401            assert_eq!(
15402                variant.to_string(),
15403                variant.label(),
15404                "WitTarget::{variant:?} Display must route through \
15405                 WitTarget::label (single source of truth: the lifted \
15406                 payload_pair 4-arm dispatch the label helper already \
15407                 threads through)"
15408            );
15409        }
15410    }
15411
15412    #[test]
15413    fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
15414        // Consumer-side pin on the three-path convergence:
15415        // [`std::fmt::Display`] agrees byte-for-byte with the
15416        // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
15417        // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
15418        // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
15419        // Pre-lift the two paths were structurally independent — the
15420        // substrate-side gate reached for `target_view.label()` while a
15421        // future downstream diagnostic / graph / audit line reaching
15422        // for `format!("{target}")` would silently land on the `Debug`
15423        // derive's structural output. Pin the two paths byte-for-byte
15424        // here so any future variant addition (M4 `Rest`/`Grpc` split
15425        // of [`WitTarget::Http`], `Queue`-shaped peer of
15426        // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
15427        // match error at [`WitTarget::payload_pair`] rather than a
15428        // silent per-consumer dispatch miss.
15429        for variant in [
15430            WitTarget::Http {
15431                endpoint: "/charge",
15432            },
15433            WitTarget::PubSub {
15434                subject: "events.checkout.paid",
15435            },
15436            WitTarget::Store {
15437                slot: "checkout/$order",
15438            },
15439            WitTarget::Capability,
15440        ] {
15441            assert_eq!(
15442                format!("{variant}"),
15443                variant.label(),
15444                "WitTarget::{variant:?} Display byte-string must match \
15445                 the AplicacaoError::ContratoDuplicate `target:` carrier \
15446                 the AplicacaoSpec::validate duplicate-`:contratos` gate \
15447                 seeds via WitTarget::label — three-path convergence: \
15448                 Display + label + payload_pair all resolve to the same \
15449                 per-arm byte-string"
15450            );
15451        }
15452    }
15453
15454    #[test]
15455    fn wit_target_payload_pair_pins_per_variant() {
15456        // Pin the per-arm `(field-name, payload)` pair single-sourced
15457        // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
15458        // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
15459        // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
15460        // and [`WitTarget::field_name`] (returns the first component)
15461        // route through. Until this lift landed [`WitTarget::label`]
15462        // dispatched on the same three arms with a per-arm
15463        // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
15464        // paired [`WitTarget::HTTP_FIELD_NAME`] /
15465        // [`WitTarget::PUBSUB_FIELD_NAME`] /
15466        // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
15467        // canonical "same shape, written N times" duplication
15468        // THEORY.md §I.3.5 promotes to a build-time concern. A future
15469        // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
15470        // [`WitTarget::Http`], `Queue`-shaped peer of
15471        // [`WitTarget::Store`]) is one match-arm edit at
15472        // [`WitTarget::payload_pair`], visible here as a compile-time
15473        // exhaustiveness error on both this pin and the label-format
15474        // pin above.
15475        assert_eq!(
15476            WitTarget::Http {
15477                endpoint: "/charge"
15478            }
15479            .payload_pair(),
15480            Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
15481        );
15482        assert_eq!(
15483            WitTarget::PubSub {
15484                subject: "events.x",
15485            }
15486            .payload_pair(),
15487            Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
15488        );
15489        assert_eq!(
15490            WitTarget::Store {
15491                slot: "checkout/$order",
15492            }
15493            .payload_pair(),
15494            Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
15495        );
15496        assert_eq!(WitTarget::Capability.payload_pair(), None);
15497    }
15498
15499    #[test]
15500    fn wit_target_field_name_pins_per_variant() {
15501        // Pin the per-arm author-facing `:contratos` payload field
15502        // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
15503        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
15504        // + returned by [`WitTarget::field_name`]. Every downstream
15505        // consumer (the [`WitContract::target`] gate's `expected:`
15506        // scalar, the [`WitTarget::label`] template's keyword prefix,
15507        // the `feira app graph` verb's `endpoint=…` prefix) routes
15508        // through the same three peer consts, so a rename on the
15509        // author-surface `(defcaixa … :contratos ((:de … :para …
15510        // :wit … :endpoint …)))` field lands in exactly one place.
15511        assert_eq!(
15512            WitTarget::Http {
15513                endpoint: "/charge"
15514            }
15515            .field_name(),
15516            Some(WitTarget::HTTP_FIELD_NAME),
15517        );
15518        assert_eq!(
15519            WitTarget::PubSub {
15520                subject: "events.x",
15521            }
15522            .field_name(),
15523            Some(WitTarget::PUBSUB_FIELD_NAME),
15524        );
15525        assert_eq!(
15526            WitTarget::Store {
15527                slot: "checkout/$order",
15528            }
15529            .field_name(),
15530            Some(WitTarget::STORE_FIELD_NAME),
15531        );
15532        // Capability arm carries no payload field — the diagnostic
15533        // never reports `expected: "capability"` because the gate's
15534        // Capability arm accepts no payload at all (it fires the
15535        // "expected: none" WrongTarget error instead), so the field-
15536        // name method returns None here rather than a placeholder.
15537        assert_eq!(WitTarget::Capability.field_name(), None);
15538
15539        // Peer const scalar values pinned so a rename on either side
15540        // (author-surface field name in the `(defcaixa …)` DSL, or
15541        // the diagnostic's `expected:` scalar) can't drift without
15542        // failing here first.
15543        assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
15544        assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
15545        assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
15546    }
15547
15548    #[test]
15549    fn wit_target_payload_pins_per_variant() {
15550        // Pin the per-arm payload scalar single-sourced onto the
15551        // [`WitTarget::payload_pair`] 4-arm dispatch and surfaced through
15552        // [`WitTarget::payload`] — the peer per-half projection to
15553        // [`WitTarget::field_name`] on the paired sub-selector axis. The
15554        // three payload-carrying arms round-trip their author-declared
15555        // scalar verbatim (`Http` → `Some("/charge")`, `PubSub` →
15556        // `Some("events.x")`, `Store` → `Some("checkout/$order")`) and
15557        // the payload-less [`WitTarget::Capability`] arm returns `None`.
15558        // Same shape as the sibling `wit_target_field_name_pins_per_variant`
15559        // (c6ec2af) pin on the Component-0 projection axis, extended
15560        // onto the Component-1 projection axis so both per-half readers
15561        // on the paired dispatch carry their own byte-shape pin.
15562        assert_eq!(
15563            WitTarget::Http {
15564                endpoint: "/charge",
15565            }
15566            .payload(),
15567            Some("/charge"),
15568        );
15569        assert_eq!(
15570            WitTarget::PubSub {
15571                subject: "events.x",
15572            }
15573            .payload(),
15574            Some("events.x"),
15575        );
15576        assert_eq!(
15577            WitTarget::Store {
15578                slot: "checkout/$order",
15579            }
15580            .payload(),
15581            Some("checkout/$order"),
15582        );
15583        assert_eq!(WitTarget::Capability.payload(), None);
15584    }
15585
15586    #[test]
15587    fn wit_target_payload_matches_payload_pair_second_component_per_variant() {
15588        // Per-variant equivalence pin: for every arm of [`WitTarget`],
15589        // `.payload()` equals `.payload_pair().map(|(_, p)| p)`
15590        // byte-for-byte. Guards the drift surface where a future refactor
15591        // that split one accessor off the shared match onto its own
15592        // dispatch — a well-meaning "inline the pair back into per-half
15593        // fields for one crate-internal caller who only wanted one half"
15594        // or a scratch `impl` shadowing the derived projection — would
15595        // silently desynchronize [`WitTarget::payload`] from the
15596        // authoritative [`WitTarget::payload_pair`] dispatch, and every
15597        // downstream consumer that thinks "the payload half of the pair"
15598        // would drift from the diagnostic / graph consumers reading the
15599        // same match through [`WitTarget::label`] / [`WitTarget::graph_label`].
15600        // Sibling to the peer [`caixa_flux::GitRefSpec`] `ref_value`
15601        // per-half projection pin (`gitrefspec_ref_pair_projects_
15602        // ref_field_name_and_ref_value_per_variant`, 655a1c0) on the
15603        // FluxCD source-controller `spec.ref.<field>` axis — same "one
15604        // paired dispatch, both per-half projections agree byte-for-
15605        // byte" discipline extended onto the M3 `:contratos` payload-
15606        // arm surface.
15607        for variant in [
15608            WitTarget::Http {
15609                endpoint: "/charge",
15610            },
15611            WitTarget::PubSub {
15612                subject: "events.checkout.paid",
15613            },
15614            WitTarget::Store {
15615                slot: "checkout/$order",
15616            },
15617            WitTarget::Capability,
15618        ] {
15619            let via_projection = variant.payload();
15620            let via_pair = variant.payload_pair().map(|(_, p)| p);
15621            assert_eq!(
15622                via_projection, via_pair,
15623                "WitTarget::{variant:?} payload() must equal \
15624                 payload_pair().map(|(_, p)| p) byte-for-byte — a \
15625                 regression that splits the two per-half projections off \
15626                 their shared match would silently desynchronize the \
15627                 payload accessor from the paired dispatch every \
15628                 diagnostic / graph consumer reads through",
15629            );
15630        }
15631    }
15632
15633    #[test]
15634    fn wit_target_http_endpoint_pins_per_variant() {
15635        // Pin the per-arm HTTP-endpoint scalar single-sourced onto the
15636        // [`WitTarget::http_endpoint`] 2-arm dispatch — the
15637        // substrate-primitive per-arm post-projection accessor every
15638        // L7-HTTP-facing consumer routes through, sibling to the peer
15639        // WitContract pre-projection [`WitContract::endpoint`] (7020470)
15640        // scalar accessor on the raw-field axis. The [`WitTarget::Http`]
15641        // arm round-trips its author-declared endpoint verbatim as
15642        // `Some("/charge")`; the three sibling arms
15643        // ([`WitTarget::PubSub`] / [`WitTarget::Store`] /
15644        // [`WitTarget::Capability`]) each return `None` because they
15645        // carry no HTTP endpoint by definition. Same fail-before-pass-
15646        // after per-variant discipline as the sibling
15647        // `wit_target_payload_pins_per_variant` (5d6dc92) /
15648        // `wit_target_field_name_pins_per_variant` (c6ec2af) /
15649        // `wit_target_payload_pair_pins_per_variant` (6788ed6) pins on
15650        // the peer pan-arm / per-half projection axes — extended onto
15651        // the per-arm HTTP-shape post-projection axis so a future
15652        // [`WitTarget`] variant addition (a `Rest`/`Grpc` split of
15653        // [`WitTarget::Http`], a `Queue`-shaped peer of
15654        // [`WitTarget::Store`]) trips a compile-time exhaustiveness
15655        // error on the sibling [`WitTarget::http_endpoint`] match arms
15656        // whose payload the L7-HTTP-shape accept-set is meant to bound.
15657        assert_eq!(
15658            WitTarget::Http {
15659                endpoint: "/charge",
15660            }
15661            .http_endpoint(),
15662            Some("/charge"),
15663        );
15664        assert_eq!(
15665            WitTarget::PubSub {
15666                subject: "events.checkout.paid",
15667            }
15668            .http_endpoint(),
15669            None,
15670        );
15671        assert_eq!(
15672            WitTarget::Store {
15673                slot: "checkout/$order",
15674            }
15675            .http_endpoint(),
15676            None,
15677        );
15678        assert_eq!(WitTarget::Capability.http_endpoint(), None);
15679    }
15680
15681    #[test]
15682    fn wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere() {
15683        // Per-variant coherence pin: for every arm of [`WitTarget`],
15684        // `.http_endpoint()` equals `.payload()` on the [`WitTarget::Http`]
15685        // arm (both project the same author-declared request-path
15686        // scalar), and returns `None` on every sibling arm regardless of
15687        // whether [`WitTarget::payload`] itself returns `Some` (PubSub /
15688        // Store carry their own payload the pan-arm accessor surfaces,
15689        // but that payload is not an HTTP endpoint — the per-arm
15690        // accessor must not leak it through the HTTP-shape channel).
15691        // Guards the drift surface where a future refactor that
15692        // conflated the per-arm HTTP projection with the pan-arm
15693        // [`WitTarget::payload`] projection — a well-meaning "one
15694        // accessor for the L7 branch, one for the graph" collapse that
15695        // routes both through the same 4-arm dispatch — would silently
15696        // widen the L7-HTTP-shape accept-set onto pub-sub / store
15697        // payloads at the caixa-mesh L7 emit branch, admitting a
15698        // `nats:pub-sub` edge's `:subject` as a Cilium L7 HTTP `path:`
15699        // rule with the operator-side apply-time symptom (Cilium's
15700        // eBPF data-plane rejects every ingress edge whose L7 filter
15701        // doesn't match the wire-format HTTP request line) far from
15702        // the source refactor. Sibling to the peer
15703        // `wit_target_payload_matches_payload_pair_second_component_
15704        // per_variant` (5d6dc92) coherence pin on the pan-arm axis —
15705        // extended onto the per-arm HTTP specialization axis so both
15706        // the pan-arm and the per-arm projections carry their own
15707        // byte-shape coherence witness against the substrate's typed
15708        // arm-family accept-set.
15709        for variant in [
15710            WitTarget::Http {
15711                endpoint: "/charge",
15712            },
15713            WitTarget::PubSub {
15714                subject: "events.checkout.paid",
15715            },
15716            WitTarget::Store {
15717                slot: "checkout/$order",
15718            },
15719            WitTarget::Capability,
15720        ] {
15721            let per_arm = variant.http_endpoint();
15722            let pan_arm = variant.payload();
15723            if variant.is_http() {
15724                assert_eq!(
15725                    per_arm, pan_arm,
15726                    "WitTarget::{variant:?} http_endpoint() must equal \
15727                     payload() on the Http arm — a per-arm-vs-pan-arm \
15728                     split would silently drift the L7 emit branch's \
15729                     path-scalar source from the graph verb's payload \
15730                     scalar source",
15731                );
15732            } else {
15733                assert_eq!(
15734                    per_arm, None,
15735                    "WitTarget::{variant:?} http_endpoint() must return \
15736                     None on non-Http arms — a leak that surfaced a \
15737                     pub-sub :subject or a key/value :slot through the \
15738                     HTTP-endpoint accessor would silently widen the \
15739                     Cilium L7 HTTP `path:` rule accept-set onto \
15740                     protocol shapes Cilium's eBPF data-plane can't \
15741                     introspect",
15742                );
15743            }
15744        }
15745    }
15746
15747    #[test]
15748    fn wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant() {
15749        // Per-variant coherence pin: for every arm of [`WitTarget`],
15750        // `.http_endpoint().is_some()` iff `.is_http()`. Guards the
15751        // drift surface where a future extension of the
15752        // [`WitTarget::http_endpoint`] accessor's accept-set (e.g. a
15753        // `Rest`/`Grpc` split of [`WitTarget::Http`] that widened the
15754        // accessor to cover both peers) landed without a paired
15755        // extension of the [`gen_platform::IsVariant`]-derived
15756        // `is_http()` predicate's accept-set, or vice versa — a
15757        // regression that split the "which arms count as HTTP-shaped
15758        // for L7-path emission?" answer between two dispatch surfaces
15759        // the substrate ships. Sibling to the peer
15760        // `wit_target_field_name_pins_per_variant` (c6ec2af) discipline
15761        // on the paired dispatch axis — extended onto the per-arm
15762        // predicate-vs-accessor coherence axis so the gen-platform
15763        // IsVariant predicate and the substrate-lifted per-arm
15764        // accessor carry one shared answer to "is this the HTTP arm?".
15765        for variant in [
15766            WitTarget::Http {
15767                endpoint: "/charge",
15768            },
15769            WitTarget::PubSub {
15770                subject: "events.checkout.paid",
15771            },
15772            WitTarget::Store {
15773                slot: "checkout/$order",
15774            },
15775            WitTarget::Capability,
15776        ] {
15777            assert_eq!(
15778                variant.http_endpoint().is_some(),
15779                variant.is_http(),
15780                "WitTarget::{variant:?} http_endpoint().is_some() must \
15781                 equal is_http() — a drift would split the L7 emit \
15782                 branch's arm-set gate from the substrate-derived \
15783                 shape-discrimination predicate on the same axis",
15784            );
15785        }
15786    }
15787
15788    #[test]
15789    fn wit_target_pubsub_subject_pins_per_variant() {
15790        // Fail-before-pass-after pin: the substrate-canonical per-arm
15791        // pub-sub-subject scalar accessor [`WitTarget::pubsub_subject`]
15792        // is the single dispatch every future pub-sub-facing consumer
15793        // routes through, sibling to the peer [`WitContract::subject`]
15794        // (63e18a0) pre-projection scalar accessor on the raw-field
15795        // axis and to the peer [`WitTarget::http_endpoint`] (5d6dc92)
15796        // post-projection per-arm accessor on the sibling HTTP-shape
15797        // axis. The [`WitTarget::PubSub`] arm round-trips its
15798        // author-declared subject verbatim as
15799        // `Some("events.checkout.paid")`; the three sibling arms each
15800        // return `None` because they carry no NATS-shaped subject by
15801        // definition. Same fail-before-pass-after per-variant discipline
15802        // as the sibling `wit_target_http_endpoint_pins_per_variant`
15803        // pin on the peer per-arm axis — extended onto the per-arm
15804        // pub-sub-shape post-projection axis so a future [`WitTarget`]
15805        // variant addition (a `Rest`/`Grpc` split of [`WitTarget::Http`],
15806        // a `Queue`-shaped peer of [`WitTarget::Store`]) trips a
15807        // compile-time exhaustiveness error on the sibling
15808        // [`WitTarget::pubsub_subject`] match arms whose payload the
15809        // pub-sub-shape accept-set is meant to bound.
15810        assert_eq!(
15811            WitTarget::PubSub {
15812                subject: "events.checkout.paid",
15813            }
15814            .pubsub_subject(),
15815            Some("events.checkout.paid"),
15816        );
15817        assert_eq!(
15818            WitTarget::Http {
15819                endpoint: "/charge",
15820            }
15821            .pubsub_subject(),
15822            None,
15823        );
15824        assert_eq!(
15825            WitTarget::Store {
15826                slot: "checkout/$order",
15827            }
15828            .pubsub_subject(),
15829            None,
15830        );
15831        assert_eq!(WitTarget::Capability.pubsub_subject(), None);
15832    }
15833
15834    #[test]
15835    fn wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere() {
15836        // Per-variant coherence pin: for every arm of [`WitTarget`],
15837        // `.pubsub_subject()` equals `.payload()` on the
15838        // [`WitTarget::PubSub`] arm (both project the same
15839        // author-declared subject scalar), and returns `None` on every
15840        // sibling arm regardless of whether [`WitTarget::payload`]
15841        // itself returns `Some` (Http / Store carry their own payload
15842        // the pan-arm accessor surfaces, but that payload is not a
15843        // pub-sub subject — the per-arm accessor must not leak it
15844        // through the pub-sub-shape channel). Sibling to the peer
15845        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
15846        // coherence pin on the per-arm HTTP-shape axis — extended onto
15847        // the per-arm pub-sub specialization axis so both per-arm
15848        // projections carry their own byte-shape coherence witness
15849        // against the substrate's typed arm-family accept-set.
15850        for variant in [
15851            WitTarget::Http {
15852                endpoint: "/charge",
15853            },
15854            WitTarget::PubSub {
15855                subject: "events.checkout.paid",
15856            },
15857            WitTarget::Store {
15858                slot: "checkout/$order",
15859            },
15860            WitTarget::Capability,
15861        ] {
15862            let per_arm = variant.pubsub_subject();
15863            let pan_arm = variant.payload();
15864            if variant.is_pubsub() {
15865                assert_eq!(
15866                    per_arm, pan_arm,
15867                    "WitTarget::{variant:?} pubsub_subject() must equal \
15868                     payload() on the PubSub arm — a per-arm-vs-pan-arm \
15869                     split would silently drift the pub-sub-shape emit \
15870                     branch's subject-scalar source from the graph verb's \
15871                     payload scalar source",
15872                );
15873            } else {
15874                assert_eq!(
15875                    per_arm, None,
15876                    "WitTarget::{variant:?} pubsub_subject() must return \
15877                     None on non-PubSub arms — a leak that surfaced an \
15878                     HTTP :endpoint or a key/value :slot through the \
15879                     pub-sub-subject accessor would silently widen the \
15880                     downstream NATS-shape accept-set onto protocol \
15881                     shapes NATS servers can't route",
15882                );
15883            }
15884        }
15885    }
15886
15887    #[test]
15888    fn wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant() {
15889        // Per-variant coherence pin: for every arm of [`WitTarget`],
15890        // `.pubsub_subject().is_some()` iff `.is_pubsub()`. Guards the
15891        // drift surface where a future extension of the
15892        // [`WitTarget::pubsub_subject`] accessor's accept-set landed
15893        // without a paired extension of the [`gen_platform::IsVariant`]-
15894        // derived `is_pubsub()` predicate's accept-set, or vice versa
15895        // — a regression that split the "which arms count as pub-sub-
15896        // shaped for subject emission?" answer between two dispatch
15897        // surfaces the substrate ships. Sibling to the peer
15898        // `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
15899        // pin on the per-arm HTTP-shape axis — extended onto the
15900        // per-arm pub-sub predicate-vs-accessor coherence axis so the
15901        // gen-platform IsVariant predicate and the substrate-lifted
15902        // per-arm accessor carry one shared answer to "is this the
15903        // PubSub arm?".
15904        for variant in [
15905            WitTarget::Http {
15906                endpoint: "/charge",
15907            },
15908            WitTarget::PubSub {
15909                subject: "events.checkout.paid",
15910            },
15911            WitTarget::Store {
15912                slot: "checkout/$order",
15913            },
15914            WitTarget::Capability,
15915        ] {
15916            assert_eq!(
15917                variant.pubsub_subject().is_some(),
15918                variant.is_pubsub(),
15919                "WitTarget::{variant:?} pubsub_subject().is_some() must \
15920                 equal is_pubsub() — a drift would split the pub-sub \
15921                 emit branch's arm-set gate from the substrate-derived \
15922                 shape-discrimination predicate on the same axis",
15923            );
15924        }
15925    }
15926
15927    #[test]
15928    fn wit_target_store_slot_pins_per_variant() {
15929        // Fail-before-pass-after pin: the substrate-canonical per-arm
15930        // key/value-store-slot scalar accessor [`WitTarget::store_slot`]
15931        // is the single dispatch every future store-facing consumer
15932        // routes through, sibling to the peer [`WitContract::slot`]
15933        // pre-projection scalar accessor on the raw-field axis and to
15934        // the peer [`WitTarget::http_endpoint`] (5d6dc92) +
15935        // [`WitTarget::pubsub_subject`] post-projection per-arm
15936        // accessors on the sibling per-payload-arm axes. The
15937        // [`WitTarget::Store`] arm round-trips its author-declared
15938        // slot verbatim as `Some("checkout/$order")`; the three
15939        // sibling arms each return `None` because they carry no
15940        // WASI-key/value slot by definition. Same fail-before-pass-
15941        // after per-variant discipline as the sibling
15942        // `wit_target_http_endpoint_pins_per_variant` +
15943        // `wit_target_pubsub_subject_pins_per_variant` pins on the
15944        // peer per-arm axes — extended onto the per-arm store-shape
15945        // post-projection axis so a future [`WitTarget`] variant
15946        // addition trips a compile-time exhaustiveness error on the
15947        // sibling [`WitTarget::store_slot`] match arms whose payload
15948        // the store-shape accept-set is meant to bound.
15949        assert_eq!(
15950            WitTarget::Store {
15951                slot: "checkout/$order",
15952            }
15953            .store_slot(),
15954            Some("checkout/$order"),
15955        );
15956        assert_eq!(
15957            WitTarget::Http {
15958                endpoint: "/charge",
15959            }
15960            .store_slot(),
15961            None,
15962        );
15963        assert_eq!(
15964            WitTarget::PubSub {
15965                subject: "events.checkout.paid",
15966            }
15967            .store_slot(),
15968            None,
15969        );
15970        assert_eq!(WitTarget::Capability.store_slot(), None);
15971    }
15972
15973    #[test]
15974    fn wit_target_store_slot_matches_payload_on_store_arm_and_is_none_elsewhere() {
15975        // Per-variant coherence pin: for every arm of [`WitTarget`],
15976        // `.store_slot()` equals `.payload()` on the
15977        // [`WitTarget::Store`] arm (both project the same
15978        // author-declared slot scalar), and returns `None` on every
15979        // sibling arm regardless of whether [`WitTarget::payload`]
15980        // itself returns `Some`. Sibling to the peer
15981        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
15982        // and `wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere`
15983        // pins on the per-arm HTTP and PubSub axes — closes the
15984        // per-arm-vs-pan-arm byte-shape coherence trio across all
15985        // three payload arms.
15986        for variant in [
15987            WitTarget::Http {
15988                endpoint: "/charge",
15989            },
15990            WitTarget::PubSub {
15991                subject: "events.checkout.paid",
15992            },
15993            WitTarget::Store {
15994                slot: "checkout/$order",
15995            },
15996            WitTarget::Capability,
15997        ] {
15998            let per_arm = variant.store_slot();
15999            let pan_arm = variant.payload();
16000            if variant.is_store() {
16001                assert_eq!(
16002                    per_arm, pan_arm,
16003                    "WitTarget::{variant:?} store_slot() must equal \
16004                     payload() on the Store arm — a per-arm-vs-pan-arm \
16005                     split would silently drift the store-shape emit \
16006                     branch's slot-scalar source from the graph verb's \
16007                     payload scalar source",
16008                );
16009            } else {
16010                assert_eq!(
16011                    per_arm, None,
16012                    "WitTarget::{variant:?} store_slot() must return \
16013                     None on non-Store arms — a leak that surfaced an \
16014                     HTTP :endpoint or a NATS :subject through the \
16015                     key/value-slot accessor would silently widen the \
16016                     downstream WASI-key/value slot accept-set onto \
16017                     protocol shapes the kv backends can't route",
16018                );
16019            }
16020        }
16021    }
16022
16023    #[test]
16024    fn wit_target_store_slot_agrees_with_is_store_predicate_per_variant() {
16025        // Per-variant coherence pin: for every arm of [`WitTarget`],
16026        // `.store_slot().is_some()` iff `.is_store()`. Guards the
16027        // drift surface where a future extension of the
16028        // [`WitTarget::store_slot`] accessor's accept-set landed
16029        // without a paired extension of the [`gen_platform::IsVariant`]-
16030        // derived `is_store()` predicate's accept-set. Sibling to the
16031        // peer `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
16032        // and `wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant`
16033        // pins — closes the per-arm predicate-vs-accessor coherence
16034        // trio across all three payload arms so the gen-platform
16035        // IsVariant predicate and the substrate-lifted per-arm
16036        // accessor carry one shared answer to "is this the Store arm?".
16037        for variant in [
16038            WitTarget::Http {
16039                endpoint: "/charge",
16040            },
16041            WitTarget::PubSub {
16042                subject: "events.checkout.paid",
16043            },
16044            WitTarget::Store {
16045                slot: "checkout/$order",
16046            },
16047            WitTarget::Capability,
16048        ] {
16049            assert_eq!(
16050                variant.store_slot().is_some(),
16051                variant.is_store(),
16052                "WitTarget::{variant:?} store_slot().is_some() must \
16053                 equal is_store() — a drift would split the store-shape \
16054                 emit branch's arm-set gate from the substrate-derived \
16055                 shape-discrimination predicate on the same axis",
16056            );
16057        }
16058    }
16059
16060    #[test]
16061    fn wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set() {
16062        // Fail-before-pass-after cross-axis pin on the trio
16063        // (`http_endpoint`, `pubsub_subject`, `store_slot`): on every
16064        // payload-carrying arm of [`WitTarget`], exactly one per-arm
16065        // accessor returns `Some(payload)` and the two peers return
16066        // `None`; and on the payload-less [`WitTarget::Capability`]
16067        // arm, all three return `None`. Guards the drift surface where
16068        // a future extension of one per-arm accessor's accept-set (e.g.
16069        // a hypothetical `Rest`/`Grpc` split of [`WitTarget::Http`]
16070        // that widened `http_endpoint` to cover both peers without
16071        // narrowing the peer `pubsub_subject` / `store_slot` accept-
16072        // sets to keep the partition mutually exclusive) landed without
16073        // threading through the peer per-arm accessors — the resulting
16074        // silent overlap would land the same edge's payload on two
16075        // downstream per-shape emit branches at once, or leak a
16076        // pub-sub subject through the store-slot channel, at renderer
16077        // emit time far from the substrate primitive's arm-widening
16078        // commit. Peer of the sibling `wit_target_field_names_are_pairwise_distinct`
16079        // 3-way pin on the payload-field-name axis — extended onto the
16080        // per-arm-accessor payload-projection axis so the substrate-
16081        // owned partition invariant is load-bearing at every per-arm
16082        // consumer's read site.
16083        let payload_variants = [
16084            (
16085                WitTarget::Http {
16086                    endpoint: "/charge",
16087                },
16088                "http",
16089            ),
16090            (
16091                WitTarget::PubSub {
16092                    subject: "events.checkout.paid",
16093                },
16094                "pubsub",
16095            ),
16096            (
16097                WitTarget::Store {
16098                    slot: "checkout/$order",
16099                },
16100                "store",
16101            ),
16102        ];
16103        for (variant, own_arm_label) in payload_variants {
16104            let own_arm_hit = match own_arm_label {
16105                "http" => variant.is_http(),
16106                "pubsub" => variant.is_pubsub(),
16107                "store" => variant.is_store(),
16108                other => panic!("unknown own-arm label {other:?}"),
16109            };
16110            let per_arm_results = [
16111                ("http_endpoint", variant.http_endpoint()),
16112                ("pubsub_subject", variant.pubsub_subject()),
16113                ("store_slot", variant.store_slot()),
16114            ];
16115            let some_count = per_arm_results.iter().filter(|(_, v)| v.is_some()).count();
16116            assert_eq!(
16117                some_count, 1,
16118                "WitTarget::{variant:?} must land exactly one per-arm \
16119                 post-projection accessor's Some result — the trio \
16120                 (http_endpoint, pubsub_subject, store_slot) must \
16121                 partition the payload arm-set; got {per_arm_results:?}",
16122            );
16123            assert!(
16124                own_arm_hit,
16125                "WitTarget::{variant:?} own-arm gen-platform predicate \
16126                 must return true on its own arm — a partition failure \
16127                 upstream of this pin",
16128            );
16129            assert!(
16130                variant.payload().is_some(),
16131                "WitTarget::{variant:?} pan-arm payload() must return \
16132                 Some on every payload-carrying arm the trio partitions",
16133            );
16134        }
16135        // The payload-less Capability arm must return None on every
16136        // per-arm accessor — the partition's terminal-fallback shape.
16137        let cap = WitTarget::Capability;
16138        assert_eq!(cap.http_endpoint(), None);
16139        assert_eq!(cap.pubsub_subject(), None);
16140        assert_eq!(cap.store_slot(), None);
16141        assert_eq!(
16142            cap.payload(),
16143            None,
16144            "WitTarget::Capability pan-arm payload() must return None — \
16145             the trio's payload-less-arm coherence witness",
16146        );
16147    }
16148
16149    #[test]
16150    fn wit_target_field_names_are_pairwise_distinct() {
16151        // Distinctness pin: if any two of the three payload-field-name
16152        // scalars ever collapse (e.g. an accidental `endpoint` copy-
16153        // paste over the `subject` const), the [`WitContract::target`]
16154        // gate's diagnostic would point authors at the wrong field —
16155        // an "expected `:endpoint`" error on a pub-sub edge would
16156        // silently misroute the fix. Same cross-axis-distinctness
16157        // discipline as the peer M3 `:placement :estrategia` variant-
16158        // discriminator scalar-value pins (cc8f749) applied to the
16159        // payload-field-name axis.
16160        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
16161        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
16162        assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
16163    }
16164
16165    #[test]
16166    fn wit_target_graph_label_routes_through_payload_pair_on_payload_arms() {
16167        // Fail-before-pass-after pin: the graph-verb payload column's
16168        // per-arm `{field}={payload}` byte-string is derived through the
16169        // single [`WitTarget::payload_pair`] 4-arm dispatch on the three
16170        // payload-carrying arms, not through a hand-rolled per-arm match
16171        // that re-projects [`WitTarget::HTTP_FIELD_NAME`] /
16172        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
16173        // inline. A future variant addition — the M4-and-later per-edge
16174        // WIT registry may split [`WitTarget::Http`] into `Rest` / `Grpc`
16175        // peers, or extend [`WitTarget::Store`] with a `Queue`-shaped
16176        // peer — becomes one match-arm edit at [`WitTarget::payload_pair`],
16177        // and both [`WitTarget::label`] (duplicate-`:contratos`
16178        // diagnostic) and [`WitTarget::graph_label`] (`feira app graph`
16179        // payload column) pick up the new arm from the same dispatch.
16180        // Prior to this lift the graph verb open-coded the 4-arm match
16181        // in caixa-feira, so a variant addition would have to be threaded
16182        // through both projections in lockstep or the graph verb would
16183        // silently drop the new arm to `(capability-only)`.
16184        for variant in [
16185            WitTarget::Http {
16186                endpoint: "/charge",
16187            },
16188            WitTarget::PubSub {
16189                subject: "events.checkout.paid",
16190            },
16191            WitTarget::Store {
16192                slot: "checkout/$order",
16193            },
16194        ] {
16195            let (field, payload) = variant
16196                .payload_pair()
16197                .expect("payload arm must expose (field, payload)");
16198            assert_eq!(
16199                variant.graph_label(),
16200                format!("{field}={payload}"),
16201                "WitTarget::{variant:?} graph_label must route the \
16202                 `{{field}}={{payload}}` template through payload_pair — \
16203                 a regression to a hand-rolled per-arm match at the graph \
16204                 verb would silently disagree with a future variant \
16205                 addition landed only at payload_pair"
16206            );
16207        }
16208    }
16209
16210    #[test]
16211    fn wit_target_graph_label_returns_capability_graph_label_const_on_capability_arm() {
16212        // Fail-before-pass-after pin on the payload-less arm: the graph
16213        // verb's `(capability-only)` byte-string routes through the
16214        // lifted [`WitTarget::CAPABILITY_GRAPH_LABEL`] const on the
16215        // [`WitTarget::Capability`] arm, not through an inline
16216        // `.to_string()` literal at the caixa-feira `cmd::app::GraphArgs::run`
16217        // per-`:contratos` payload column. Peer of the sibling
16218        // [`wit_target_label_pins_per_variant_format`] Capability-arm
16219        // assertion on the [`WitTarget::CAPABILITY_LABEL`] const —
16220        // extended here onto the third payload-less-arm consumer axis
16221        // (graph verb, sibling to the duplicate-`:contratos` diagnostic
16222        // axis and the wrong-target diagnostic axis).
16223        assert_eq!(
16224            WitTarget::Capability.graph_label(),
16225            WitTarget::CAPABILITY_GRAPH_LABEL,
16226        );
16227        assert_eq!(WitTarget::CAPABILITY_GRAPH_LABEL, "(capability-only)");
16228    }
16229
16230    #[test]
16231    fn wit_target_capability_graph_label_distinct_from_capability_label() {
16232        // Cross-consumer-axis distinctness pin: the graph-verb
16233        // payload-column const [`WitTarget::CAPABILITY_GRAPH_LABEL`]
16234        // (`(capability-only)`) and the duplicate-`:contratos` diagnostic
16235        // label const [`WitTarget::CAPABILITY_LABEL`] (`(capability — no
16236        // payload)`) surface the payload-less arm on two distinct
16237        // consumer axes; a collapse (an accidental rebrand that lands
16238        // one spelling on both consts, a copy-paste that unifies them
16239        // "for consistency") would silently merge the two byte-strings
16240        // and lose the vocabulary distinction the graph verb's
16241        // compact-column form and the diagnostic's descriptive-clause
16242        // form each carry on purpose. Peer of the sibling 4-way
16243        // [`wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`]
16244        // pin on the `ContratoWrongTarget::expected` scalar-value axis —
16245        // extended here onto the cross-consumer-axis distinctness of the
16246        // two payload-less-arm consts.
16247        assert_ne!(
16248            WitTarget::CAPABILITY_GRAPH_LABEL,
16249            WitTarget::CAPABILITY_LABEL,
16250            "WitTarget::CAPABILITY_GRAPH_LABEL (graph-verb payload column) \
16251             and WitTarget::CAPABILITY_LABEL (duplicate-`:contratos` \
16252             diagnostic) must remain distinct — a collapse would silently \
16253             merge two consumer axes onto one spelling"
16254        );
16255    }
16256
16257    #[test]
16258    fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
16259        // 4-way distinctness pin extending the sibling
16260        // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
16261        // (which covers only the HTTP / PubSub / Store payload arms)
16262        // onto the fourth scalar the shared
16263        // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
16264        // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
16265        // (`"none"`), the payload-less Capability-arm rejection scalar.
16266        //
16267        // All four [`WitTarget::HTTP_FIELD_NAME`] /
16268        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
16269        // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
16270        // dispatch surface [`WitContract::target`] writes onto the
16271        // `ContratoWrongTarget::expected` field — the same `&'static
16272        // str` axis authors read as "this WIT world's shape admits
16273        // (only|not) `:<field>`". Pairwise-distinctness is the invariant
16274        // downstream consumers rely on: an `expected: "endpoint"`
16275        // diagnostic on a Capability-shaped edge tells the author to
16276        // add a `:endpoint "…"` slot to a WIT world that admits none,
16277        // silently misrouting the fix. Until this pin landed the three
16278        // payload-arm consts were distinctness-guarded by the sibling
16279        // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
16280        // scalar (d4f54f2) sat unguarded — a rebrand collision (the
16281        // author-facing vocabulary shift from `"none"` to `"endpoint"`
16282        // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
16283        // into per-shape peers) would have silently landed one
16284        // Capability-arm rejection on a payload-arm's `expected:` byte-
16285        // string and desynchronized the diagnostic from the author's
16286        // typed shape.
16287        //
16288        // Same 4-way pairwise-distinctness pin discipline as the peer
16289        // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
16290        // (cc8f749) applies on the sibling M3 closed-set typed-enum
16291        // scalar-value dispatch axis; extends the pin trajectory the
16292        // sibling `wit_target_field_names_are_pairwise_distinct`
16293        // 3-way pin opened to cover the last unguarded corner on the
16294        // `ContratoWrongTarget::expected` scalar-value axis.
16295        //
16296        // Fail-before-pass-after locally verified by mutating
16297        // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
16298        // — this pin fires as expected; restoring passes.
16299        let all = [
16300            WitTarget::HTTP_FIELD_NAME,
16301            WitTarget::PUBSUB_FIELD_NAME,
16302            WitTarget::STORE_FIELD_NAME,
16303            WitTarget::CAPABILITY_EXPECTED,
16304        ];
16305        for (i, a) in all.iter().enumerate() {
16306            for (j, b) in all.iter().enumerate() {
16307                if i != j {
16308                    assert_ne!(
16309                        a, b,
16310                        "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
16311                         STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
16312                         pairwise distinct — got duplicate {a:?} at indices \
16313                         {i} and {j}; all four scalars thread through the \
16314                         shared `AplicacaoError::ContratoWrongTarget::expected` \
16315                         &'static str axis, so a collapse silently misdirects \
16316                         the diagnostic on which typed shape the WIT world admits",
16317                    );
16318                }
16319            }
16320        }
16321    }
16322
16323    #[test]
16324    fn wit_target_is_variant_predicates_partition_the_arm_set() {
16325        // Fail-before-pass-after pin on the
16326        // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
16327        // each of the four variants exactly one of the generated
16328        // `is_http` / `is_pubsub` / `is_store` / `is_capability`
16329        // predicates returns `true` and the other three return
16330        // `false`. Prior to this derive the only production
16331        // arm-discriminator on [`WitTarget`] — the sync-cycle
16332        // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
16333        // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
16334        // the variant that expressed no compile-time link back to
16335        // the closed-set typed dispatch a future fifth
16336        // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
16337        // split of [`WitTarget::PubSub`] into shape-specific peers,
16338        // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
16339        // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
16340        // to thread through in lockstep or the DFS exclusion would
16341        // silently disagree with the peer diagnostic templates on
16342        // which arms carry sync-versus-async semantics. Peer of the
16343        // sibling [`crate::CaixaKind`] (f5bba80),
16344        // [`PlacementStrategy`] (766ec63),
16345        // [`crate::supervisor::RestartStrategy`],
16346        // [`crate::supervisor::RestartPolicy`], and
16347        // [`crate::upgrade::UpgradeInstruction`] (915a934)
16348        // `IsVariant` derives on the sibling closed-set typed-enum
16349        // discriminator axes — extends the same one-typed-dispatch-
16350        // per-variant discipline onto the last unlifted closed-set
16351        // typed-enum discriminator on the caixa surface (the M3
16352        // mesh-slot per-`:contratos` target-arm axis), closing the
16353        // arm-discriminator convergence trajectory across every
16354        // closed-set typed enum in caixa-core.
16355        let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
16356            (
16357                WitTarget::Http { endpoint: "/x" },
16358                [true, false, false, false],
16359            ),
16360            (
16361                WitTarget::PubSub {
16362                    subject: "events.x",
16363                },
16364                [false, true, false, false],
16365            ),
16366            (
16367                WitTarget::Store { slot: "kv/x" },
16368                [false, false, true, false],
16369            ),
16370            (WitTarget::Capability, [false, false, false, true]),
16371        ];
16372        for (variant, expected) in rows {
16373            let observed = [
16374                variant.is_http(),
16375                variant.is_pubsub(),
16376                variant.is_store(),
16377                variant.is_capability(),
16378            ];
16379            assert_eq!(
16380                observed, expected,
16381                "WitTarget::{variant:?} is_* predicates must partition \
16382                 the arm set (http, pubsub, store, capability); got {observed:?}"
16383            );
16384        }
16385    }
16386
16387    #[test]
16388    fn wit_target_is_variant_predicates_are_const_fn() {
16389        // The [`gen_platform::IsVariant`] derive emits `const fn`
16390        // predicates on the peer [`crate::CaixaKind`] +
16391        // [`crate::upgrade::UpgradeInstruction`] +
16392        // [`crate::supervisor::RestartStrategy`] +
16393        // [`crate::supervisor::RestartPolicy`] +
16394        // [`PlacementStrategy`] closed-set typed enums — pin the
16395        // same posture on [`WitTarget`] so a future accidental
16396        // downgrade to non-`const` (an added runtime helper reachable
16397        // only from a non-`const` context, a manual hand-rolled
16398        // `impl` that shadows the derive-generated method) trips at
16399        // caixa-core build time rather than surfacing as a downstream
16400        // `const`-context regression far from the derive declaration.
16401        //
16402        // Unlike the peer unit-variant enums (`CaixaKind` /
16403        // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
16404        // whose `const` constructors need no arguments, the three
16405        // payload-carrying [`WitTarget`] arms are const-constructed
16406        // through `&'static str` payloads — the same `'static`
16407        // lifetime the closed-set typed enum's four-arm partition
16408        // pin above already threads through.
16409        //
16410        // The pin lives inside a `const { assert!(..) }` block so the
16411        // compiler enforces both halves (arm predicate is `const`-
16412        // callable AND returns `true` for the matching arm) at
16413        // caixa-core compile time — peer to the sibling
16414        // [`crate::CaixaKind::is_*`] const-block pin on the closed-set
16415        // typed enum arm-predicate const-callability axis.
16416        const {
16417            assert!(WitTarget::Http { endpoint: "/x" }.is_http());
16418            assert!(WitTarget::PubSub { subject: "e" }.is_pubsub());
16419            assert!(WitTarget::Store { slot: "kv/x" }.is_store());
16420            assert!(WitTarget::Capability.is_capability());
16421        }
16422    }
16423
16424    #[test]
16425    fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
16426        // Consumer-side pin on the sole production converge site:
16427        // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
16428        // edges from the synchronous-subgraph DFS via the lifted
16429        // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
16430        // predicate (rebound from the prior raw
16431        // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
16432        // variant). Byte-equivalent today (`is_pubsub` is the
16433        // derive-generated `matches!(self, Self::PubSub { .. })` by
16434        // construction, the `#[is_variant(name = "pubsub")]` override
16435        // aliasing the auto-derived `is_pub_sub` back to the sibling
16436        // [`WitContract::is_pubsub`] name); pin the behavior so a
16437        // future accidental drift (a rebind onto a peer arm
16438        // predicate, a manual hand-rolled `impl` that shadows the
16439        // derive-generated method with different semantics, a peer
16440        // arm rename that shifts which variant carries sync-versus-
16441        // async semantics) trips at caixa-core test time rather than
16442        // at some downstream operator's runtime dispatch far from the
16443        // rebind commit.
16444        //
16445        // The fixture constructs a two-Servico Aplicacao with one
16446        // pub-sub edge that would close a sync-cycle if the DFS did
16447        // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
16448        // pub-sub exclusion means the DFS sees only the `b → a` HTTP
16449        // edge, which is not a cycle. A regression in the converge
16450        // (a rebind that reads the pub-sub arm as sync) would report
16451        // `AplicacaoError::ContratoCycle`.
16452        let s = AplicacaoSpec {
16453            membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
16454            contratos: vec![
16455                // Pub-sub edge: DFS must skip via is_pubsub().
16456                WitContract {
16457                    de: "a".into(),
16458                    para: "b".into(),
16459                    wit: "nats:pub-sub".into(),
16460                    endpoint: None,
16461                    subject: Some("events.x".into()),
16462                    slot: None,
16463                },
16464                // HTTP edge: DFS must include.
16465                WitContract {
16466                    de: "b".into(),
16467                    para: "a".into(),
16468                    wit: "wasi:http/proxy".into(),
16469                    endpoint: Some("/x".into()),
16470                    subject: None,
16471                    slot: None,
16472                },
16473            ],
16474            politicas: MeshPolicy::default(),
16475            placement: Placement {
16476                estrategia: PlacementStrategy::Replicated,
16477                clusters: vec!["rio".into()],
16478                affinity: None,
16479                shard_key: None,
16480            },
16481            entrada: None,
16482        };
16483        s.validate()
16484            .expect("pub-sub edge must be excluded from sync-cycle DFS");
16485    }
16486
16487    #[test]
16488    fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
16489        // Consumer-side pin: the same three peer consts thread through
16490        // both the [`WitTarget::label`] template (leading-`:` keyword
16491        // prefix in the duplicate-`:contratos` diagnostic) and the
16492        // [`WitContract::target`] gate's [`AplicacaoError::
16493        // ContratoMissingTarget`] `expected:` scalar (the field the
16494        // author needs to add). Pin both routes at once so a future
16495        // refactor can't accidentally split them onto separate string
16496        // literals — the "one place, everywhere reaches for it"
16497        // invariant the peer const set carries.
16498        let http_label = WitTarget::Http { endpoint: "/x" }.label();
16499        assert!(
16500            http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
16501            "label must lead with :{} keyword (got {http_label:?})",
16502            WitTarget::HTTP_FIELD_NAME,
16503        );
16504
16505        let mut s = three_member_spec();
16506        s.contratos.push(WitContract {
16507            de: "cart".into(),
16508            para: "catalog".into(),
16509            wit: "kafka:topic".into(),
16510            endpoint: None,
16511            subject: None,
16512            slot: None,
16513        });
16514        match s.validate().unwrap_err() {
16515            AplicacaoError::ContratoMissingTarget { expected, .. } => {
16516                assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
16517            }
16518            other => panic!("expected ContratoMissingTarget, got {other:?}"),
16519        }
16520    }
16521
16522    #[test]
16523    fn duplicate_pubsub_diagnostic_names_offending_subject() {
16524        // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
16525        // on the pub-sub target axis: the duplicate-edge diagnostic
16526        // must name the `:subject` payload verbatim (not just the
16527        // `(de, para, wit)` triple). Prior to lifting the label onto
16528        // [`WitTarget::label`] the diagnostic derived the label from
16529        // raw [`WitContract`] `Option<String>` probes — a future
16530        // `WitTarget` variant addition (M4 per-edge WIT registry)
16531        // would silently fall through to the `Capability` "no
16532        // payload" default without a compiler warning. Pinning the
16533        // pub-sub arm's format closes the second of three
16534        // payload-carrying `WitTarget` arms this diagnostic threads
16535        // through.
16536        let mut s = three_member_spec();
16537        let pubsub = WitContract {
16538            de: "payment".into(),
16539            para: "cart".into(),
16540            wit: "nats:pub-sub".into(),
16541            endpoint: None,
16542            subject: Some("events.checkout.paid".into()),
16543            slot: None,
16544        };
16545        s.contratos.push(pubsub.clone());
16546        s.contratos.push(pubsub);
16547        let err = s.validate().unwrap_err();
16548        let msg = format!("{err}");
16549        assert!(
16550            msg.contains(":subject \"events.checkout.paid\""),
16551            "duplicate-pubsub diagnostic must name the offending \
16552             :subject payload (got: {msg:?})"
16553        );
16554    }
16555
16556    #[test]
16557    fn duplicate_store_diagnostic_names_offending_slot() {
16558        // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
16559        // key-value target axis: the diagnostic must name the `:slot`
16560        // payload verbatim. Third of three payload-carrying
16561        // `WitTarget` arms this diagnostic threads through, closing
16562        // the per-arm label pin trilogy (`Http` — 6841,
16563        // `PubSub` + `Store` — this test + peer above).
16564        let mut s = three_member_spec();
16565        let store = WitContract {
16566            de: "cart".into(),
16567            para: "payment".into(),
16568            wit: "wasi:keyvalue/store".into(),
16569            endpoint: None,
16570            subject: None,
16571            slot: Some("checkout/$orderId".into()),
16572        };
16573        s.contratos
16574            .retain(|c| !(c.de == "cart" && c.para == "payment"));
16575        s.contratos.push(store.clone());
16576        s.contratos.push(store);
16577        let err = s.validate().unwrap_err();
16578        let msg = format!("{err}");
16579        assert!(
16580            msg.contains(":slot \"checkout/$orderId\""),
16581            "duplicate-store diagnostic must name the offending :slot \
16582             payload (got: {msg:?})"
16583        );
16584    }
16585
16586    #[test]
16587    fn rejects_entrada_path_without_leading_slash() {
16588        let mut s = three_member_spec();
16589        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
16590        let err = s.validate().unwrap_err();
16591        assert!(
16592            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
16593            "got {err:?}"
16594        );
16595    }
16596
16597    #[test]
16598    fn rejects_empty_entrada_path() {
16599        let mut s = three_member_spec();
16600        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), String::new()];
16601        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
16602    }
16603
16604    #[test]
16605    fn rejects_duplicate_entrada_paths() {
16606        let mut s = three_member_spec();
16607        s.entrada.as_mut().unwrap().paths = vec![
16608            "/api/cart".into(),
16609            "/api/products".into(),
16610            "/api/cart".into(),
16611        ];
16612        let err = s.validate().unwrap_err();
16613        assert!(
16614            matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
16615            "got {err:?}"
16616        );
16617    }
16618
16619    #[test]
16620    fn rejects_zero_entrada_port() {
16621        let mut s = three_member_spec();
16622        s.entrada.as_mut().unwrap().port = 0;
16623        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
16624    }
16625
16626    // ── :entrada :paths value-shape gate ─────────────────────────────
16627    //
16628    // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
16629    // sibling `:paths` axis. Every authoring footgun the K8s Gateway
16630    // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
16631    // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
16632    // time now becomes a caixa-build-time `EntradaPathInvalid` with
16633    // the offending `:paths` entry named verbatim.
16634
16635    #[test]
16636    fn rejects_entrada_path_with_query() {
16637        // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
16638        // silently passed validate and the Gateway API webhook
16639        // rejected it at apply time with no source citation.
16640        let mut s = three_member_spec();
16641        s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
16642        let err = s.validate().unwrap_err();
16643        assert!(
16644            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16645                if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
16646            "got {err:?}"
16647        );
16648    }
16649
16650    #[test]
16651    fn rejects_entrada_path_with_fragment() {
16652        let mut s = three_member_spec();
16653        s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
16654        let err = s.validate().unwrap_err();
16655        assert!(
16656            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16657                if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
16658            "got {err:?}"
16659        );
16660    }
16661
16662    #[test]
16663    fn rejects_entrada_path_with_space() {
16664        let mut s = three_member_spec();
16665        s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
16666        let err = s.validate().unwrap_err();
16667        assert!(
16668            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16669                if path == "/api/my cart" && reason.contains("whitespace")),
16670            "got {err:?}"
16671        );
16672    }
16673
16674    #[test]
16675    fn rejects_entrada_path_with_tab() {
16676        let mut s = three_member_spec();
16677        s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
16678        let err = s.validate().unwrap_err();
16679        assert!(
16680            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16681                if path == "/api/\tcart" && reason.contains("whitespace")),
16682            "got {err:?}"
16683        );
16684    }
16685
16686    #[test]
16687    fn rejects_entrada_path_with_control_char() {
16688        // 0x01 (SOH) — a non-whitespace control char surfaces the
16689        // distinct "control character" reason arm, separate from
16690        // the whitespace arm. Pinned so a future refactor that
16691        // collapses the two arms can't accidentally drop the more
16692        // self-locating diagnostic.
16693        let mut s = three_member_spec();
16694        s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
16695        let err = s.validate().unwrap_err();
16696        assert!(
16697            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16698                if path == "/api/\x01cart" && reason.contains("control character")),
16699            "got {err:?}"
16700        );
16701    }
16702
16703    #[test]
16704    fn rejects_entrada_path_with_non_ascii() {
16705        // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
16706        // unreserved-set rule rejects. The Gateway API webhook
16707        // rejects literal non-ASCII bytes; percent-encoding is the
16708        // only way to author non-ASCII in a path.
16709        let mut s = three_member_spec();
16710        s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
16711        let err = s.validate().unwrap_err();
16712        assert!(
16713            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16714                if path == "/api/café" && reason.contains("non-ASCII")),
16715            "got {err:?}"
16716        );
16717    }
16718
16719    #[test]
16720    fn rejects_entrada_path_with_consecutive_slashes() {
16721        let mut s = three_member_spec();
16722        s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
16723        let err = s.validate().unwrap_err();
16724        assert!(
16725            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16726                if path == "/api//cart" && reason.contains("consecutive `/`")),
16727            "got {err:?}"
16728        );
16729    }
16730
16731    #[test]
16732    fn rejects_entrada_path_with_dot_segment() {
16733        let mut s = three_member_spec();
16734        s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
16735        let err = s.validate().unwrap_err();
16736        assert!(
16737            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16738                if path == "/api/./cart" && reason.contains("`.` segment")),
16739            "got {err:?}"
16740        );
16741    }
16742
16743    #[test]
16744    fn rejects_entrada_path_with_trailing_dot_segment() {
16745        // The bare `/.` and the trailing `/foo/.` are both rejected
16746        // by the Gateway API webhook; pinned separately so a future
16747        // narrowing that catches only the inner form surfaces here.
16748        let mut s = three_member_spec();
16749        s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
16750        let err = s.validate().unwrap_err();
16751        assert!(
16752            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16753                if path == "/api/." && reason.contains("`.` segment")),
16754            "got {err:?}"
16755        );
16756    }
16757
16758    #[test]
16759    fn rejects_entrada_path_with_parent_segment() {
16760        let mut s = three_member_spec();
16761        s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
16762        let err = s.validate().unwrap_err();
16763        assert!(
16764            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16765                if path == "/api/../etc" && reason.contains("`..` parent-segment")),
16766            "got {err:?}"
16767        );
16768    }
16769
16770    #[test]
16771    fn rejects_entrada_path_with_trailing_parent_segment() {
16772        // Trailing `/..` — symmetric arm of the parent-segment rule,
16773        // pinned separately so a future relaxation that only checks
16774        // the inner form (`/../`) surfaces here.
16775        let mut s = three_member_spec();
16776        s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
16777        let err = s.validate().unwrap_err();
16778        assert!(
16779            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16780                if path == "/api/.." && reason.contains("`..` parent-segment")),
16781            "got {err:?}"
16782        );
16783    }
16784
16785    #[test]
16786    fn rejects_entrada_path_too_long() {
16787        // 1025-byte path — one over the Gateway API HTTPPathMatch.value
16788        // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
16789        // ASCII-alphanumeric body so only the length rule fires.
16790        let mut s = three_member_spec();
16791        let big = format!("/api/{}", "a".repeat(1020));
16792        assert_eq!(big.len(), 1025);
16793        s.entrada.as_mut().unwrap().paths = vec![big.clone()];
16794        let err = s.validate().unwrap_err();
16795        assert!(
16796            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16797                if path == &big && reason.contains("max length of 1024")),
16798            "got {err:?}"
16799        );
16800    }
16801
16802    #[test]
16803    fn entrada_path_max_length_validates() {
16804        // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
16805        // maxLength cap. Boundary pin: drift in the cap surfaces here
16806        // and at `rejects_entrada_path_too_long` simultaneously.
16807        let mut s = three_member_spec();
16808        let big = format!("/api/{}", "a".repeat(1019));
16809        assert_eq!(big.len(), 1024);
16810        s.entrada.as_mut().unwrap().paths = vec![big];
16811        s.validate().unwrap();
16812    }
16813
16814    #[test]
16815    fn entrada_accepts_canonical_paths() {
16816        // Positive-control sweep — every form the Gateway API
16817        // apiserver accepts must round-trip through validate. Covers
16818        // the root catch-all, plain paths, dot-prefixed segments
16819        // (hidden-file-style, distinct from `.` and `..` segments
16820        // which are rejected), digit-bearing segments, the canonical
16821        // route-template `:param` form (`:` is RFC 3986 reserved-set
16822        // valid in paths), trailing-slash form, percent-encoded
16823        // segments, and an interior `..` *substring* (`/foo..bar` is
16824        // not the `..` segment and is allowed).
16825        for path in [
16826            "/",
16827            "/api/cart",
16828            "/healthz",
16829            "/api/.config",
16830            "/v1/products",
16831            "/products/:id",
16832            "/api/cart/",
16833            "/api/caf%C3%A9",
16834            "/foo..bar",
16835            "/...",
16836        ] {
16837            let mut s = three_member_spec();
16838            s.entrada.as_mut().unwrap().paths = vec![path.into()];
16839            s.validate()
16840                .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
16841        }
16842    }
16843
16844    #[test]
16845    fn entrada_path_empty_takes_precedence_over_invalid() {
16846        // Ordering pin: `EntradaPathEmpty` is the more self-locating
16847        // diagnostic on `""` and must lead — `validate_entrada_path`
16848        // is only reached after the empty-check fires at the call
16849        // site. (The predicate itself defends against direct
16850        // invocation by returning the same error on `""`.)
16851        let mut s = three_member_spec();
16852        s.entrada.as_mut().unwrap().paths = vec![String::new()];
16853        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
16854    }
16855
16856    #[test]
16857    fn entrada_path_not_absolute_takes_precedence_over_invalid() {
16858        // Ordering pin: a path without a leading `/` surfaces the
16859        // narrower `EntradaPathNotAbsolute` diagnostic first; the
16860        // value-shape gate is only consulted on paths that already
16861        // satisfy the absolute-prefix invariant.
16862        let mut s = three_member_spec();
16863        // `bad path` would fire the whitespace rule under the
16864        // value-shape gate, but missing-leading-`/` is the more
16865        // self-locating diagnostic.
16866        s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
16867        let err = s.validate().unwrap_err();
16868        assert!(
16869            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
16870            "got {err:?}"
16871        );
16872    }
16873
16874    #[test]
16875    fn entrada_path_invalid_fires_before_duplicate_check() {
16876        // Ordering pin: a malformed path on the *first* entry of a
16877        // would-be duplicate pair fires the value-shape gate before
16878        // the duplicate gate, mirroring the
16879        // `placement_cluster_invalid_fires_before_duplicate_check`
16880        // (6cbb900) pattern on the peer axis.
16881        let mut s = three_member_spec();
16882        s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
16883        let err = s.validate().unwrap_err();
16884        assert!(
16885            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
16886            "got {err:?}"
16887        );
16888    }
16889
16890    #[test]
16891    fn entrada_path_diagnostic_carries_offending_path() {
16892        // Diagnostic-shape pin — the offending path + a non-empty
16893        // reason flow through verbatim so the author can grep their
16894        // caixa.lisp for `:paths` and fix it in one edit. Same shape
16895        // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
16896        let mut s = three_member_spec();
16897        s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
16898        let err = s.validate().unwrap_err();
16899        match err {
16900            AplicacaoError::EntradaPathInvalid { path, reason } => {
16901                assert_eq!(path, "/api?q=1");
16902                assert!(!reason.is_empty(), "reason field must be non-empty");
16903            }
16904            other => panic!("expected EntradaPathInvalid, got {other:?}"),
16905        }
16906    }
16907
16908    #[test]
16909    fn rejects_entrada_path_with_curly_brace_template_form() {
16910        // Per-axis pin on the shared `is_gateway_api_http_path`
16911        // reserved-byte arm: the canonical "I wrote an OpenAPI
16912        // path-template `{id}` instead of the Gateway API `:id` form"
16913        // footgun the K8s apiserver would otherwise catch at admission
16914        // time on every `HTTPRoute.spec.rules[].matches[].path.value`
16915        // landing site, far from the caixa.lisp. Surfaces as
16916        // `EntradaPathInvalid` carrying the offending path verbatim
16917        // plus the canonical `%7B`/`%7D` percent-encoding remediation
16918        // — the substrate-side `gateway_api_http_path_rejects_every_
16919        // reserved_printable_ascii_byte` predicate-level sweep pins the
16920        // full eleven-byte set; this per-axis pin confirms the
16921        // diagnostic flows through to the `EntradaPathInvalid` variant.
16922        let mut s = three_member_spec();
16923        s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
16924        let err = s.validate().unwrap_err();
16925        assert!(
16926            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16927                if path == "/api/cart/{id}"
16928                    && reason.contains("reserved character")
16929                    && reason.contains("'{'")
16930                    && reason.contains("%7B")),
16931            "got {err:?}"
16932        );
16933    }
16934
16935    #[test]
16936    fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
16937        // Per-axis peer of `rejects_entrada_path_with_curly_brace_
16938        // template_form` on the sibling `:contratos :endpoint` axis.
16939        // Same shared `is_gateway_api_http_path` reserved-byte arm
16940        // fires through `ContratoEndpointInvalid`, with the offending
16941        // endpoint + `:de` + `:para` + reason flowing through verbatim.
16942        // Pins that the lifted predicate's tightening lands on both
16943        // caller axes simultaneously — one source of truth for the
16944        // Gateway API HTTPPathMatch.value accepted set.
16945        let err = contrato_endpoint_err("/api/cart/{id}");
16946        assert!(
16947            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
16948                if endpoint == "/api/cart/{id}"
16949                    && reason.contains("reserved character")
16950                    && reason.contains("'{'")
16951                    && reason.contains("%7B")),
16952            "got {err:?}"
16953        );
16954    }
16955
16956    // ── :entrada :host value-shape gate ──────────────────────────────
16957    //
16958    // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
16959    // the sibling `:host` axis. Every authoring footgun the K8s
16960    // Gateway API v1 apiserver would catch at admission time becomes
16961    // a caixa-build-time `EntradaHostInvalid` with the offending
16962    // `:host` named verbatim. Same diagnostic shape as
16963    // `MembroVersaoInvalid` (9888b13).
16964
16965    #[test]
16966    fn rejects_entrada_host_with_scheme() {
16967        // Fail-before-pass-after pin — pre-gate codebases silently
16968        // accepted `https://…` and the apiserver rejected it at apply
16969        // time with no source citation.
16970        let mut s = three_member_spec();
16971        s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
16972        let err = s.validate().unwrap_err();
16973        assert!(
16974            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
16975                if host == "https://checkout.quero.cloud"),
16976            "got {err:?}"
16977        );
16978    }
16979
16980    #[test]
16981    fn rejects_entrada_host_with_port() {
16982        // The `:8080` port suffix is the canonical "I forgot the port
16983        // belongs in `:entrada :port`" footgun. The top-level `:` arm
16984        // (introduced after the per-label loop-only impl silently
16985        // surfaced a deep "label \"cloud:8080\" contains invalid
16986        // character ':'" leak) names the canonical fix verbatim — the
16987        // `:entrada :port` slot.
16988        let mut s = three_member_spec();
16989        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
16990        let err = s.validate().unwrap_err();
16991        assert!(
16992            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
16993                if host == "checkout.quero.cloud:8080"
16994                && reason.contains(":entrada :port")),
16995            "got {err:?}"
16996        );
16997    }
16998
16999    #[test]
17000    fn rejects_entrada_host_with_trailing_colon() {
17001        // Trailing `:` (e.g. an in-progress `:host "example.com:"`
17002        // edit) — the per-label loop would land it as a deep
17003        // "label \"com:\" must start and end with an alphanumeric"
17004        // / "contains invalid character ':'" leak. The top-level
17005        // `:` arm pre-empts with the canonical `:port` slot
17006        // diagnostic.
17007        let mut s = three_member_spec();
17008        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
17009        let err = s.validate().unwrap_err();
17010        assert!(
17011            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
17012                if host == "checkout.quero.cloud:"
17013                && reason.contains(":entrada :port")),
17014            "got {err:?}"
17015        );
17016    }
17017
17018    #[test]
17019    fn rejects_entrada_host_unbracketed_ipv6_literal() {
17020        // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
17021        // literals across the board (peer with `rejects_entrada_host_
17022        // ipv4_literal` above for the four-label-all-digit IPv4 arm).
17023        // Before this top-level `:` arm landed the per-label loop
17024        // surfaced a single-label byte-class diagnostic that named the
17025        // `:` byte but not the IP-literal prohibition. The top-level
17026        // `:` arm names both the `:port` slot and the IP-literal
17027        // prohibition verbatim, so an author whose `:host "2001:..."`
17028        // value lands here gets a self-locating fix either way.
17029        let mut s = three_member_spec();
17030        s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
17031        let err = s.validate().unwrap_err();
17032        assert!(
17033            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
17034                if host == "2001:db8::1"
17035                && reason.contains("IPv6")),
17036            "got {err:?}"
17037        );
17038    }
17039
17040    #[test]
17041    fn rejects_entrada_host_wildcard_with_port() {
17042        // Wildcard host with port suffix — the `*.` strip and the
17043        // per-label loop on `["foo", "quero", "cloud:8080"]` would
17044        // surface the deep byte-class leak. The top-level `:` arm sits
17045        // upstream of the `*.` strip, so it names the canonical `:port`
17046        // fix verbatim regardless of whether the host is wildcard-led.
17047        let mut s = three_member_spec();
17048        s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
17049        let err = s.validate().unwrap_err();
17050        assert!(
17051            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
17052                if host == "*.quero.cloud:8080"
17053                && reason.contains(":entrada :port")),
17054            "got {err:?}"
17055        );
17056    }
17057
17058    #[test]
17059    fn rejects_entrada_host_with_path() {
17060        let mut s = three_member_spec();
17061        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
17062        let err = s.validate().unwrap_err();
17063        assert!(
17064            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
17065                if host == "checkout.quero.cloud/api"),
17066            "got {err:?}"
17067        );
17068    }
17069
17070    #[test]
17071    fn rejects_entrada_host_with_uppercase() {
17072        // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
17073        // rejected, not silently lower-cased.
17074        let mut s = three_member_spec();
17075        s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
17076        let err = s.validate().unwrap_err();
17077        assert!(
17078            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17079                if reason.contains("uppercase")),
17080            "got {err:?}"
17081        );
17082    }
17083
17084    #[test]
17085    fn rejects_entrada_host_with_underscore() {
17086        // RFC 1123 allows `[a-z0-9-]` only; underscore is the
17087        // canonical "I'm thinking of HTTP cookies / SRV records" leak.
17088        let mut s = three_member_spec();
17089        s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
17090        let err = s.validate().unwrap_err();
17091        assert!(
17092            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17093                if reason.contains('_')),
17094            "got {err:?}"
17095        );
17096    }
17097
17098    #[test]
17099    fn rejects_entrada_host_ipv4_literal() {
17100        // Gateway API v1 explicitly forbids IP literals as Hostnames.
17101        let mut s = three_member_spec();
17102        s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
17103        let err = s.validate().unwrap_err();
17104        assert!(
17105            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17106                if reason.contains("IPv4")),
17107            "got {err:?}"
17108        );
17109    }
17110
17111    #[test]
17112    fn rejects_entrada_host_with_trailing_dot() {
17113        // The Gateway API regex anchors at end-of-string with no
17114        // trailing `.` allowance — the FQDN root-dot form is rejected.
17115        let mut s = three_member_spec();
17116        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
17117        let err = s.validate().unwrap_err();
17118        assert!(
17119            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
17120                if host == "checkout.quero.cloud."),
17121            "got {err:?}"
17122        );
17123    }
17124
17125    #[test]
17126    fn rejects_entrada_host_with_leading_dot() {
17127        let mut s = three_member_spec();
17128        s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
17129        let err = s.validate().unwrap_err();
17130        assert!(
17131            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17132                if reason.contains("empty label")),
17133            "got {err:?}"
17134        );
17135    }
17136
17137    #[test]
17138    fn rejects_entrada_host_with_consecutive_dots() {
17139        let mut s = three_member_spec();
17140        s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
17141        let err = s.validate().unwrap_err();
17142        assert!(
17143            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17144                if reason.contains("empty label")),
17145            "got {err:?}"
17146        );
17147    }
17148
17149    #[test]
17150    fn rejects_entrada_host_with_leading_hyphen_label() {
17151        let mut s = three_member_spec();
17152        s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
17153        let err = s.validate().unwrap_err();
17154        assert!(
17155            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17156                if reason.contains("alphanumeric")),
17157            "got {err:?}"
17158        );
17159    }
17160
17161    #[test]
17162    fn rejects_entrada_host_with_trailing_hyphen_label() {
17163        let mut s = three_member_spec();
17164        s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
17165        let err = s.validate().unwrap_err();
17166        assert!(
17167            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17168                if reason.contains("alphanumeric")),
17169            "got {err:?}"
17170        );
17171    }
17172
17173    #[test]
17174    fn rejects_entrada_host_with_inner_wildcard() {
17175        // Gateway API allows `*` only as the first label (`*.foo`);
17176        // any inner or trailing `*` is rejected.
17177        let mut s = three_member_spec();
17178        s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
17179        let err = s.validate().unwrap_err();
17180        assert!(
17181            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17182                if reason.contains("wildcard")),
17183            "got {err:?}"
17184        );
17185    }
17186
17187    #[test]
17188    fn rejects_entrada_host_bare_wildcard() {
17189        // `*.` with no domain is meaningless; Gateway API rejects it.
17190        let mut s = three_member_spec();
17191        s.entrada.as_mut().unwrap().host = "*.".into();
17192        let err = s.validate().unwrap_err();
17193        assert!(
17194            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17195                if reason.contains("wildcard")),
17196            "got {err:?}"
17197        );
17198    }
17199
17200    #[test]
17201    fn rejects_entrada_host_with_whitespace() {
17202        let mut s = three_member_spec();
17203        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
17204        let err = s.validate().unwrap_err();
17205        assert!(
17206            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17207                if reason.contains("whitespace")),
17208            "got {err:?}"
17209        );
17210    }
17211
17212    #[test]
17213    fn rejects_entrada_host_space_names_offending_byte() {
17214        // Embedded space in the `:entrada :host` axis surfaces the
17215        // byte-naming diagnostic through the lifted
17216        // `find_ascii_whitespace_byte` predicate. Peer with the
17217        // sibling `parse_rejects_leading_whitespace` pins on
17218        // `supervisor::duration_codec` (a7ae622) — same "the
17219        // diagnostic carries the offending byte's `0x{b:02x}` shape"
17220        // discipline extended from the shared duration codec to the
17221        // Gateway API v1 Hostname axis.
17222        let mut s = three_member_spec();
17223        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
17224        let err = s.validate().unwrap_err();
17225        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
17226            panic!("expected EntradaHostInvalid, got {err:?}");
17227        };
17228        assert!(
17229            reason.contains("ASCII whitespace byte"),
17230            "expected byte-naming diagnostic, got {reason:?}"
17231        );
17232        assert!(
17233            reason.contains("0x20"),
17234            "expected offending space byte 0x20, got {reason:?}"
17235        );
17236    }
17237
17238    #[test]
17239    fn rejects_entrada_host_tab_names_offending_byte() {
17240        // Embedded tab byte in the `:entrada :host` axis — the
17241        // canonical paste-from-YAML-block-scalar / paste-from-
17242        // indented-doc footgun. Pins that the lifted predicate covers
17243        // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
17244        // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
17245        // not just the leading-space case the pre-lift `.bytes().any`
17246        // arm's opaque "must not contain whitespace" reason already
17247        // covered. Peer with `parse_rejects_tab_byte` on
17248        // `supervisor::duration_codec` (a7ae622).
17249        let mut s = three_member_spec();
17250        s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
17251        let err = s.validate().unwrap_err();
17252        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
17253            panic!("expected EntradaHostInvalid, got {err:?}");
17254        };
17255        assert!(
17256            reason.contains("ASCII whitespace byte"),
17257            "expected byte-naming diagnostic, got {reason:?}"
17258        );
17259        assert!(
17260            reason.contains("0x09"),
17261            "expected offending tab byte 0x09, got {reason:?}"
17262        );
17263    }
17264
17265    #[test]
17266    fn rejects_entrada_host_lf_names_offending_byte() {
17267        // Embedded LF byte in the `:entrada :host` axis — the
17268        // canonical paste-from-shell-heredoc / paste-from-multiline-
17269        // doc footgun the caixa-mesh YAML emitter would silently
17270        // reinterpret at the Gateway API v1 HTTPRoute admission
17271        // layer (an embedded LF byte in a YAML plain scalar either
17272        // truncates the value at the emitter or crashes the parser
17273        // on the k8s-apiserver side). Pins the third representative
17274        // of the full ASCII-whitespace set through the shared
17275        // predicate.
17276        let mut s = three_member_spec();
17277        s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
17278        let err = s.validate().unwrap_err();
17279        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
17280            panic!("expected EntradaHostInvalid, got {err:?}");
17281        };
17282        assert!(
17283            reason.contains("ASCII whitespace byte"),
17284            "expected byte-naming diagnostic, got {reason:?}"
17285        );
17286        assert!(
17287            reason.contains("0x0a"),
17288            "expected offending LF byte 0x0a, got {reason:?}"
17289        );
17290    }
17291
17292    #[test]
17293    fn rejects_entrada_host_nbsp_names_offending_codepoint() {
17294        // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
17295        // axis — the canonical paste-from-typography /
17296        // paste-from-word-processor footgun. Before the non-ASCII
17297        // Unicode `White_Space` scan lifted through the shared
17298        // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
17299        // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
17300        // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
17301        // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
17302        // with the far-from-source `label "…" must start and end
17303        // with an alphanumeric` diagnostic — burying the
17304        // paste-from-typography origin under a label-shape leak.
17305        // Peer with the sibling non-ASCII-whitespace pins at
17306        // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
17307        // — 1b75b38), `limits::parse_duration`,
17308        // `limits::parse_millicores`, and the shared duration codec
17309        // — same "the diagnostic carries the offending Unicode
17310        // codepoint's `U+XXXX` shape" discipline extended from every
17311        // typed-magnitude codec to the Gateway API v1 Hostname axis.
17312        let mut s = three_member_spec();
17313        s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
17314        let err = s.validate().unwrap_err();
17315        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
17316            panic!("expected EntradaHostInvalid, got {err:?}");
17317        };
17318        assert!(
17319            reason.contains("non-ASCII Unicode whitespace character"),
17320            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
17321        );
17322        assert!(
17323            reason.contains("U+00A0"),
17324            "expected offending NBSP codepoint U+00A0, got {reason:?}"
17325        );
17326    }
17327
17328    #[test]
17329    fn rejects_entrada_host_line_separator_names_offending_codepoint() {
17330        // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
17331        // `:entrada :host` axis — the canonical paste-from-web-doc /
17332        // paste-from-published-HTML footgun. `char::is_whitespace`
17333        // returns true for `U+2028` per the Unicode `White_Space`
17334        // property, so `str::trim` at any downstream site would
17335        // silently strip it — same drift class as NBSP but on a
17336        // different codepoint region. Pins the second representative
17337        // (non-Latin-1 `char::is_whitespace` member) through the
17338        // shared predicate. Peer with
17339        // `parse_byte_size_rejects_internal_line_separator` on
17340        // `limits::parse_byte_size` (1b75b38).
17341        let mut s = three_member_spec();
17342        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
17343        let err = s.validate().unwrap_err();
17344        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
17345            panic!("expected EntradaHostInvalid, got {err:?}");
17346        };
17347        assert!(
17348            reason.contains("non-ASCII Unicode whitespace character"),
17349            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
17350        );
17351        assert!(
17352            reason.contains("U+2028"),
17353            "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
17354        );
17355    }
17356
17357    #[test]
17358    fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
17359        // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
17360        // labels in the `:entrada :host` axis — the canonical
17361        // paste-from-CJK-typography footgun (CJK IMEs default to
17362        // full-width whitespace when the space bar is pressed in
17363        // Japanese / Chinese input modes). Pins the third
17364        // representative of the non-ASCII Unicode `White_Space` set
17365        // through the shared predicate: the CJK block, distinct from
17366        // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
17367        // SEPARATOR `U+2028` — covering the same axis breadth the
17368        // sibling `parse_byte_size_rejects_trailing_ideographic_space`
17369        // (1b75b38) pins on `limits::parse_byte_size`.
17370        let mut s = three_member_spec();
17371        s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
17372        let err = s.validate().unwrap_err();
17373        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
17374            panic!("expected EntradaHostInvalid, got {err:?}");
17375        };
17376        assert!(
17377            reason.contains("non-ASCII Unicode whitespace character"),
17378            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
17379        );
17380        assert!(
17381            reason.contains("U+3000"),
17382            "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
17383        );
17384    }
17385
17386    #[test]
17387    fn rejects_entrada_host_too_long() {
17388        // Total length cap = 253; build a 254-byte host out of two
17389        // 63-byte labels + one 62-byte label + dots.
17390        let mut s = three_member_spec();
17391        let big = format!(
17392            "{}.{}.{}.{}",
17393            "a".repeat(63),
17394            "b".repeat(63),
17395            "c".repeat(63),
17396            "d".repeat(254 - 63 * 3 - 3)
17397        );
17398        assert_eq!(big.len(), 254);
17399        s.entrada.as_mut().unwrap().host = big;
17400        let err = s.validate().unwrap_err();
17401        assert!(
17402            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17403                if reason.contains("max length of 253")),
17404            "got {err:?}"
17405        );
17406    }
17407
17408    #[test]
17409    fn rejects_entrada_host_label_too_long() {
17410        let mut s = three_member_spec();
17411        // 64-byte label — one over the per-label cap.
17412        s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
17413        let err = s.validate().unwrap_err();
17414        assert!(
17415            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17416                if reason.contains("label max length of 63")),
17417            "got {err:?}"
17418        );
17419    }
17420
17421    #[test]
17422    fn entrada_host_diagnostic_carries_offending_host() {
17423        // Diagnostic-shape pin — the offending host + a non-empty
17424        // reason flow through verbatim so the author can grep their
17425        // caixa.lisp for `:host "<host>"` and fix it in one edit.
17426        let mut s = three_member_spec();
17427        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
17428        let err = s.validate().unwrap_err();
17429        match err {
17430            AplicacaoError::EntradaHostInvalid { host, reason } => {
17431                assert_eq!(host, "checkout.quero.cloud:8080");
17432                assert!(!reason.is_empty(), "reason field must be non-empty");
17433            }
17434            other => panic!("expected EntradaHostInvalid, got {other:?}"),
17435        }
17436    }
17437
17438    // Equivalence pin for the [`AplicacaoError::entrada_host_invalid`]
17439    // substrate primitive that folds the fourteen
17440    // `AplicacaoError::EntradaHostInvalid { host: host.to_string(),
17441    // reason: <expr> }` wire-up sites at [`validate_entrada_host`] onto
17442    // one dispatch — peer with the sixteen equivalence pins the
17443    // [`crate::LayoutError`] `_violation` constructor family carries in
17444    // `layout::tests::*_ctor_matches_struct_literal_wrap` (131ca0d). The
17445    // fixture host + reason are fixed `&'static str`s so both fields of
17446    // both constructed variants pin verbatim: the `host` axis is pinned
17447    // through the shared `host.to_string()` wrap (the ctor's uniform
17448    // one-slot construction) and the `reason` axis is pinned through
17449    // the shared `reason.into()` wrap (the ctor's `impl Into<String>`
17450    // routing). Any future regression on the lift (an extra field
17451    // introduced without updating the ctor, a diverging string
17452    // conversion at either arm) surfaces at this pin's diagnostic
17453    // rather than at a per-wire-up struct-literal reintroduction.
17454    #[test]
17455    fn entrada_host_invalid_ctor_matches_struct_literal_wrap() {
17456        let host = "checkout.quero.cloud:8080";
17457        let reason = "sample reason text";
17458        assert_eq!(
17459            AplicacaoError::entrada_host_invalid(host, reason),
17460            AplicacaoError::EntradaHostInvalid {
17461                host: host.to_string(),
17462                reason: reason.to_string(),
17463            },
17464            "generated constructor must produce byte-equal AplicacaoError to open-coded struct-literal wrap",
17465        );
17466    }
17467
17468    // Routing pin — the ctor's `host: &str` argument threads through
17469    // `.to_string()` verbatim on the `host` field, so the constructed
17470    // variant carries the offending host bytes without any wrapper-
17471    // side transformation (no `.to_ascii_lowercase()` normalization,
17472    // no `.trim()` strip, no truncation) — the same "diagnostic carries
17473    // the offending value verbatim so the author can grep their
17474    // caixa.lisp" discipline every peer typed-slot ctor at this
17475    // altitude carries.
17476    #[test]
17477    fn entrada_host_invalid_ctor_routes_host_through_to_string() {
17478        // Uppercase + trailing whitespace + port suffix — three
17479        // wrapper-side transformations the ctor must *not* apply.
17480        let host = " Checkout.quero.CLOUD:8080 ";
17481        let err = AplicacaoError::entrada_host_invalid(host, "sample");
17482        match err {
17483            AplicacaoError::EntradaHostInvalid { host: h, .. } => {
17484                assert_eq!(h, host, "host must thread through `.to_string()` verbatim");
17485            }
17486            other => panic!("expected EntradaHostInvalid, got {other:?}"),
17487        }
17488    }
17489
17490    // Routing pin — the ctor's `reason: impl Into<String>` accepts both
17491    // `&str` literals and `format!(…)` outputs identically and both
17492    // route through `Into::into` verbatim onto the `reason` field.
17493    // Pins both codepaths against the same host to prove the two
17494    // shapes the fourteen wire-up sites use at their per-arm diagnostic
17495    // (ten `&str` literals — some with `.to_string()` at the caller,
17496    // some without — plus four `format!(…)` outputs) each produce
17497    // byte-equal `reason` fields against the same offending host.
17498    #[test]
17499    fn entrada_host_invalid_ctor_routes_reason_through_into() {
17500        let host = "checkout.quero.cloud";
17501        // `&str` literal — the ctor's `impl Into<String>` accepts it
17502        // without a caller-side `.to_string()`.
17503        let from_literal = AplicacaoError::entrada_host_invalid(host, "literal reason text");
17504        // Owned `String` from `format!` — the peer `format!(…)`-shaped
17505        // wire-up arm.
17506        let from_format =
17507            AplicacaoError::entrada_host_invalid(host, format!("{} reason text", "literal"));
17508        // `String` from `.to_string()` on a literal — the peer
17509        // `"literal".to_string()`-shaped wire-up arm the pre-lift
17510        // sites carried.
17511        let from_to_string =
17512            AplicacaoError::entrada_host_invalid(host, "literal reason text".to_string());
17513        match (&from_literal, &from_format, &from_to_string) {
17514            (
17515                AplicacaoError::EntradaHostInvalid {
17516                    reason: r_lit,
17517                    host: h_lit,
17518                },
17519                AplicacaoError::EntradaHostInvalid {
17520                    reason: r_fmt,
17521                    host: h_fmt,
17522                },
17523                AplicacaoError::EntradaHostInvalid {
17524                    reason: r_ts,
17525                    host: h_ts,
17526                },
17527            ) => {
17528                assert_eq!(r_lit, "literal reason text");
17529                assert_eq!(r_fmt, "literal reason text");
17530                assert_eq!(r_ts, "literal reason text");
17531                assert_eq!(h_lit, host);
17532                assert_eq!(h_fmt, host);
17533                assert_eq!(h_ts, host);
17534            }
17535            _ => panic!("expected three EntradaHostInvalid variants"),
17536        }
17537        // Cross-arm equivalence — the three shapes must produce
17538        // byte-equal `AplicacaoError` values, so the fourteen wire-up
17539        // sites' mixed per-arm shapes fold onto one canonical form.
17540        assert_eq!(from_literal, from_format);
17541        assert_eq!(from_literal, from_to_string);
17542    }
17543
17544    // Equivalence pins for the six sibling
17545    // [`aplicacao_field_reason_ctors!`]-generated constructors that
17546    // fold the peer `{ <field>: String, reason: String }` variants
17547    // onto the same substrate-primitive family
17548    // `entrada_host_invalid` (17dd504) already carries pins for.
17549    // Each ctor's fixture pair (a fixed `&'static str` value and a
17550    // fixed `&'static str` reason) pins both fields verbatim so any
17551    // future regression on the macro (an extra field introduced
17552    // without updating the macro, a diverging string conversion at
17553    // either arm, a field-name typo on one variant that dropped it
17554    // off the shared shape) surfaces at the affected variant's pin
17555    // rather than at a per-wire-up struct-literal reintroduction. Peer
17556    // discipline of the sixteen `LayoutError` _violation ctor pins in
17557    // `layout::tests::*_ctor_matches_struct_literal_wrap` (131ca0d)
17558    // and the paired
17559    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
17560    // `contrato_missing_target_ctor_matches_struct_literal_wrap`
17561    // (14b81d5) / `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
17562    // (8580068) equivalence pins on the sibling `AplicacaoError`
17563    // ctor macros.
17564    #[test]
17565    fn membro_caixa_invalid_ctor_matches_struct_literal_wrap() {
17566        let caixa = "cart-svc";
17567        let reason = "sample reason text";
17568        assert_eq!(
17569            AplicacaoError::membro_caixa_invalid(caixa, reason),
17570            AplicacaoError::MembroCaixaInvalid {
17571                caixa: caixa.to_string(),
17572                reason: reason.to_string(),
17573            },
17574        );
17575    }
17576
17577    #[test]
17578    fn entrada_para_invalid_ctor_matches_struct_literal_wrap() {
17579        let para = "checkout";
17580        let reason = "sample reason text";
17581        assert_eq!(
17582            AplicacaoError::entrada_para_invalid(para, reason),
17583            AplicacaoError::EntradaParaInvalid {
17584                para: para.to_string(),
17585                reason: reason.to_string(),
17586            },
17587        );
17588    }
17589
17590    #[test]
17591    fn entrada_path_invalid_ctor_matches_struct_literal_wrap() {
17592        let path = "/api/cart";
17593        let reason = "sample reason text";
17594        assert_eq!(
17595            AplicacaoError::entrada_path_invalid(path, reason),
17596            AplicacaoError::EntradaPathInvalid {
17597                path: path.to_string(),
17598                reason: reason.to_string(),
17599            },
17600        );
17601    }
17602
17603    #[test]
17604    fn placement_cluster_invalid_ctor_matches_struct_literal_wrap() {
17605        let cluster = "rio";
17606        let reason = "sample reason text";
17607        assert_eq!(
17608            AplicacaoError::placement_cluster_invalid(cluster, reason),
17609            AplicacaoError::PlacementClusterInvalid {
17610                cluster: cluster.to_string(),
17611                reason: reason.to_string(),
17612            },
17613        );
17614    }
17615
17616    #[test]
17617    fn placement_affinity_invalid_ctor_matches_struct_literal_wrap() {
17618        let affinity = "data-locality";
17619        let reason = "sample reason text";
17620        assert_eq!(
17621            AplicacaoError::placement_affinity_invalid(affinity, reason),
17622            AplicacaoError::PlacementAffinityInvalid {
17623                affinity: affinity.to_string(),
17624                reason: reason.to_string(),
17625            },
17626        );
17627    }
17628
17629    #[test]
17630    fn shard_key_invalid_ctor_matches_struct_literal_wrap() {
17631        let shard_key = "tenantId";
17632        let reason = "sample reason text";
17633        assert_eq!(
17634            AplicacaoError::shard_key_invalid(shard_key, reason),
17635            AplicacaoError::ShardKeyInvalid {
17636                shard_key: shard_key.to_string(),
17637                reason: reason.to_string(),
17638            },
17639        );
17640    }
17641
17642    // Cross-family invariance pin — the six sibling ctors and
17643    // `entrada_host_invalid` all route `reason: impl Into<String>` +
17644    // `<field>: &str` verbatim onto their respective typed variants
17645    // through the shared [`aplicacao_field_reason_ctors!`] macro.
17646    // Sweeps a fixture pair (`&str` literal, `format!` output) against
17647    // every ctor to pin that no per-arm wrapper transformation drifted
17648    // in against the uniform macro-generated body.
17649    #[test]
17650    fn aplicacao_field_reason_ctors_route_reason_through_into_uniformly() {
17651        let via_literal = "literal reason text";
17652        let via_format = format!("{} reason text", "literal");
17653        assert_eq!(
17654            AplicacaoError::membro_caixa_invalid("m", via_literal),
17655            AplicacaoError::membro_caixa_invalid("m", via_format.clone()),
17656        );
17657        assert_eq!(
17658            AplicacaoError::entrada_para_invalid("p", via_literal),
17659            AplicacaoError::entrada_para_invalid("p", via_format.clone()),
17660        );
17661        assert_eq!(
17662            AplicacaoError::entrada_path_invalid("/a", via_literal),
17663            AplicacaoError::entrada_path_invalid("/a", via_format.clone()),
17664        );
17665        assert_eq!(
17666            AplicacaoError::placement_cluster_invalid("c", via_literal),
17667            AplicacaoError::placement_cluster_invalid("c", via_format.clone()),
17668        );
17669        assert_eq!(
17670            AplicacaoError::placement_affinity_invalid("a", via_literal),
17671            AplicacaoError::placement_affinity_invalid("a", via_format.clone()),
17672        );
17673        assert_eq!(
17674            AplicacaoError::shard_key_invalid("k", via_literal),
17675            AplicacaoError::shard_key_invalid("k", via_format.clone()),
17676        );
17677        assert_eq!(
17678            AplicacaoError::entrada_host_invalid("h", via_literal),
17679            AplicacaoError::entrada_host_invalid("h", via_format),
17680        );
17681    }
17682
17683    #[test]
17684    fn entrada_host_empty_takes_precedence_over_invalid() {
17685        // Ordering pin: `EmptyEntradaHost` is the more self-locating
17686        // diagnostic on `""` and must lead — `validate_entrada_host`
17687        // is only reached after the empty-check fires at the call
17688        // site. (The predicate itself defends against direct
17689        // invocation by returning the same error on `""`.)
17690        let mut s = three_member_spec();
17691        s.entrada.as_mut().unwrap().host = String::new();
17692        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
17693    }
17694
17695    #[test]
17696    fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
17697        // Ordering pin: a missing :para member is the more
17698        // self-locating diagnostic and fires before the host gate.
17699        let mut s = three_member_spec();
17700        let e = s.entrada.as_mut().unwrap();
17701        e.para = "ghost".into();
17702        e.host = "BAD HOST".into();
17703        let err = s.validate().unwrap_err();
17704        assert!(
17705            matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
17706            "got {err:?}"
17707        );
17708    }
17709
17710    #[test]
17711    fn entrada_host_invalid_fires_before_port_zero() {
17712        // Ordering pin: the host gate fires before the port gate so
17713        // a malformed host is named even when the port is also wrong.
17714        let mut s = three_member_spec();
17715        let e = s.entrada.as_mut().unwrap();
17716        e.host = "Checkout.quero.cloud".into();
17717        e.port = 0;
17718        let err = s.validate().unwrap_err();
17719        assert!(
17720            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
17721                if host == "Checkout.quero.cloud"),
17722            "got {err:?}"
17723        );
17724    }
17725
17726    #[test]
17727    fn entrada_accepts_canonical_hosts() {
17728        // Positive-control sweep — every form the Gateway API
17729        // apiserver accepts must round-trip through validate. Covers
17730        // a plain DNS subdomain, a leading wildcard, a single-label
17731        // host (cluster-internal), a max-length-edge label, a
17732        // hyphen-bearing label, and a Punycode IDN label.
17733        for host in [
17734            "checkout.quero.cloud",
17735            "*.quero.cloud",
17736            "checkout",
17737            // 63-byte label — exactly the per-label cap.
17738            "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
17739            "foo-bar.quero.cloud",
17740            // Punycode IDN — valid because the author pre-encoded.
17741            "xn--bcher-kva.example.com",
17742        ] {
17743            let mut s = three_member_spec();
17744            s.entrada.as_mut().unwrap().host = host.into();
17745            s.validate()
17746                .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
17747        }
17748    }
17749
17750    #[test]
17751    fn entrada_host_max_length_validates() {
17752        // 253-byte host is the cap exactly — must validate. Build a
17753        // 253-byte host out of three 63-byte labels + one 61-byte
17754        // label + 3 dots = 252 bytes, then pad one byte to 253.
17755        let mut s = three_member_spec();
17756        let host = format!(
17757            "{}.{}.{}.{}",
17758            "a".repeat(63),
17759            "b".repeat(63),
17760            "c".repeat(63),
17761            "d".repeat(253 - 63 * 3 - 3)
17762        );
17763        assert_eq!(host.len(), 253);
17764        s.entrada.as_mut().unwrap().host = host;
17765        s.validate().unwrap();
17766    }
17767
17768    #[test]
17769    fn entrada_host_total_length_cap_threads_lifted_render_const() {
17770        // Cross-crate-side pin: the aplicacao-side `:entrada :host`
17771        // total-length gate now reads the K8s Gateway API v1 Hostname
17772        // `maxLength: 253` cap from the lifted
17773        // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
17774        // of truth — the same constant every future Gateway-API-Hostname
17775        // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
17776        // materializer's per-host validator, the future per-`Certificate`
17777        // SAN emitter for cert-manager, the multi-`:entrada`
17778        // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
17779        // from. Before the lift, the aplicacao-side reader consumed a
17780        // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
17781        // 253-byte value as the peer render-side canonical bounds
17782        // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
17783        // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
17784        // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
17785        // module boundary — a future 253-byte drift on either side would
17786        // silently split into two axes' worth of admission-schema mismatch
17787        // without a build-time signal. Pin the cap through a fresh 254-
17788        // byte host that hits the total-length arm, then read the reason
17789        // for the exact byte count the shared constant carries: any future
17790        // regression on the lift (a private alias reintroduced, a hard-
17791        // coded literal at the arm, a mismatch between the aplicacao-side
17792        // and render-side canonicals) surfaces as this pin's diagnostic
17793        // failing to match, not as a per-cluster admission rejection far
17794        // from the caixa.lisp source line.
17795        let mut s = three_member_spec();
17796        let over_cap = format!(
17797            "{}.{}.{}.{}",
17798            "a".repeat(63),
17799            "b".repeat(63),
17800            "c".repeat(63),
17801            "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
17802        );
17803        assert_eq!(
17804            over_cap.len(),
17805            crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
17806        );
17807        s.entrada.as_mut().unwrap().host = over_cap;
17808        let err = s.validate().unwrap_err();
17809        match err {
17810            AplicacaoError::EntradaHostInvalid { reason, .. } => {
17811                let needle = format!(
17812                    "max length of {} bytes",
17813                    crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
17814                );
17815                assert!(
17816                    reason.contains(&needle),
17817                    "diagnostic must name the lifted \
17818                     GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
17819                );
17820            }
17821            other => panic!("expected EntradaHostInvalid, got {other:?}"),
17822        }
17823    }
17824
17825    #[test]
17826    fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
17827        // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
17828        // on the per-label-cap axis. Before the lift, the aplicacao-side
17829        // per-label arm consumed a private const alias
17830        // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
17831        // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
17832        // split from it at the module boundary — every `.`-separated
17833        // label in a Gateway API v1 Hostname is a DNS-1123 label under
17834        // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
17835        // so the private alias's 63 and the canonical const's 63 were
17836        // pinning the same underlying rule twice. Pin the cap through a
17837        // 64-byte label that hits the per-label arm, then read the reason
17838        // for the exact byte count the shared constant carries: any
17839        // future drift on either side (a private alias reintroduced, a
17840        // hard-coded literal at the arm, a mismatch between the two
17841        // 63-byte pins) surfaces at this pin's diagnostic rather than at
17842        // a per-cluster admission rejection whose "field is invalid"
17843        // opacity misframes the root cause.
17844        let mut s = three_member_spec();
17845        let over_cap_label = format!(
17846            "{}.quero.cloud",
17847            "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
17848        );
17849        s.entrada.as_mut().unwrap().host = over_cap_label;
17850        let err = s.validate().unwrap_err();
17851        match err {
17852            AplicacaoError::EntradaHostInvalid { reason, .. } => {
17853                let needle = format!(
17854                    "label max length of {} bytes",
17855                    crate::render::DNS_1123_LABEL_MAX_LEN,
17856                );
17857                assert!(
17858                    reason.contains(&needle),
17859                    "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
17860                     cap verbatim on the per-label arm, got: {reason:?}",
17861                );
17862            }
17863            other => panic!("expected EntradaHostInvalid, got {other:?}"),
17864        }
17865    }
17866
17867    #[test]
17868    fn entrada_with_empty_paths_validates() {
17869        // Empty `:paths` is the documented "match every path" form;
17870        // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
17871        let mut s = three_member_spec();
17872        s.entrada.as_mut().unwrap().paths = vec![];
17873        s.validate().unwrap();
17874    }
17875
17876    #[test]
17877    fn entrada_root_path_validates() {
17878        // The author-supplied bare-root `:entrada :paths` entry is the
17879        // same byte-shape the peer emit-side catch-all constant
17880        // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
17881        // the author's `:paths` list is empty — sweeping the test-side
17882        // probe literal onto the lifted const closes the two-axis pin
17883        // (author-side admit + emit-side canonical fallback) around
17884        // one `&'static str`, so a future rebrand of the catch-all
17885        // reaches both consumers by construction. Peer to
17886        // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
17887        // on the canonical-literal pin surface.
17888        let mut s = three_member_spec();
17889        s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
17890        s.validate().unwrap();
17891    }
17892
17893    #[test]
17894    fn placement_strategy_variants_round_trip() {
17895        for s in [
17896            PlacementStrategy::SingleNode,
17897            PlacementStrategy::Replicated,
17898            PlacementStrategy::Sharded,
17899        ] {
17900            let p = Placement {
17901                estrategia: s,
17902                clusters: vec!["rio".into()],
17903                affinity: None,
17904                // Route the paired `:shard-key` fixture-builder through the
17905                // typed cross-slot invariant predicate
17906                // [`PlacementStrategy::requires_shard_key`] rather than the
17907                // [`gen_platform::IsVariant`]-derived [`Self::is_sharded`]
17908                // arm-identity predicate — the two answer the same
17909                // question under today's closed accept-set but a future
17910                // arm addition that consumed `:shard-key` under a
17911                // non-`Sharded` name would silently mis-attach the
17912                // fixture's `:shard-key` if the builder read through the
17913                // arm-identity predicate. The cross-slot-invariant
17914                // predicate migrates through one caixa-core edit on any
17915                // future arm addition; the fixture keeps producing a
17916                // `validate()`-passing round-trip by construction.
17917                shard_key: if s.requires_shard_key() {
17918                    Some("$key".into())
17919                } else {
17920                    None
17921                },
17922            };
17923            let json = serde_json::to_string(&p).unwrap();
17924            let back: Placement = serde_json::from_str(&json).unwrap();
17925            assert_eq!(back, p);
17926        }
17927    }
17928
17929    #[test]
17930    fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
17931        // The fail-before-pass-after pin: pre-lift there was no
17932        // single-source binding between the [`PlacementStrategy`]
17933        // variant name the `Serialize` derive emits and the byte-
17934        // string every downstream cluster-side dispatcher (the
17935        // `lareira-fleet-programs` aggregator's per-entry strategy
17936        // branch, the future `app-operator` reconciler, the M3
17937        // Adaptive compression pass's per-strategy weighting) probes
17938        // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
17939        // future `#[serde(rename_all = "kebab-case")]` attribute on
17940        // the enum — or a variant rename in the source — would
17941        // silently rebrand the emitted scalar under one spelling
17942        // while every downstream dispatcher still probed the other,
17943        // with the failure surfacing at the aggregator's dispatch
17944        // step or the operator's reconcile posture (workloads coming
17945        // up under the `default()` `Replicated` arm rather than the
17946        // typed slot's declared strategy) far from the source
17947        // rebrand commit and with no field naming the drift. Pinning
17948        // the two paths (the `Serialize` derive's serialized string
17949        // AND the [`PlacementStrategy::as_str`] helper) to the same
17950        // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
17951        // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
17952        // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
17953        // makes any future drift on either endpoint fail here at
17954        // caixa-core build time.
17955        for (variant, expected) in [
17956            (
17957                PlacementStrategy::SingleNode,
17958                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
17959            ),
17960            (
17961                PlacementStrategy::Replicated,
17962                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
17963            ),
17964            (
17965                PlacementStrategy::Sharded,
17966                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
17967            ),
17968        ] {
17969            let json = serde_json::to_string(&variant).unwrap();
17970            assert_eq!(
17971                json,
17972                format!("\"{expected}\""),
17973                "PlacementStrategy::{variant:?} must serialize to {expected:?}"
17974            );
17975            assert_eq!(
17976                variant.as_str(),
17977                expected,
17978                "PlacementStrategy::{variant:?}.as_str() must return the lifted \
17979                 M3_PLACEMENT_ESTRATEGIA_* constant"
17980            );
17981        }
17982    }
17983
17984    #[test]
17985    fn m3_placement_estrategia_consts_are_pairwise_distinct() {
17986        // Cross-arm drift-detection pin on the M3
17987        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
17988        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
17989        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
17990        // scalar-value pentad: a future collapse of two canonical
17991        // variant byte-strings onto the same value (an accidental
17992        // copy-paste flip of
17993        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
17994        // read `"SingleNode"`, a per-arm rebrand that lands one const
17995        // without touching its paired peer) would silently reroute
17996        // every downstream operator's per-strategy dispatch onto the
17997        // sibling arm's reconcile branch and pass every
17998        // propagation-probe test that expected only the stale arm's
17999        // value — a `Replicated`-declared Aplicacao would come up
18000        // under the `SingleNode` primary-and-standby reconcile
18001        // posture, so every-cluster active-active workload would
18002        // silently collapse onto one-cluster-runs-at-a-time takeover
18003        // semantics against its declared strategy, with no field
18004        // naming the strategy-value drift root cause. Peer of the
18005        // sibling
18006        // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
18007        // (09ffb2d) /
18008        // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
18009        // (ccdf955) /
18010        // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
18011        // (d739850) distinctness pins on the sibling OTP-shape /
18012        // caixa-kind closed-set typed-enum discriminator axes — the
18013        // fourth (and structurally the M3 mesh-primitive-defining)
18014        // closed-set typed-enum axis to converge on the same
18015        // "pairwise-distinct-by-construction" discipline.
18016        //
18017        // Fail-before-pass-after locally verified by mutating
18018        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
18019        // also read `"SingleNode"` — this pin fires as expected;
18020        // restoring passes.
18021        let all = [
18022            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
18023            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
18024            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
18025        ];
18026        for (i, a) in all.iter().enumerate() {
18027            for (j, b) in all.iter().enumerate() {
18028                if i != j {
18029                    assert_ne!(
18030                        a, b,
18031                        "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
18032                         distinct — got duplicate {a:?} at indices {i} and {j}",
18033                    );
18034                }
18035            }
18036        }
18037    }
18038
18039    #[test]
18040    fn placement_strategy_display_routes_through_as_str_helper() {
18041        // The fail-before-pass-after pin: pre-lift the sibling
18042        // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
18043        // / [`crate::supervisor::RestartPolicy`] both carried a stable
18044        // [`std::fmt::Display`] surface via their
18045        // `#[discriminant(also_display)]` gen-platform derive, but
18046        // [`PlacementStrategy`] did not — every consumer reaching for
18047        // a strategy byte-string past the wire format had to pick
18048        // between three paths ([`PlacementStrategy::as_str`], the
18049        // `Serialize` derive's serialized string, or `format!("{v:?}")`
18050        // on the `Debug` derive), any two of which a future variant
18051        // rename or `#[serde(rename_all = "kebab-case")]` attribute
18052        // would silently desynchronize. Wiring [`std::fmt::Display`]
18053        // through [`PlacementStrategy::as_str`] closes the third path:
18054        // every `format!("{v}")` call reaches the same lifted
18055        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
18056        // and the [`PlacementStrategy::as_str`] helper already route
18057        // through, so a future variant rename lands at exactly one
18058        // place. Pin the routing here so a future
18059        // `impl std::fmt::Display for PlacementStrategy` reimplementation
18060        // that hand-rolls the arms instead of delegating to
18061        // [`PlacementStrategy::as_str`] fails at caixa-core build time.
18062        for variant in [
18063            PlacementStrategy::SingleNode,
18064            PlacementStrategy::Replicated,
18065            PlacementStrategy::Sharded,
18066        ] {
18067            assert_eq!(
18068                variant.to_string(),
18069                variant.as_str(),
18070                "PlacementStrategy::{variant:?} Display must route through \
18071                 PlacementStrategy::as_str (single source of truth: the lifted \
18072                 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
18073            );
18074        }
18075    }
18076
18077    #[test]
18078    fn placement_strategy_display_matches_serialized_wire_byte_string() {
18079        // The fail-before-pass-after pin on the second half of the
18080        // three-path convergence: `Display` (user-facing text) agrees
18081        // byte-for-byte with the `Serialize` derive's wire format
18082        // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
18083        // scalar) on every variant. Pre-lift the two paths were
18084        // structurally independent — a future
18085        // `#[serde(rename_all = "kebab-case")]` attribute on the enum
18086        // would silently rebrand the emitted wire scalar
18087        // (`single-node`, `replicated`, `sharded`) while every consumer
18088        // that pretty-prints the strategy (the M3 diagnostic templates,
18089        // the future `feira app graph` per-Aplicacao strategy line,
18090        // the future M4 CR materializer's admission-webhook rejection
18091        // body) would still emit the TitleCase form the `as_str` /
18092        // `Display` route returns, with the mismatch surfacing at
18093        // consumer parse time / operator dispatch time far from the
18094        // source rebrand commit. Pin the two paths byte-for-byte here
18095        // so any future serde-attribute or variant-rename drift is a
18096        // caixa-core-build-time test failure at this call, not a
18097        // silent per-consumer dispatch miss.
18098        for variant in [
18099            PlacementStrategy::SingleNode,
18100            PlacementStrategy::Replicated,
18101            PlacementStrategy::Sharded,
18102        ] {
18103            let wire = serde_json::to_string(&variant).unwrap();
18104            // Strip the outer `"…"` the JSON string form carries — the
18105            // wire scalar the K8s / YAML apiserver consumes is the
18106            // enclosed byte-string, not the quote wrapper.
18107            let unquoted = wire
18108                .strip_prefix('"')
18109                .and_then(|s| s.strip_suffix('"'))
18110                .expect("serialized PlacementStrategy is a JSON string");
18111            assert_eq!(
18112                variant.to_string(),
18113                unquoted,
18114                "PlacementStrategy::{variant:?} Display byte-string must match the \
18115                 Serialize derive's wire byte-string (three-path convergence: \
18116                 Display + as_str + Serialize all resolve to the same \
18117                 M3_PLACEMENT_ESTRATEGIA_* const)"
18118            );
18119        }
18120    }
18121
18122    #[test]
18123    fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
18124        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
18125        // derive on [`PlacementStrategy`]: for each of the three variants
18126        // exactly one of the generated `is_single_node` / `is_replicated`
18127        // / `is_sharded` predicates returns `true` and the other two
18128        // return `false`. Prior to this derive the three per-arm
18129        // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
18130        // (the `placement_strategy_variants_round_trip` fixture, the
18131        // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
18132        // fixture, and the
18133        // `validate_placement_reads_through_lifted_estrategia_accessor`
18134        // fixture) each open-coded a per-arm PartialEq compare against
18135        // the enum variant — three sites that expressed no compile-time
18136        // link back to the closed-set typed dispatch a future fourth
18137        // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
18138        // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
18139        // would have to thread through in lockstep or one fixture would
18140        // silently disagree with the others on which arms consume the
18141        // `:shard-key` axis. Peer of the sibling
18142        // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
18143        // / [`crate::supervisor::RestartPolicy`] /
18144        // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
18145        // the sibling closed-set typed-enum discriminator axes — extends
18146        // the same one-typed-dispatch-per-variant discipline onto the
18147        // fifth (and only remaining) closed-set typed-enum discriminator
18148        // on the caixa surface, closing the axis on the M3 mesh-slot
18149        // family.
18150        let rows: [(PlacementStrategy, [bool; 3]); 3] = [
18151            (PlacementStrategy::SingleNode, [true, false, false]),
18152            (PlacementStrategy::Replicated, [false, true, false]),
18153            (PlacementStrategy::Sharded, [false, false, true]),
18154        ];
18155        for (variant, expected) in rows {
18156            let observed = [
18157                variant.is_single_node(),
18158                variant.is_replicated(),
18159                variant.is_sharded(),
18160            ];
18161            assert_eq!(
18162                observed, expected,
18163                "PlacementStrategy::{variant:?} is_* predicates must partition \
18164                 the arm set (single_node, replicated, sharded); got {observed:?}"
18165            );
18166        }
18167    }
18168
18169    #[test]
18170    fn placement_strategy_is_variant_predicates_are_const_fn() {
18171        // The [`gen_platform::IsVariant`] derive emits `const fn`
18172        // predicates on the peer [`crate::CaixaKind`] +
18173        // [`crate::upgrade::UpgradeInstruction`] +
18174        // [`crate::supervisor::RestartStrategy`] +
18175        // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
18176        // pin the same posture on [`PlacementStrategy`] so a future
18177        // accidental downgrade to non-`const` (an added runtime helper
18178        // reachable only from a non-`const` context, a manual hand-rolled
18179        // `impl` that shadows the derive-generated method) trips at
18180        // caixa-core build time rather than surfacing as a downstream
18181        // `const`-context regression far from the derive declaration.
18182        //
18183        // The pin lives inside a `const { assert!(..) }` block so the
18184        // compiler enforces both halves (arm predicate is `const`-
18185        // callable AND returns `true` for the matching arm) at
18186        // caixa-core compile time — peer to the sibling
18187        // [`crate::CaixaKind::is_*`] + [`WitTarget::is_*`] const-block
18188        // pins on the closed-set typed enum arm-predicate const-
18189        // callability axis.
18190        const {
18191            assert!(PlacementStrategy::SingleNode.is_single_node());
18192            assert!(PlacementStrategy::Replicated.is_replicated());
18193            assert!(PlacementStrategy::Sharded.is_sharded());
18194        }
18195    }
18196
18197    #[test]
18198    fn placement_strategy_requires_shard_key_partitions_the_arm_set() {
18199        // Fail-before-pass-after pin on the substrate-lifted
18200        // [`PlacementStrategy::requires_shard_key`] cross-slot-invariant
18201        // per-arm predicate: for each variant in the closed accept-set the
18202        // predicate returns `true` iff the variant consumes the paired
18203        // [`Placement::shard_key`] axis under
18204        // [`AplicacaoSpec::validate_placement`]'s `Sharded` ↔ non-`Sharded`
18205        // partition. Today the accept-set is the singleton `{Sharded}` —
18206        // `Sharded` is the Akka-style hash-keyed distribution arm
18207        // (MESH-COMPOSITION §II.4), `SingleNode` (Erlang/OTP takeover —
18208        // §II.1) and `Replicated` (active-active) refuse the axis through
18209        // [`AplicacaoError::ShardKeyOnNonSharded`].
18210        //
18211        // Pins the per-arm truth-table so a future arm addition (an
18212        // `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint the
18213        // roadmap names, a `WeightedShard` promotion the future M5
18214        // adaptive-placement engine acknowledges) that landed a variant
18215        // without extending this predicate's arm-set would surface as a
18216        // caixa-core build-time exhaustiveness error at the
18217        // `match self { … }` arm-fan below rather than a silent per-consumer
18218        // mis-classification at renderer emit time. The paired
18219        // [`Self::is_sharded`] `gen_platform::IsVariant`-derived arm-identity
18220        // predicate stays a distinct question — arm-identity (which the
18221        // sibling
18222        // [`placement_strategy_is_variant_predicates_partition_the_arm_set`]
18223        // pin already locks) is not cross-slot-invariant consumption; today
18224        // they trip on the same singleton but the pair migrates through
18225        // one caixa-core edit on any future arm addition.
18226        //
18227        // Peer of the sibling per-arm classifier pins
18228        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
18229        // (7b97d26) on the [`WitContract`] pre-projection WIT-shape axis
18230        // and the [`WitTarget::is_capability`] `gen_platform::IsVariant`-
18231        // derived paired predicate on the post-projection typed-view axis
18232        // — same "per-arm semantic-classification predicate paired with
18233        // the arm-identity predicate the derive already emits" discipline
18234        // extended onto the M3 mesh-slot `:placement :estrategia` ↔
18235        // `:placement :shard-key` cross-slot-invariant axis.
18236        let rows: [(PlacementStrategy, bool); 3] = [
18237            (PlacementStrategy::SingleNode, false),
18238            (PlacementStrategy::Replicated, false),
18239            (PlacementStrategy::Sharded, true),
18240        ];
18241        for (variant, expected) in rows {
18242            assert_eq!(
18243                variant.requires_shard_key(),
18244                expected,
18245                "PlacementStrategy::{variant:?}.requires_shard_key() must \
18246                 be {expected} (the substrate-canonical cross-slot invariant \
18247                 on the :placement :shard-key axis; today `Sharded` is the \
18248                 singleton consuming arm — MESH-COMPOSITION §II.4)",
18249            );
18250        }
18251    }
18252
18253    #[test]
18254    fn placement_strategy_requires_shard_key_is_const_fn() {
18255        // The [`PlacementStrategy::requires_shard_key`] cross-slot-
18256        // invariant per-arm predicate is declared `#[must_use] pub const
18257        // fn` — pin the `const`-eval posture here so a future accidental
18258        // downgrade to non-`const` (an added runtime helper reachable
18259        // only from a non-`const` context, a manual hand-rolled `impl`
18260        // that shadows the current three-arm `match self { … }` dispatch)
18261        // trips at caixa-core build time rather than surfacing as a
18262        // downstream `const`-context regression far from the declaration.
18263        // Same shape as the sibling
18264        // [`placement_strategy_is_variant_predicates_are_const_fn`] pin on
18265        // the peer [`gen_platform::IsVariant`]-derived arm-identity
18266        // predicate axis, but here the load-bearing assertions live in
18267        // module-scope `const _: () = assert!(…)` items so a violation
18268        // fails at compile time (const-eval trip) rather than test time —
18269        // strictly stronger than the runtime `assert!(CONST)` pattern the
18270        // sibling pin uses, and side-steps the
18271        // `clippy::assertions_on_constants` lint the runtime pattern
18272        // otherwise accumulates on the module baseline.
18273        //
18274        // The test body simply witnesses that the module-scope items
18275        // compiled and the runtime dispatch agrees with the const-eval
18276        // dispatch on every arm — the runtime read gives the test a
18277        // failure surface (rather than an empty test body clippy would
18278        // flag as a no-op).
18279        const REQUIRES_SINGLE_NODE: bool = PlacementStrategy::SingleNode.requires_shard_key();
18280        const REQUIRES_REPLICATED: bool = PlacementStrategy::Replicated.requires_shard_key();
18281        const REQUIRES_SHARDED: bool = PlacementStrategy::Sharded.requires_shard_key();
18282        assert_eq!(
18283            [REQUIRES_SINGLE_NODE, REQUIRES_REPLICATED, REQUIRES_SHARDED,],
18284            [
18285                PlacementStrategy::SingleNode.requires_shard_key(),
18286                PlacementStrategy::Replicated.requires_shard_key(),
18287                PlacementStrategy::Sharded.requires_shard_key(),
18288            ],
18289            "runtime and const-eval dispatch on \
18290             PlacementStrategy::requires_shard_key must agree on every arm",
18291        );
18292    }
18293
18294    #[test]
18295    fn placement_estrategia_accessor_is_const_fn() {
18296        // The [`Placement::estrategia`] per-`:placement` distribution-
18297        // strategy `Copy`-return scalar accessor is declared
18298        // `#[must_use] pub const fn` — matching the peer M3 mesh-slot
18299        // `Copy`-return accessor family ([`MeshPolicy::timeout`] /
18300        // [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
18301        // [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`]
18302        // on the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`]
18303        // / [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
18304        // [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
18305        // [`RateLimit`], every one a `pub const fn`). Pin the
18306        // `const`-eval posture here so a future accidental downgrade to
18307        // non-`const` (an added runtime helper reachable only from a
18308        // non-`const` context, a slot promotion to a non-`Copy` return
18309        // that would silently drop the `const` qualifier, a manual
18310        // hand-rolled shadow) trips at caixa-core build time rather
18311        // than surfacing as a downstream `const`-context regression far
18312        // from the declaration.
18313        //
18314        // Same shape as the sibling
18315        // [`placement_strategy_requires_shard_key_is_const_fn`] pin on
18316        // the peer [`PlacementStrategy::requires_shard_key`] `const fn`
18317        // predicate axis — the load-bearing witness lives in the
18318        // module-scope `const fn` wrapper `estrategia_via_const_fn`
18319        // below: a body that calls [`Placement::estrategia`] under a
18320        // `const fn` signature is well-formed only when the callee is
18321        // itself `const fn`, so any future accidental downgrade of
18322        // [`Placement::estrategia`] to non-`const` fails at caixa-core
18323        // build time (const-eval E0015 / E0658 depending on the arm),
18324        // strictly stronger than a runtime `assert!(CONST)` and
18325        // side-stepping the destructor-in-const restriction that
18326        // blocks direct `const _: PlacementStrategy = FIXTURE.estrategia()`
18327        // items on `Placement`'s `Vec<String>` / `Option<String>`
18328        // carriers.
18329        //
18330        // The runtime body witnesses that the const-eval-shaped
18331        // wrapper agrees with a direct call on every closed-set arm.
18332        const fn estrategia_via_const_fn(p: &Placement) -> PlacementStrategy {
18333            p.estrategia()
18334        }
18335        for estrategia in [
18336            PlacementStrategy::SingleNode,
18337            PlacementStrategy::Replicated,
18338            PlacementStrategy::Sharded,
18339        ] {
18340            let placement = Placement {
18341                estrategia,
18342                clusters: Vec::new(),
18343                affinity: None,
18344                shard_key: None,
18345            };
18346            assert_eq!(
18347                estrategia_via_const_fn(&placement),
18348                placement.estrategia(),
18349                "const-fn-wrapped and direct dispatch on \
18350                 Placement::estrategia must agree for {estrategia:?}",
18351            );
18352        }
18353    }
18354
18355    #[test]
18356    fn entrada_port_accessor_is_const_fn() {
18357        // The [`Entrada::port`] per-`:entrada` L4-port `Copy`-return
18358        // scalar accessor is declared `#[must_use] pub const fn` —
18359        // matching the peer M3 mesh-slot `Copy`-return accessor family
18360        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`] /
18361        // [`MeshPolicy::mtls_required`] / [`MeshPolicy::rate_limit`] /
18362        // [`MeshPolicy::circuit_breaker`] on the parent [`MeshPolicy`],
18363        // [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
18364        // on the sibling [`CircuitBreaker`], [`RateLimit::rate`] /
18365        // [`RateLimit::window`] on the sibling [`RateLimit`], the
18366        // sibling per-`:placement` [`Placement::estrategia`] pinned by
18367        // [`placement_estrategia_accessor_is_const_fn`] above — every
18368        // one a `pub const fn`). Pin the `const`-eval posture here so
18369        // a future accidental downgrade to non-`const` (an added
18370        // runtime helper reachable only from a non-`const` context, an
18371        // `Option<u16>`-shape migration once the substrate grows
18372        // per-`:membros` heterogeneous listener ports that would
18373        // silently drop the `const` qualifier, a manual hand-rolled
18374        // shadow) trips at caixa-core build time rather than surfacing
18375        // as a downstream `const`-context regression far from the
18376        // declaration.
18377        //
18378        // Same shape as the sibling
18379        // [`placement_estrategia_accessor_is_const_fn`] pin above — the
18380        // load-bearing witness lives in the module-scope `const fn`
18381        // wrapper `port_via_const_fn`: a body that calls
18382        // [`Entrada::port`] under a `const fn` signature is well-formed
18383        // only when the callee is itself `const fn`, side-stepping the
18384        // destructor-in-const restriction that would otherwise block a
18385        // direct `const _: u16 = FIXTURE.port()` item on `Entrada`'s
18386        // `String` / `Vec<String>` carriers.
18387        //
18388        // The runtime body sweeps a representative port set spanning
18389        // the [`SERVICO_PORT_MIN`] floor, the substrate-canonical
18390        // [`DEFAULT_SERVICO_PORT`] default, and the top-edge `u16::MAX`
18391        // ceiling — the const-fn-wrapped call must agree with a direct
18392        // call on every fixture (a violation trips the test) and every
18393        // returned scalar must byte-equal the input `port` (a violation
18394        // means the accessor stopped being a raw field-return copy).
18395        const fn port_via_const_fn(e: &Entrada) -> u16 {
18396            e.port()
18397        }
18398        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, u16::MAX] {
18399            let entrada = Entrada {
18400                host: String::new(),
18401                para: String::new(),
18402                port,
18403                paths: Vec::new(),
18404            };
18405            assert_eq!(
18406                port_via_const_fn(&entrada),
18407                entrada.port(),
18408                "const-fn-wrapped and direct dispatch on Entrada::port \
18409                 must agree for port={port}",
18410            );
18411            assert_eq!(
18412                entrada.port(),
18413                port,
18414                "Entrada::port must return the storage-side u16 verbatim \
18415                 for port={port}",
18416            );
18417        }
18418    }
18419
18420    #[test]
18421    fn validate_placement_admits_paired_shape_iff_strategy_requires_shard_key() {
18422        // Load-bearing cross-slot-partition pin closing the loop between
18423        // the substrate-lifted
18424        // [`PlacementStrategy::requires_shard_key`] per-arm predicate on
18425        // the closed-set typed enum and the actual
18426        // [`AplicacaoSpec::validate_placement`] runtime behavior across
18427        // the paired `:placement :shard-key` axis: every validated
18428        // [`Placement`] past [`AplicacaoSpec::validate_placement`]
18429        // satisfies `placement.shard_key().is_some() ==
18430        // placement.estrategia().requires_shard_key()`. The four-cell
18431        // shape witness sweeps every combination of (variant in the
18432        // closed accept-set, `:shard-key` Some/None) and pins:
18433        //
18434        //   * variant.requires_shard_key() && shard_key.is_some() →
18435        //     validate() passes; the paired shape is the sole
18436        //     `requires_shard_key` arm-family accepted shape.
18437        //   * variant.requires_shard_key() && shard_key.is_none() →
18438        //     validate() fails with [`AplicacaoError::ShardedWithoutKey`];
18439        //     the paired shape is the refused missing-key shape on
18440        //     Sharded-family arms.
18441        //   * !variant.requires_shard_key() && shard_key.is_some() →
18442        //     validate() fails with
18443        //     [`AplicacaoError::ShardKeyOnNonSharded`]; the paired shape
18444        //     is the refused declared-but-inert shape on non-Sharded-
18445        //     family arms.
18446        //   * !variant.requires_shard_key() && shard_key.is_none() →
18447        //     validate() passes; the paired shape is the sole
18448        //     non-`requires_shard_key` arm-family accepted shape.
18449        //
18450        // The compile-time-exhaustive `match p.estrategia()` dispatch at
18451        // [`AplicacaoSpec::validate_placement`] preserves its structural
18452        // arm-fan (a future arm addition still surfaces a build-time
18453        // exhaustiveness error there); this pin closes the semantic loop
18454        // between the arm-fan's shape-gate cascades and the substrate-
18455        // canonical predicate every downstream consumer of the paired
18456        // shape reads through. Fail-before-pass-after locally verified by
18457        // mutating the predicate's `Sharded => true` arm to `false` — the
18458        // truthy `expects_ok` cell for `Sharded` + `Some` trips the
18459        // `validate() must pass` assertion; restoring passes. Same "close
18460        // the loop between the typed predicate and the runtime behavior"
18461        // discipline as the sibling
18462        // [`wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant`]
18463        // (7b97d26) cross-projection pin on the peer [`WitTarget`]
18464        // per-arm classifier axis.
18465        for variant in [
18466            PlacementStrategy::SingleNode,
18467            PlacementStrategy::Replicated,
18468            PlacementStrategy::Sharded,
18469        ] {
18470            for present in [false, true] {
18471                let mut spec = three_member_spec();
18472                spec.placement.estrategia = variant;
18473                spec.placement.shard_key = present.then(|| "tenantId".into());
18474                let expects_ok = variant.requires_shard_key() == present;
18475                let result = spec.validate();
18476                match (expects_ok, &result) {
18477                    (true, Ok(())) => {}
18478                    (false, Err(err)) => {
18479                        // Cross-check the refusal diagnostic names the
18480                        // right cell of the four-cell shape witness — the
18481                        // `requires_shard_key && !present` cell must trip
18482                        // [`AplicacaoError::ShardedWithoutKey`]; the
18483                        // `!requires_shard_key && present` cell must trip
18484                        // [`AplicacaoError::ShardKeyOnNonSharded`].
18485                        match (variant.requires_shard_key(), present, err) {
18486                            (true, false, AplicacaoError::ShardedWithoutKey) => {}
18487                            (
18488                                false,
18489                                true,
18490                                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. },
18491                            ) => {
18492                                assert_eq!(
18493                                    *e, variant,
18494                                    "ShardKeyOnNonSharded.estrategia must byte-equal \
18495                                     the paired PlacementStrategy",
18496                                );
18497                            }
18498                            _ => panic!(
18499                                "unexpected refusal for estrategia={variant:?} \
18500                                 present={present}: {err:?}"
18501                            ),
18502                        }
18503                    }
18504                    (true, Err(err)) => panic!(
18505                        "validate() must pass for estrategia={variant:?} \
18506                         present={present} (requires_shard_key={} == present={present}), \
18507                         got {err:?}",
18508                        variant.requires_shard_key(),
18509                    ),
18510                    (false, Ok(())) => panic!(
18511                        "validate() must fail for estrategia={variant:?} \
18512                         present={present} (requires_shard_key={} != present={present})",
18513                        variant.requires_shard_key(),
18514                    ),
18515                }
18516            }
18517        }
18518    }
18519
18520    #[test]
18521    fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
18522        // Pin the M3 diagnostic template routes through the typed
18523        // [`PlacementStrategy`] Display byte-string (rebound from the
18524        // prior `{estrategia:?}` `Debug` route). Pre-lift the two
18525        // routes emitted identical bytes (the `Debug` derive on a
18526        // unit variant emits the variant name verbatim, exactly what
18527        // `as_str` returns), but the two paths were structurally
18528        // independent — a future `#[serde(rename_all = "…")]`
18529        // attribute or variant rename would coordinate the wire /
18530        // `Display` / `as_str` triple through the lifted const but
18531        // leave the `Debug` route on the compiler-derived variant name,
18532        // silently desynchronizing the diagnostic byte-string from the
18533        // wire byte-string. Rebinding the template onto `Display`
18534        // ties the diagnostic to the same lifted
18535        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
18536        // emits — drift becomes structurally impossible. Pin the
18537        // byte-string here so a future edit that reverts the template
18538        // to `{estrategia:?}` is caught at caixa-core test time, not
18539        // at consumer dispatch time.
18540        for (variant, expected_scalar) in [
18541            (
18542                PlacementStrategy::SingleNode,
18543                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
18544            ),
18545            (
18546                PlacementStrategy::Replicated,
18547                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
18548            ),
18549            (
18550                PlacementStrategy::Sharded,
18551                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
18552            ),
18553        ] {
18554            let err = AplicacaoError::PlacementWithoutClusters {
18555                estrategia: variant,
18556            };
18557            let msg = err.to_string();
18558            assert!(
18559                msg.starts_with(&format!(":placement {expected_scalar} requires")),
18560                "PlacementWithoutClusters diagnostic for {variant:?} must open \
18561                 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
18562            );
18563        }
18564    }
18565
18566    #[test]
18567    fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
18568        // Peer of
18569        // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
18570        // on the second M3 diagnostic that carries the typed
18571        // [`PlacementStrategy`] in its `#[error(…)]` template. Both
18572        // diagnostics now route the strategy scalar through the same
18573        // [`std::fmt::Display`] surface, tying the diagnostic
18574        // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
18575        // const set the wire format also emits. The two non-Sharded
18576        // arms are exercised here (the diagnostic exists to flag a
18577        // `:shard-key` slot the current strategy will never consume);
18578        // the peer `Sharded` arm never reaches this diagnostic (the
18579        // `Sharded` strategy consumes `:shard-key` — the
18580        // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
18581        // slot instead).
18582        for (variant, expected_scalar) in [
18583            (
18584                PlacementStrategy::SingleNode,
18585                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
18586            ),
18587            (
18588                PlacementStrategy::Replicated,
18589                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
18590            ),
18591        ] {
18592            let err = AplicacaoError::ShardKeyOnNonSharded {
18593                estrategia: variant,
18594                shard_key: "$tenantId".into(),
18595            };
18596            let msg = err.to_string();
18597            assert!(
18598                msg.starts_with(&format!(":placement {expected_scalar} carries")),
18599                "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
18600                 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
18601            );
18602        }
18603    }
18604
18605    #[test]
18606    fn placement_strategy_all_enumerates_every_variant_once() {
18607        // Fail-before-pass-after pin on the [`PlacementStrategy::ALL`]
18608        // exhaustive-iteration surface: every variant appears exactly
18609        // once, and the slice length matches the arm count of the
18610        // closed set. Every consumer that walks the accepted-strategy
18611        // set (a future `feira app placement --list` CLI-side surfacing,
18612        // a future M4 admission-webhook's rejection body naming the
18613        // accepted-strategy list, the [`PlacementStrategy::from_wire`]
18614        // reverse-projection consumers that iterate the accept-set for
18615        // a "did you mean" hint) reads through this slice, so a future
18616        // variant addition (an `Anycast` mesh-anycast arm the
18617        // MESH-COMPOSITION §II.5 hint names as a trajectory item) that
18618        // grows the enum but forgets to grow [`Self::ALL`] silently
18619        // truncates every downstream consumer's accept-set at the same
18620        // pre-addition boundary — this pin fails at caixa-core build
18621        // time on the pairwise-distinct + arm-count invariants.
18622        //
18623        // Peer of the sibling [`RateLimitUnit::ALL`] (6bce03d) /
18624        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
18625        // pins on the peer closed-set typed-enum axes.
18626        let all: &[PlacementStrategy] = PlacementStrategy::ALL;
18627        assert_eq!(
18628            all.len(),
18629            3,
18630            "PlacementStrategy::ALL must enumerate every variant of the \
18631             three-arm closed set (SingleNode, Replicated, Sharded); got {all:?}"
18632        );
18633        for (i, a) in all.iter().enumerate() {
18634            for (j, b) in all.iter().enumerate() {
18635                if i != j {
18636                    assert_ne!(
18637                        a, b,
18638                        "PlacementStrategy::ALL must carry every variant exactly \
18639                         once — got duplicate {a:?} at indices {i} and {j}"
18640                    );
18641                }
18642            }
18643        }
18644        for variant in [
18645            PlacementStrategy::SingleNode,
18646            PlacementStrategy::Replicated,
18647            PlacementStrategy::Sharded,
18648        ] {
18649            assert!(
18650                all.contains(&variant),
18651                "PlacementStrategy::ALL must contain {variant:?} — a future variant \
18652                 addition that grows the enum but forgets to grow the ALL slice \
18653                 silently truncates every downstream consumer's accept-set at the \
18654                 pre-addition boundary"
18655            );
18656        }
18657    }
18658
18659    #[test]
18660    fn placement_strategy_from_wire_accepts_every_lifted_constant() {
18661        // Fail-before-pass-after pin on the forward accept-set of the
18662        // [`PlacementStrategy::from_wire`] reverse projection: every
18663        // canonical [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
18664        // constant the [`PlacementStrategy::as_str`] emitter walks
18665        // parses back to its paired variant. Any future arm addition
18666        // that grows the emitter's `as_str` match but forgets to grow
18667        // the parser's `from_str` match silently splits the two halves
18668        // of the round-trip — the wire byte-string one non-serde
18669        // consumer parses from the one the emitter wrote — with the
18670        // failure surfacing at parse time far from the rebrand commit.
18671        // Pinning the three-arm accept-set here catches the drift at
18672        // caixa-core build time.
18673        //
18674        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
18675        // + [`RateLimitUnit::from_suffix`] accept-set pins on the peer
18676        // closed-set typed-enum `str → Self` axes.
18677        for (wire, expected) in [
18678            (
18679                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
18680                PlacementStrategy::SingleNode,
18681            ),
18682            (
18683                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
18684                PlacementStrategy::Replicated,
18685            ),
18686            (
18687                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
18688                PlacementStrategy::Sharded,
18689            ),
18690        ] {
18691            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
18692                panic!(
18693                    "PlacementStrategy::from_wire({wire:?}) must accept every \
18694                     M3_PLACEMENT_ESTRATEGIA_* constant — got None for the \
18695                     lifted canonical byte-string that PlacementStrategy::{expected:?} \
18696                     serializes as under M3_PLACEMENT_KEY_ESTRATEGIA"
18697                )
18698            });
18699            assert_eq!(
18700                parsed, expected,
18701                "PlacementStrategy::from_wire({wire:?}) must return \
18702                 PlacementStrategy::{expected:?}; got PlacementStrategy::{parsed:?}"
18703            );
18704        }
18705    }
18706
18707    #[test]
18708    fn placement_strategy_from_wire_round_trips_through_as_str() {
18709        // Fail-before-pass-after pin on the closed round-trip between
18710        // the forward [`PlacementStrategy::as_str`] emitter and the
18711        // reverse [`PlacementStrategy::from_wire`] parser: for every
18712        // variant in [`PlacementStrategy::ALL`], parsing the emitter's
18713        // output must return exactly the same variant. Any per-arm
18714        // divergence — a future arm added to `as_str` but not
18715        // `from_str`, an accidental copy-paste flip in one but not the
18716        // other — silently splits the emit and parse halves and the
18717        // failure surfaces at consumer parse time far from the drift
18718        // site. The `ALL`-iterating shape means a future variant
18719        // addition picks up the coverage by construction.
18720        //
18721        // Peer of the sibling [`crate::kind::tests`] round-trip pin on
18722        // [`crate::CaixaKind::from_wire`] and the
18723        // [`super::tests::rate_limit_unit_from_suffix_round_trips_through_as_suffix`]
18724        // sibling round-trip pin on [`RateLimitUnit`].
18725        for &variant in PlacementStrategy::ALL {
18726            let wire = variant.as_str();
18727            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
18728                panic!(
18729                    "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
18730                     must be Some({variant:?}) — the two halves of the round-trip \
18731                     dispatch on the same lifted M3_PLACEMENT_ESTRATEGIA_* consts; \
18732                     got None on wire byte-string {wire:?}"
18733                )
18734            });
18735            assert_eq!(
18736                parsed, variant,
18737                "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
18738                 must round-trip to the same variant; got {parsed:?}"
18739            );
18740        }
18741    }
18742
18743    #[test]
18744    fn placement_strategy_from_wire_rejects_unknown_byte_strings() {
18745        // Fail-before-pass-after pin on the closed-set refusal
18746        // discipline of [`PlacementStrategy::from_wire`]: every
18747        // byte-string outside the three-arm accept-set returns `None`
18748        // rather than silently collapsing onto the [`Default`]
18749        // (`Replicated`) arm or an arbitrary neighbor. The refusal set
18750        // exercised here sweeps the load-bearing drift shapes: the
18751        // empty string (a stripped serde-attribute drift), an all-
18752        // whitespace string (the canonical text-editor accidental
18753        // padding shape), the lowercased kebab-case forms a future
18754        // `#[serde(rename_all = "kebab-case")]` attribute would emit
18755        // (`"single-node"`, `"replicated"`, `"sharded"` — the last two
18756        // coincidentally match the accepted canonical scalars, so only
18757        // `"single-node"` fires as a refusal, but pinning the case-
18758        // sensitivity of the accepted arms via the peer [`SingleNode`]
18759        // assertion in the round-trip pin makes the discipline
18760        // structurally clear), the lowercased single-word forms
18761        // (`"singlenode"`), the padded canonical scalar
18762        // (`" Sharded "`), the trailing-comma / trailing-newline shapes
18763        // (`"Sharded\n"`), and a pointer-different `&'static str` that
18764        // happens to alias a canonical byte-string by content but not
18765        // by identity (validated implicitly by the emitter's routing
18766        // through `crate::render::M3_PLACEMENT_ESTRATEGIA_*`, whose
18767        // identity a paired [`crate::assert_str_reexport_identity`] pin
18768        // in caixa-core's per-const declaration surface would catch).
18769        //
18770        // Peer of the sibling
18771        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
18772        // (2aa6d23) refusal pin on [`crate::CaixaKind::from_wire`].
18773        for bad in [
18774            "",
18775            " ",
18776            "\n",
18777            "\t",
18778            "single-node",
18779            "singlenode",
18780            "SingleNodes",
18781            "single_node",
18782            "single node",
18783            "SINGLENODE",
18784            "SingleNode ",
18785            " SingleNode",
18786            " Sharded ",
18787            "Sharded\n",
18788            "replicated ",
18789            "sharded",
18790            "REPLICATED",
18791            "Anycast",
18792            "Global",
18793            "?",
18794        ] {
18795            assert!(
18796                PlacementStrategy::from_wire(bad).is_none(),
18797                "PlacementStrategy::from_wire({bad:?}) must return None — the \
18798                 parser's accept-set is exactly the three PlacementStrategy::as_str \
18799                 outputs (SingleNode, Replicated, Sharded), and this byte-string \
18800                 is outside that closed set"
18801            );
18802        }
18803    }
18804
18805    #[test]
18806    fn placement_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
18807        // Fail-before-pass-after pin on the third path of the four-path
18808        // convergence: `from_str` (the reverse projection) inverts the
18809        // `Serialize` derive's wire byte-string on every variant.
18810        // Together with the pre-existing three-path convergence
18811        // (`Display` + `as_str` + `Serialize` all resolve to the same
18812        // lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const, pinned by
18813        // the peer
18814        // [`placement_strategy_display_matches_serialized_wire_byte_string`])
18815        // this closes the round-trip: the wire byte-string the
18816        // `Serialize` derive emits parses back to the same variant
18817        // through `from_str`, so any future serde-attribute or variant-
18818        // rename drift on the emit half now surfaces as a matched drift
18819        // on the parse half at caixa-core build time — the two halves
18820        // migrate as a unit through the lifted consts on any future
18821        // rename, and the round-trip cannot silently split.
18822        //
18823        // Peer of the sibling
18824        // [`placement_strategy_display_matches_serialized_wire_byte_string`]
18825        // wire-format pin — extends the three-path convergence
18826        // (`Display` + `as_str` + `Serialize`) onto the fourth path
18827        // (`from_str`), closing the `str ↔ Self` round-trip on the
18828        // M3 `:placement :estrategia` closed-set axis.
18829        for &variant in PlacementStrategy::ALL {
18830            let wire = serde_json::to_string(&variant).unwrap();
18831            let unquoted = wire
18832                .strip_prefix('"')
18833                .and_then(|s| s.strip_suffix('"'))
18834                .expect("serialized PlacementStrategy is a JSON string");
18835            let parsed = PlacementStrategy::from_wire(unquoted).unwrap_or_else(|| {
18836                panic!(
18837                    "PlacementStrategy::from_wire({unquoted:?}) must accept the \
18838                     Serialize derive's wire byte-string for \
18839                     PlacementStrategy::{variant:?} — the four-path convergence \
18840                     (Display + as_str + Serialize + from_str) resolves through \
18841                     the same lifted M3_PLACEMENT_ESTRATEGIA_* const; got None"
18842                )
18843            });
18844            assert_eq!(
18845                parsed, variant,
18846                "PlacementStrategy::from_wire of the Serialize derive's wire \
18847                 byte-string for PlacementStrategy::{variant:?} must round-trip \
18848                 to the same variant; got {parsed:?}"
18849            );
18850        }
18851    }
18852
18853    #[test]
18854    fn rejects_zero_policy_timeout() {
18855        let mut s = three_member_spec();
18856        s.politicas.timeout = Some(Duration::ZERO);
18857        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
18858    }
18859
18860    #[test]
18861    fn rejects_zero_policy_retries() {
18862        let mut s = three_member_spec();
18863        s.politicas.retries = Some(0);
18864        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
18865    }
18866
18867    #[test]
18868    fn rejects_policy_retries_above_cap() {
18869        // The fail-before-pass-after pin: `Some(11)` is structurally
18870        // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
18871        // passed validate on every pre-gate codebase because the
18872        // typed slot's only check was the zero-floor arm. The
18873        // thundering-herd amplification vector only surfaced at the
18874        // runtime substrate (Envoy / Cilium L7 retry overlay)
18875        // far from the source caixa.lisp with no field naming the
18876        // offending policy.
18877        let mut s = three_member_spec();
18878        s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
18879        assert_eq!(
18880            s.validate().unwrap_err(),
18881            AplicacaoError::PolicyRetriesExceedsCap {
18882                retries: POLICY_RETRIES_MAX + 1
18883            }
18884        );
18885    }
18886
18887    #[test]
18888    fn rejects_policy_retries_far_above_cap() {
18889        // The `u32::MAX` worst case — the four-billion-retry policy
18890        // a typo (`(:retries 4294967295)`) or struct-literal
18891        // copy-paste lands in the slot. Pin the cap arm's coverage
18892        // explicitly across the full `u32` overflow so a future
18893        // relaxation that drops the upper bound surfaces here.
18894        let mut s = three_member_spec();
18895        s.politicas.retries = Some(u32::MAX);
18896        assert_eq!(
18897            s.validate().unwrap_err(),
18898            AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
18899        );
18900    }
18901
18902    #[test]
18903    fn accepts_policy_retries_at_cap() {
18904        // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
18905        // must validate. The cap is inclusive on the top edge,
18906        // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
18907        // discipline on the sibling [`crate::LimitsSpec::memory`]
18908        // axis. Pin the boundary explicitly so a future off-by-one
18909        // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
18910        // surfaces here as a test failure rather than a silent
18911        // contract narrowing.
18912        let mut s = three_member_spec();
18913        s.politicas.retries = Some(POLICY_RETRIES_MAX);
18914        s.validate()
18915            .expect("retries == POLICY_RETRIES_MAX must validate");
18916    }
18917
18918    #[test]
18919    fn accepts_policy_retries_typical_values() {
18920        // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
18921        // every value in the validated set must pass. The
18922        // Envoy / Istio production-playbook recommendation band
18923        // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
18924        // (`maxRetries ≤ 10`) both lie within this set.
18925        for r in 1..=POLICY_RETRIES_MAX {
18926            let mut s = three_member_spec();
18927            s.politicas.retries = Some(r);
18928            s.validate()
18929                .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
18930        }
18931    }
18932
18933    #[test]
18934    fn policy_retries_zero_takes_precedence_over_cap() {
18935        // The cross-arm ordering pin: `Some(0)` is structurally
18936        // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
18937        // (cap), but the zero-floor diagnostic is the more
18938        // self-locating one (it directly names the omit-axis
18939        // remediation), so the validate gate must fire on zero
18940        // first. Pin the order so a future refactor that reorders
18941        // the arms surfaces here as a test failure rather than a
18942        // silent diagnostic regression. Same shape every other
18943        // zero-then-shape ordering on this surface uses
18944        // ([`AplicacaoError::PolicyTimeoutZero`] then
18945        // [`AplicacaoError::PolicyTimeoutNotCanonical`];
18946        // [`AplicacaoError::PolicyBreakerZeroWindow`] then
18947        // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
18948        let mut s = three_member_spec();
18949        s.politicas.retries = Some(0);
18950        assert_eq!(
18951            s.validate().unwrap_err(),
18952            AplicacaoError::PolicyRetriesZero,
18953            "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
18954        );
18955    }
18956
18957    #[test]
18958    fn policy_retries_cap_diagnostic_carries_offending_value() {
18959        // The diagnostic-shape pin: the offending `u32` is carried
18960        // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
18961        // variant so the surfaced error message names the value the
18962        // author wrote (`":politicas :retries (47) exceeds the
18963        // mesh-policy ceiling …"`), not just the cap. Same
18964        // self-locating diagnostic shape every other typed-cap arm
18965        // on this surface carries
18966        // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
18967        // offending byte count verbatim).
18968        let mut s = three_member_spec();
18969        s.politicas.retries = Some(47);
18970        let err = s.validate().unwrap_err();
18971        assert!(
18972            matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
18973            "got {err:?}"
18974        );
18975        let msg = err.to_string();
18976        assert!(
18977            msg.contains("47"),
18978            ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
18979        );
18980    }
18981
18982    #[test]
18983    fn policy_retries_cap_is_aws_app_mesh_aligned() {
18984        // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
18985        // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
18986        // schema cap — the only upstream mesh-policy schema that
18987        // documents an explicit hard cap. Pinning the literal value
18988        // here surfaces a future drift (a relaxation to 20, a
18989        // tightening to 5) as a deliberate test edit, not a silent
18990        // contract narrowing.
18991        assert_eq!(POLICY_RETRIES_MAX, 10);
18992    }
18993
18994    #[test]
18995    fn rejects_circuit_breaker_zero_max_failures() {
18996        let mut s = three_member_spec();
18997        s.politicas.circuit_breaker = Some(CircuitBreaker {
18998            max_failures: 0,
18999            window: Duration::from_secs(60),
19000        });
19001        assert_eq!(
19002            s.validate().unwrap_err(),
19003            AplicacaoError::PolicyBreakerZeroFailures
19004        );
19005    }
19006
19007    #[test]
19008    fn rejects_circuit_breaker_max_failures_above_cap() {
19009        // The fail-before-pass-after pin: `1001` is structurally one
19010        // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
19011        // silently passed validate on every pre-gate codebase
19012        // because the typed slot's only check was the zero-floor
19013        // arm. The breaker-no-op vector only surfaced at the runtime
19014        // substrate (Envoy / Cilium L7 outlier-detection overlay)
19015        // far from the source caixa.lisp with no field naming the
19016        // offending policy.
19017        let mut s = three_member_spec();
19018        s.politicas.circuit_breaker = Some(CircuitBreaker {
19019            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
19020            window: Duration::from_secs(60),
19021        });
19022        assert_eq!(
19023            s.validate().unwrap_err(),
19024            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
19025                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
19026            }
19027        );
19028    }
19029
19030    #[test]
19031    fn rejects_circuit_breaker_max_failures_far_above_cap() {
19032        // The `u32::MAX` worst case — the four-billion-failure
19033        // threshold a typo (`(:max-failures 4294967295)`) or a
19034        // struct-literal copy-paste lands in the slot. Pin the cap
19035        // arm's coverage explicitly across the full `u32` overflow
19036        // so a future relaxation that drops the upper bound surfaces
19037        // here.
19038        let mut s = three_member_spec();
19039        s.politicas.circuit_breaker = Some(CircuitBreaker {
19040            max_failures: u32::MAX,
19041            window: Duration::from_secs(60),
19042        });
19043        assert_eq!(
19044            s.validate().unwrap_err(),
19045            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
19046                max_failures: u32::MAX,
19047            }
19048        );
19049    }
19050
19051    #[test]
19052    fn accepts_circuit_breaker_max_failures_at_cap() {
19053        // The boundary value — exactly
19054        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
19055        // cap is inclusive on the top edge, matching the
19056        // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
19057        // discipline on the sibling capped axes. Pin the boundary
19058        // explicitly so a future off-by-one tightening
19059        // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
19060        // surfaces here as a test failure rather than a silent
19061        // contract narrowing.
19062        let mut s = three_member_spec();
19063        s.politicas.circuit_breaker = Some(CircuitBreaker {
19064            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
19065            window: Duration::from_secs(60),
19066        });
19067        s.validate()
19068            .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
19069    }
19070
19071    #[test]
19072    fn accepts_circuit_breaker_max_failures_typical_values() {
19073        // The documented production-playbook band positive-control
19074        // sweep — every value Hystrix / Istio / Envoy / Polly /
19075        // Resilience4j recommend (5..=50) must pass, plus a sweep
19076        // through the hyperscale band (100, 500, 1000) the cap
19077        // accepts. Pin the inclusive validated set explicitly so a
19078        // future tightening of the ceiling surfaces here.
19079        //
19080        // Clears the fixture's `:retries` (which is `Some(3)`) so this
19081        // per-axis sweep is pure: the sibling cross-axis
19082        // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
19083        // gate rejects any `max_failures <= retries` pair, so the
19084        // `max_failures = 1` boundary at the head of the sweep would
19085        // otherwise trip on the fixture-inherited retry policy rather
19086        // than the per-axis boundary this test names. Same discipline
19087        // the sibling per-axis `accepts_circuit_breaker_window_*`
19088        // sweeps take against the fixture's `:timeout` for the
19089        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`]
19090        // cross-axis arm.
19091        for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
19092            let mut s = three_member_spec();
19093            s.politicas.retries = None;
19094            s.politicas.circuit_breaker = Some(CircuitBreaker {
19095                max_failures: n,
19096                window: Duration::from_secs(60),
19097            });
19098            s.validate()
19099                .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
19100        }
19101    }
19102
19103    #[test]
19104    fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
19105        // The cross-arm ordering pin: `0` is structurally outside
19106        // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
19107        // (cap), but the zero-floor diagnostic is the more
19108        // self-locating one (it directly names the omit-axis
19109        // remediation), so the validate gate must fire on zero
19110        // first. Same shape every other zero-then-shape ordering on
19111        // this surface uses
19112        // ([`AplicacaoError::PolicyRetriesZero`] then
19113        // [`AplicacaoError::PolicyRetriesExceedsCap`];
19114        // [`AplicacaoError::PolicyTimeoutZero`] then
19115        // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
19116        let mut s = three_member_spec();
19117        s.politicas.circuit_breaker = Some(CircuitBreaker {
19118            max_failures: 0,
19119            window: Duration::from_secs(60),
19120        });
19121        assert_eq!(
19122            s.validate().unwrap_err(),
19123            AplicacaoError::PolicyBreakerZeroFailures,
19124            "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
19125        );
19126    }
19127
19128    #[test]
19129    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
19130        // The cross-arm ordering pin between the cap and the
19131        // sibling `:window` gates (zero-window, canonical-window).
19132        // A breaker carrying both an over-cap `max_failures` AND a
19133        // structurally invalid window (zero, sub-ms) must surface
19134        // the cap diagnostic first — the cap arm is wired
19135        // immediately after the zero-failure arm and strictly
19136        // before the window arms, so the offending value the
19137        // diagnostic names matches the order the author would
19138        // discover the gates by reading top-to-bottom through
19139        // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
19140        // future refactor that reorders the arms surfaces here as a
19141        // test failure rather than a silent diagnostic regression.
19142        let mut s = three_member_spec();
19143        s.politicas.circuit_breaker = Some(CircuitBreaker {
19144            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
19145            window: Duration::ZERO,
19146        });
19147        assert_eq!(
19148            s.validate().unwrap_err(),
19149            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
19150                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
19151            },
19152            "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
19153        );
19154    }
19155
19156    #[test]
19157    fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
19158        // The diagnostic-shape pin: the offending `u32` is carried
19159        // verbatim into the
19160        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
19161        // variant so the surfaced error message names the value the
19162        // author wrote (`":politicas :circuit-breaker :max-failures
19163        // (50000) exceeds the mesh-policy ceiling …"`), not just
19164        // the cap. Same self-locating diagnostic shape every other
19165        // typed-cap arm on this surface carries
19166        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
19167        // offending retry count verbatim,
19168        // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
19169        // offending byte count verbatim).
19170        let mut s = three_member_spec();
19171        s.politicas.circuit_breaker = Some(CircuitBreaker {
19172            max_failures: 50_000,
19173            window: Duration::from_secs(60),
19174        });
19175        let err = s.validate().unwrap_err();
19176        assert!(
19177            matches!(
19178                err,
19179                AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
19180                    max_failures: 50_000
19181                }
19182            ),
19183            "got {err:?}"
19184        );
19185        let msg = err.to_string();
19186        assert!(
19187            msg.contains("50000"),
19188            ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
19189        );
19190    }
19191
19192    #[test]
19193    fn policy_breaker_max_failures_cap_pins_canonical_value() {
19194        // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
19195        // value at 1000 — an order of magnitude above every
19196        // documented production-playbook recommendation band
19197        // (Hystrix `requestVolumeThreshold` default 20, Istio
19198        // `outlierDetection.consecutive5xxErrors` default 5, Envoy
19199        // `outlier_detection.consecutive_5xx` default 5, Polly /
19200        // Resilience4j typical 5..=50) and below the
19201        // clearly-pathological "effectively no protection" floor
19202        // (10_000, 100_000, u32::MAX). Pinning the literal value
19203        // here surfaces a future drift (a relaxation to 10_000, a
19204        // tightening to 100) as a deliberate test edit, not a
19205        // silent contract narrowing.
19206        assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
19207    }
19208
19209    #[test]
19210    fn rejects_circuit_breaker_zero_window() {
19211        let mut s = three_member_spec();
19212        s.politicas.circuit_breaker = Some(CircuitBreaker {
19213            max_failures: 5,
19214            window: Duration::ZERO,
19215        });
19216        assert_eq!(
19217            s.validate().unwrap_err(),
19218            AplicacaoError::PolicyBreakerZeroWindow
19219        );
19220    }
19221
19222    #[test]
19223    fn rejects_zero_rate_limit() {
19224        let mut s = three_member_spec();
19225        s.politicas.rate_limit = Some(RateLimit {
19226            rate: 0,
19227            window: Duration::from_secs(1),
19228        });
19229        assert_eq!(
19230            s.validate().unwrap_err(),
19231            AplicacaoError::PolicyRateLimitZero
19232        );
19233    }
19234
19235    #[test]
19236    fn rejects_rate_limit_zero_window() {
19237        // `RateLimit { rate: 100, window: Duration::ZERO }` is
19238        // constructible programmatically (the typed `Duration` field
19239        // imposes no nonzero invariant) but renders through
19240        // `rate_limit_codec::render` as `"100/0s"` — a fragment the
19241        // codec's `parse` rejects as `unknown rate-limit window unit
19242        // "0s"`. Until this validate-time gate landed the typed slot
19243        // accepted the value silently and the round-trip break only
19244        // surfaced at deserialize time (potentially in a downstream
19245        // consumer that never re-validates). Pin the rejection at
19246        // `AplicacaoSpec::validate` so the typed slot's valid set
19247        // matches the codec's round-trippable set structurally.
19248        let mut s = three_member_spec();
19249        s.politicas.rate_limit = Some(RateLimit {
19250            rate: 100,
19251            window: Duration::ZERO,
19252        });
19253        assert_eq!(
19254            s.validate().unwrap_err(),
19255            AplicacaoError::PolicyRateLimitWindowNotCanonical {
19256                window: Duration::ZERO
19257            }
19258        );
19259    }
19260
19261    #[test]
19262    fn rejects_rate_limit_arbitrary_seconds_window() {
19263        // 45 seconds is a valid `Duration` but not one of the three
19264        // canonical rate-limit windows the codec round-trips
19265        // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
19266        // refuses on round-trip — same round-trip-break shape the
19267        // zero-window arm above pins, with a non-zero magnitude to
19268        // guard against a future "reject only zero" half-measure.
19269        let mut s = three_member_spec();
19270        let window = Duration::from_secs(45);
19271        s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
19272        assert_eq!(
19273            s.validate().unwrap_err(),
19274            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
19275        );
19276    }
19277
19278    #[test]
19279    fn rejects_rate_limit_two_minute_window() {
19280        // 120 seconds = 2 minutes is a "looks-canonical" but
19281        // not-canonical window: it's a clean integer multiple of the
19282        // minute unit, but the codec only round-trips the
19283        // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
19284        // A `Duration::from_secs(120)` window renders as `"100/120s"`
19285        // which the parser rejects. Pinning this case rules out a
19286        // future "accept any clean multiple of s/m/h" relaxation
19287        // that would silently break the codec contract.
19288        let mut s = three_member_spec();
19289        let window = Duration::from_secs(120);
19290        s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
19291        assert_eq!(
19292            s.validate().unwrap_err(),
19293            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
19294        );
19295    }
19296
19297    #[test]
19298    fn rejects_rate_limit_subsecond_window() {
19299        // A sub-second window (e.g. 500ms) is a valid `Duration` but
19300        // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
19301        // Pin the rejection so a future relaxation can't silently
19302        // admit fractional-second windows that the codec can't
19303        // round-trip.
19304        let mut s = three_member_spec();
19305        let window = Duration::from_millis(500);
19306        s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
19307        assert_eq!(
19308            s.validate().unwrap_err(),
19309            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
19310        );
19311    }
19312
19313    #[test]
19314    fn rejects_policy_rate_limit_above_cap() {
19315        // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
19316        // is structurally one past the cap and silently passed
19317        // validate on every pre-gate codebase because the typed slot's
19318        // only `rate` check was the zero-floor arm. The no-op-limiter
19319        // shape only surfaced at the runtime substrate (Envoy's
19320        // `local_rate_limit.token_bucket.max_tokens`, the future
19321        // Cilium L7 rate-limit overlay) far from the source caixa.lisp
19322        // with no field naming the offending policy.
19323        let mut s = three_member_spec();
19324        s.politicas.rate_limit = Some(RateLimit {
19325            rate: POLICY_RATE_LIMIT_MAX + 1,
19326            window: Duration::from_secs(1),
19327        });
19328        assert_eq!(
19329            s.validate().unwrap_err(),
19330            AplicacaoError::PolicyRateLimitExceedsCap {
19331                rate: POLICY_RATE_LIMIT_MAX + 1
19332            }
19333        );
19334    }
19335
19336    #[test]
19337    fn rejects_policy_rate_limit_far_above_cap() {
19338        // The `u32::MAX` worst case — the four-billion-token rate-limit
19339        // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
19340        // copy-paste lands in the slot. Pin the cap arm's coverage
19341        // explicitly across the full `u32` overflow so a future
19342        // relaxation that drops the upper bound surfaces here. Peer to
19343        // `rejects_policy_retries_far_above_cap` on the sibling
19344        // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
19345        // on the sibling `:max-failures` axis.
19346        let mut s = three_member_spec();
19347        s.politicas.rate_limit = Some(RateLimit {
19348            rate: u32::MAX,
19349            window: Duration::from_secs(1),
19350        });
19351        assert_eq!(
19352            s.validate().unwrap_err(),
19353            AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
19354        );
19355    }
19356
19357    #[test]
19358    fn accepts_policy_rate_limit_at_cap() {
19359        // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
19360        // must validate. The cap is inclusive on the top edge, matching
19361        // every other typed upper bound in this crate
19362        // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
19363        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
19364        // across all three canonical windows so a future off-by-one
19365        // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
19366        // window-conditional cap surfaces here as a test failure rather
19367        // than a silent contract narrowing.
19368        for secs in [1u64, 60, 3600] {
19369            let mut s = three_member_spec();
19370            s.politicas.rate_limit = Some(RateLimit {
19371                rate: POLICY_RATE_LIMIT_MAX,
19372                window: Duration::from_secs(secs),
19373            });
19374            s.validate().unwrap_or_else(|e| {
19375                panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
19376            });
19377        }
19378    }
19379
19380    #[test]
19381    fn accepts_policy_rate_limit_typical_values() {
19382        // The documented production-playbook recommendation band —
19383        // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
19384        // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
19385        // Enterprise ~1M per-hour. Every value in the validated set
19386        // must pass; pin the band explicitly so a future tightening
19387        // surfaces here.
19388        //
19389        // Clears the fixture's `:retries` (which is `Some(3)`) so this
19390        // per-axis sweep is pure: the sibling cross-axis
19391        // [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] gate
19392        // rejects any `rate <= retries` pair, so the `rate = 1`
19393        // boundary at the head of the sweep would otherwise trip on the
19394        // fixture-inherited retry policy rather than the per-axis
19395        // boundary this test names. Same discipline the sibling per-axis
19396        // `accepts_circuit_breaker_max_failures_typical_values` sweep
19397        // takes against the fixture's `:retries` for the peer cross-axis
19398        // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
19399        // arm.
19400        for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
19401            for secs in [1u64, 60, 3600] {
19402                let mut s = three_member_spec();
19403                s.politicas.retries = None;
19404                s.politicas.rate_limit = Some(RateLimit {
19405                    rate,
19406                    window: Duration::from_secs(secs),
19407                });
19408                s.validate().unwrap_or_else(|e| {
19409                    panic!("rate={rate} window={secs}s must validate; got {e:?}")
19410                });
19411            }
19412        }
19413    }
19414
19415    #[test]
19416    fn policy_rate_limit_zero_takes_precedence_over_cap() {
19417        // The cross-arm ordering pin: `rate == 0` is structurally
19418        // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
19419        // (cap), but the zero-floor diagnostic is the more
19420        // self-locating one (it directly names the omit-axis
19421        // remediation). Pin the order so a future refactor that
19422        // reorders the arms surfaces here as a test failure rather
19423        // than a silent diagnostic regression. Same shape every other
19424        // zero-then-cap ordering on this surface uses
19425        // ([`AplicacaoError::PolicyRetriesZero`] then
19426        // [`AplicacaoError::PolicyRetriesExceedsCap`];
19427        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
19428        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
19429        let mut s = three_member_spec();
19430        s.politicas.rate_limit = Some(RateLimit {
19431            rate: 0,
19432            window: Duration::from_secs(1),
19433        });
19434        assert_eq!(
19435            s.validate().unwrap_err(),
19436            AplicacaoError::PolicyRateLimitZero,
19437            "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
19438        );
19439    }
19440
19441    #[test]
19442    fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
19443        // Two-axis-bad pin: rate above cap *and* window non-canonical.
19444        // The validate gate must fire on the rate cap first — the
19445        // amplification-shape (no-op limiter) diagnostic is the more
19446        // fundamental one; the window-canonical diagnostic is the
19447        // narrower codec-round-trip shape. Pin the ordering so a future
19448        // refactor that reorders the rate-then-window check arms
19449        // surfaces here as a test failure rather than a silent
19450        // diagnostic regression.
19451        let mut s = three_member_spec();
19452        s.politicas.rate_limit = Some(RateLimit {
19453            rate: POLICY_RATE_LIMIT_MAX + 1,
19454            window: Duration::from_secs(45),
19455        });
19456        assert_eq!(
19457            s.validate().unwrap_err(),
19458            AplicacaoError::PolicyRateLimitExceedsCap {
19459                rate: POLICY_RATE_LIMIT_MAX + 1
19460            },
19461            "above-cap rate must surface the cap diagnostic, not the window diagnostic"
19462        );
19463    }
19464
19465    #[test]
19466    fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
19467        // The diagnostic-shape pin: the offending `u32` is carried
19468        // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
19469        // variant so the surfaced error message names the value the
19470        // author wrote (`":politicas :rate-limit rate (5000000) exceeds
19471        // the mesh-policy ceiling …"`), not just the cap. Same
19472        // self-locating diagnostic shape every other typed-cap arm on
19473        // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
19474        // carries the offending retries count verbatim,
19475        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
19476        // the offending failure count verbatim).
19477        let mut s = three_member_spec();
19478        s.politicas.rate_limit = Some(RateLimit {
19479            rate: 5_000_000,
19480            window: Duration::from_secs(1),
19481        });
19482        let err = s.validate().unwrap_err();
19483        assert!(
19484            matches!(
19485                err,
19486                AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
19487            ),
19488            "got {err:?}"
19489        );
19490        let msg = err.to_string();
19491        assert!(
19492            msg.contains("5000000"),
19493            ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
19494        );
19495    }
19496
19497    #[test]
19498    fn policy_rate_limit_cap_pins_canonical_value() {
19499        // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
19500        // 1_000_000 — two-to-three orders of magnitude above every
19501        // documented production-playbook recommendation band (Envoy /
19502        // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
19503        // Gateway 10_000..=100_000 per-minute) and below the
19504        // clearly-pathological "paste-from-binary blob" floor
19505        // (100_000_000, u32::MAX). Pinning the literal value here
19506        // surfaces a future drift (a relaxation to 10_000_000, a
19507        // tightening to 100_000) as a deliberate test edit, not a
19508        // silent contract narrowing.
19509        assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
19510    }
19511
19512    #[test]
19513    fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
19514        // Both axes are invalid here: rate == 0 *and* window is
19515        // non-canonical. The validate gate must fire on rate first
19516        // (matching the existing `rejects_zero_rate_limit` ordering),
19517        // so the existing diagnostic continues to lead with the
19518        // simpler "zero rate" framing. Pinning the order of checks
19519        // so a future refactor that reorders the arms surfaces here
19520        // as a test failure rather than a silent diagnostic
19521        // regression.
19522        let mut s = three_member_spec();
19523        s.politicas.rate_limit = Some(RateLimit {
19524            rate: 0,
19525            window: Duration::from_secs(45),
19526        });
19527        assert_eq!(
19528            s.validate().unwrap_err(),
19529            AplicacaoError::PolicyRateLimitZero
19530        );
19531    }
19532
19533    #[test]
19534    fn rate_limit_canonical_windows_validate() {
19535        // The three canonical windows the codec round-trips
19536        // losslessly — 1s / 60s / 3600s — must all pass `validate()`
19537        // unchanged. Pin the full canonical set as a positive case
19538        // (the existing `rate_limit_round_trip_seconds` /
19539        // `rate_limit_round_trip_minutes` tests pin the
19540        // serialize-then-deserialize property at the codec layer; this
19541        // test pins the validate-side complement so a future tightening
19542        // of the canonical set — e.g. dropping `:hour` — surfaces here
19543        // as a test failure rather than a silent contract narrowing).
19544        for secs in [1u64, 60, 3600] {
19545            let mut s = three_member_spec();
19546            s.politicas.rate_limit = Some(RateLimit {
19547                rate: 100,
19548                window: Duration::from_secs(secs),
19549            });
19550            s.validate().expect("canonical window must validate");
19551        }
19552    }
19553
19554    #[test]
19555    fn rate_limit_validated_value_round_trips_through_codec() {
19556        // The structural property the validate gate enforces:
19557        // every `RateLimit` past `AplicacaoSpec::validate` round-trips
19558        // losslessly through the `rate_limit_codec` (serialize → string
19559        // → deserialize → equal value). Pin this end-to-end so a future
19560        // change to either side (the validate gate's accepted window
19561        // set, the codec's parse/render unit set) that breaks the
19562        // alignment surfaces here. The previous-state shape (typed
19563        // slot accepts arbitrary `Duration`, codec only round-trips
19564        // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
19565        // window — the validate gate now forecloses that.
19566        for secs in [1u64, 60, 3600] {
19567            let mut s = three_member_spec();
19568            s.politicas.rate_limit = Some(RateLimit {
19569                rate: 250,
19570                window: Duration::from_secs(secs),
19571            });
19572            s.validate().unwrap();
19573            let json = serde_json::to_string(&s.politicas).unwrap();
19574            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
19575            assert_eq!(
19576                back.rate_limit, s.politicas.rate_limit,
19577                "every validated :rate-limit must round-trip losslessly through the codec"
19578            );
19579        }
19580    }
19581
19582    #[test]
19583    fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
19584        // The hour-window canonical form (`"<n>/h"`) was missing from
19585        // the prior `rate_limit_round_trip_seconds` / `_minutes` test
19586        // pair. Now that the validate gate pins 3600s as part of the
19587        // canonical set, pin its serialize-side render shape too so
19588        // the third leg of the s/m/h tripod is explicitly tested.
19589        let policy = MeshPolicy {
19590            rate_limit: Some(RateLimit {
19591                rate: 10000,
19592                window: Duration::from_secs(3600),
19593            }),
19594            ..Default::default()
19595        };
19596        let json = serde_json::to_string(&policy).unwrap();
19597        assert!(
19598            json.contains("\"10000/h\""),
19599            "hour-window canonical form must render with `h` suffix (got: {json})"
19600        );
19601        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
19602        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
19603    }
19604
19605    #[test]
19606    fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
19607        // Pin the substrate-primitive [`RateLimit::canonical_unit`]
19608        // typed accessor's accepted-window set against the codec's
19609        // accepted set explicitly. A future addition to the codec
19610        // (e.g. accepting `:day`/`:week` as authoring units) must be
19611        // accompanied by a parallel addition here, and a regression
19612        // that drops one of the three canonical units from either
19613        // side surfaces as a test failure. The accessor is the
19614        // single source of truth for the canonical-window set —
19615        // [`AplicacaoSpec::validate_politicas`]'s canonical-window
19616        // gate and [`rate_limit_codec::render`]'s canonical arm both
19617        // read through it — this test enshrines that its
19618        // `Duration → Option<RateLimitUnit>` projection matches the
19619        // codec's parse / render arms' accepted-window set exactly.
19620        //
19621        // Predecessor: this pin previously read the module-private
19622        // free helper `is_canonical_rate_limit_window` — a delegate
19623        // that composed [`RateLimitUnit::from_window`] with `.is_some()`
19624        // — but the helper had no production consumers left after the
19625        // validate-gate migration onto [`RateLimit::canonical_unit`]
19626        // and was deleted; the closed-set arm-window bijection now
19627        // lives on exactly one typed dispatch on the substrate
19628        // primitive.
19629        let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
19630            RateLimit { rate: 1, window }.canonical_unit()
19631        };
19632        assert!(canonical_unit(Duration::from_secs(1)).is_some());
19633        assert!(canonical_unit(Duration::from_secs(60)).is_some());
19634        assert!(canonical_unit(Duration::from_secs(3600)).is_some());
19635        // Non-canonical windows the accessor rejects.
19636        assert!(canonical_unit(Duration::ZERO).is_none());
19637        assert!(canonical_unit(Duration::from_secs(2)).is_none());
19638        assert!(canonical_unit(Duration::from_secs(30)).is_none());
19639        assert!(canonical_unit(Duration::from_secs(120)).is_none());
19640        assert!(canonical_unit(Duration::from_secs(86400)).is_none());
19641        // Sub-second windows: even `Duration::from_millis(1000)` is
19642        // exactly 1s and accepted; `Duration::from_millis(500)` is
19643        // sub-second and rejected.
19644        assert!(canonical_unit(Duration::from_millis(1000)).is_some());
19645        assert!(canonical_unit(Duration::from_millis(500)).is_none());
19646        assert!(canonical_unit(Duration::from_millis(1500)).is_none());
19647    }
19648
19649    #[test]
19650    fn rate_limit_unit_table_projections_are_mutual_inverses() {
19651        // Bidirection pin against the closed-set typed enum
19652        // [`RateLimitUnit`] arm-table (the canonical
19653        // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
19654        // of the rate-limit unit surface reads from). The two
19655        // projection directions [`RateLimitUnit::from_suffix`] /
19656        // [`RateLimitUnit::window`] (str → Duration, exposed as one
19657        // typed dispatch through [`RateLimitUnit::window_from_suffix`])
19658        // and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
19659        // (Duration → str, exposed as one typed dispatch through
19660        // [`RateLimit::canonical_unit`] composed with
19661        // [`RateLimitUnit::as_suffix`]) are the substrate primitives the
19662        // codec's parse arm ([`rate_limit_codec::parse`] via
19663        // [`RateLimitUnit::window_from_suffix`]), the codec's render arm
19664        // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
19665        // and the validate gate ([`AplicacaoSpec::validate_politicas`]
19666        // via [`RateLimit::canonical_unit`]) all key off. A future
19667        // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
19668        // sub-second window) is one variant + one arm per method on the
19669        // closed-set enum; the compiler-enforced exhaustiveness on
19670        // every consumer's `match self` arms picks it up by
19671        // construction. This pin enshrines that both projection
19672        // directions agree on every canonical arm row and neither
19673        // leaks a spurious entry the other doesn't recognize.
19674        //
19675        // Predecessor: this test previously read the two vestigial
19676        // module-private free helpers `rate_limit_window_unit` and
19677        // `rate_limit_window_from_unit` on the `Duration → &str` and
19678        // `&str → Duration` axes; the former was deleted after its
19679        // sole production consumer ([`rate_limit_codec::render`])
19680        // migrated onto [`RateLimit::canonical_unit`] (61421a6), and
19681        // the latter is folded here into the substrate primitive
19682        // [`RateLimitUnit::window_from_suffix`] so both projection
19683        // directions live on the closed-set enum's arm-table.
19684        for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
19685            let window = super::RateLimitUnit::window_from_suffix(unit)
19686                .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
19687            assert_eq!(
19688                window,
19689                Duration::from_secs(secs),
19690                "unit {unit:?} must resolve to {secs}s"
19691            );
19692            let projected_suffix = RateLimit { rate: 1, window }
19693                .canonical_unit()
19694                .map(super::RateLimitUnit::as_suffix);
19695            assert_eq!(
19696                projected_suffix,
19697                Some(unit),
19698                "Duration({secs}s) must render as {unit:?} \
19699                 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
19700            );
19701        }
19702        // Non-table units yield None on the `unit → Duration`
19703        // projection — a future `"d"` addition to the table would
19704        // flip this arm; today it pins the current three-row table's
19705        // rejection semantics.
19706        assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
19707        assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
19708        assert!(super::RateLimitUnit::window_from_suffix("").is_none());
19709        // Non-table Durations yield None on the `Duration → unit`
19710        // projection — pins that the two projections agree on the
19711        // "not in the table" semantic too, so a drift where the
19712        // parse-side accepts a value the render-side can't emit is
19713        // a build error at the two-arm pair, not a silent codec
19714        // round-trip break.
19715        let projected_suffix = |window: Duration| -> Option<&'static str> {
19716            RateLimit { rate: 1, window }
19717                .canonical_unit()
19718                .map(super::RateLimitUnit::as_suffix)
19719        };
19720        assert!(projected_suffix(Duration::from_secs(2)).is_none());
19721        assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
19722        assert!(projected_suffix(Duration::from_millis(1500)).is_none());
19723    }
19724
19725    #[test]
19726    fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
19727        // Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
19728        // substrate-primitive `&str → Duration` associated method the
19729        // codec's parse arm ([`rate_limit_codec::parse`]) now routes
19730        // through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
19731        // to the same [`Duration`] the two-step composition
19732        // [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
19733        // returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
19734        // `"MIN"`) must project to [`None`] on both paths. A future
19735        // implementation of `window_from_suffix` that took a shortcut
19736        // through a per-suffix `match` table (bypassing the arm-table's
19737        // `Self::from_suffix` scan and the arm-table's `Self::window`
19738        // dispatch) would silently split the accept-set — the parse
19739        // arm would accept a suffix the enum's arm-table doesn't know,
19740        // or reject a suffix the enum's arm-table does; this pin
19741        // surfaces that drift at caixa-core build time rather than at a
19742        // downstream serde round-trip audit on a live `MeshPolicy`.
19743        //
19744        // Same byte-parity discipline the sibling
19745        // [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
19746        // pin carries on the peer `Duration → RateLimitUnit` axis via
19747        // [`RateLimit::canonical_unit`], and the peer
19748        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
19749        // carries on the bidirectional arm-table axis — extended here
19750        // onto the fifth (and last unlifted) projection axis on the
19751        // closed-set enum's arm-table.
19752        let composition = |suffix: &str| -> Option<Duration> {
19753            super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
19754        };
19755        for suffix in ["s", "m", "h"] {
19756            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
19757            let via_composition = composition(suffix);
19758            assert_eq!(
19759                via_method, via_composition,
19760                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
19761                 from_suffix({suffix:?}).map(window) — the substrate-primitive \
19762                 method must delegate to the arm-table's two typed dispatches, \
19763                 not shortcut through a per-suffix match table"
19764            );
19765            assert!(
19766                via_method.is_some(),
19767                "canonical suffix {suffix:?} must resolve to Some(Duration) via \
19768                 RateLimitUnit::window_from_suffix"
19769            );
19770        }
19771        for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
19772            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
19773            let via_composition = composition(suffix);
19774            assert_eq!(
19775                via_method, via_composition,
19776                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
19777                 from_suffix({suffix:?}).map(window) on the non-arm rejection \
19778                 axis too"
19779            );
19780            assert!(
19781                via_method.is_none(),
19782                "non-arm suffix {suffix:?} must project to None via \
19783                 RateLimitUnit::window_from_suffix — a future extension that \
19784                 accepted this suffix without a corresponding arm on the enum \
19785                 would split the codec's parse-accepted set from the enum's \
19786                 arm-table"
19787            );
19788        }
19789        // And the codec's parse arm now reads through this method: a
19790        // canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
19791        // the same `Duration` the method returns for its unit, closing
19792        // the two-consumer drift surface (the codec's parse arm and the
19793        // enum's arm-table) with one typed dispatch on the substrate
19794        // primitive.
19795        for suffix in ["s", "m", "h"] {
19796            let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
19797            let mp: MeshPolicy = serde_json::from_str(&wire)
19798                .unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
19799            let parsed = mp.rate_limit().expect("rate_limit payload present");
19800            let via_method = super::RateLimitUnit::window_from_suffix(suffix)
19801                .unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
19802            assert_eq!(
19803                parsed.window(),
19804                via_method,
19805                "codec parse arm on {wire:?} must resolve the window through \
19806                 RateLimitUnit::window_from_suffix, not a divergent path"
19807            );
19808        }
19809    }
19810
19811    #[test]
19812    fn rate_limit_unit_all_enumerates_every_arm_once() {
19813        // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
19814        // enumerate every arm of the closed-set enum exactly once, in
19815        // the canonical shortest-to-longest window order (Second before
19816        // Minute before Hour) — the same order the sibling
19817        // [`crate::supervisor::RestartStrategy`] /
19818        // [`crate::supervisor::RestartPolicy`] /
19819        // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
19820        // typed enums carry (the arm declared first is the arm listed
19821        // first). A future variant addition that extends the enum
19822        // without appending to [`RateLimitUnit::ALL`] leaves the
19823        // exhaustive iteration surface silently short one arm — the
19824        // codec's parse arm would then reject the new suffix even
19825        // though the enum knows it. This pin closes the drift.
19826        assert_eq!(
19827            super::RateLimitUnit::ALL,
19828            &[
19829                super::RateLimitUnit::Second,
19830                super::RateLimitUnit::Minute,
19831                super::RateLimitUnit::Hour,
19832            ],
19833            "RateLimitUnit::ALL must enumerate every arm exactly once, \
19834             in canonical shortest-to-longest window order"
19835        );
19836    }
19837
19838    #[test]
19839    fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
19840        // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
19841        // every arm's [`RateLimitUnit::as_suffix`] output must parse
19842        // back through [`RateLimitUnit::from_suffix`] to the same
19843        // variant. A future arm addition that lands `as_suffix` but
19844        // forgets `from_suffix` (`from_suffix` iterates
19845        // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
19846        // is the load-bearing carrier of the round-trip; the sibling
19847        // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
19848        // the `ALL` half) trips here at caixa-core build time rather
19849        // than surfacing as a codec round-trip miss (a `render` emit
19850        // that lands a suffix the paired `parse` cannot decode).
19851        for unit in super::RateLimitUnit::ALL {
19852            let suffix = unit.as_suffix();
19853            let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
19854                panic!(
19855                    "RateLimitUnit::from_suffix({suffix:?}) must accept every \
19856                     RateLimitUnit::as_suffix output — got None for {unit:?}"
19857                )
19858            });
19859            assert_eq!(
19860                parsed, *unit,
19861                "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
19862                 must return RateLimitUnit::{unit:?}"
19863            );
19864        }
19865    }
19866
19867    #[test]
19868    fn rate_limit_unit_from_window_and_window_round_trip() {
19869        // Total round-trip pin on the `(from_window, window)` pair:
19870        // every arm's [`RateLimitUnit::window`] output must parse back
19871        // through [`RateLimitUnit::from_window`] to the same variant.
19872        // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
19873        // on the peer `Duration` axis — the two round-trip pins
19874        // together enshrine that both projections of the typed
19875        // canonical-unit bijection are total on the arm-set.
19876        for unit in super::RateLimitUnit::ALL {
19877            let window = unit.window();
19878            let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
19879                panic!(
19880                    "RateLimitUnit::from_window({window:?}) must accept every \
19881                     RateLimitUnit::window output — got None for {unit:?}"
19882                )
19883            });
19884            assert_eq!(
19885                parsed, *unit,
19886                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
19887                 must return RateLimitUnit::{unit:?}"
19888            );
19889        }
19890    }
19891
19892    #[test]
19893    fn rate_limit_unit_from_window_accessor_is_const_fn() {
19894        // Fail-before-pass-after pin: witnesses the
19895        // [`RateLimitUnit::from_window`] `const`-eval posture via a
19896        // `const fn` wrapper `from_window_via_const_fn(window: Duration)
19897        // -> Option<RateLimitUnit>` whose body calls
19898        // `RateLimitUnit::from_window(window)`, well-formed only when
19899        // the callee is itself `const fn` (any future downgrade to
19900        // non-`const` fails at caixa-core build time with E0015 `cannot
19901        // call non-const function`, strictly stronger than a runtime
19902        // `assert!`, side-stepping the destructor-in-const restriction
19903        // that blocks direct `const _: Option<RateLimitUnit> =
19904        // RateLimitUnit::from_window(...)` items on `Duration`'s
19905        // carrier). The runtime body sweeps every closed-set
19906        // [`RateLimitUnit::ALL`] arm plus a representative non-canonical
19907        // rejection sample (`Duration::from_millis(500)` sub-second
19908        // residue) and asserts the wrapped and direct dispatches agree
19909        // — a violation means the wrapper stopped compiling under a
19910        // future `const`-posture downgrade, or the reverse resolver's
19911        // arm-set silently split from the peer `Self::window` emitter's
19912        // arm-set. Peer of the sibling
19913        // [`crate::supervisor::tests::child_spec_restart_accessor_is_const_fn`]
19914        // (152c868) /
19915        // [`crate::supervisor::tests::supervisor_spec_estrategia_accessor_is_const_fn`]
19916        // (152c868) /
19917        // [`entrada_port_accessor_is_const_fn`] (bafa004) /
19918        // [`placement_estrategia_accessor_is_const_fn`] (bafa004)
19919        // `const`-eval-surface pins on the peer M2 / M3 substrate-
19920        // primitive `Copy`-return accessor axes, extended onto the
19921        // reverse `Duration → RateLimitUnit` projection axis on the
19922        // M3 mesh-slot rate-limit closed-set typed enum.
19923        const fn from_window_via_const_fn(window: Duration) -> Option<super::RateLimitUnit> {
19924            super::RateLimitUnit::from_window(window)
19925        }
19926        for unit in super::RateLimitUnit::ALL {
19927            let window = unit.window();
19928            let via_wrapper = from_window_via_const_fn(window);
19929            let direct = super::RateLimitUnit::from_window(window);
19930            assert_eq!(
19931                via_wrapper, direct,
19932                "RateLimitUnit::from_window({window:?}) via const fn \
19933                 wrapper must agree with direct dispatch for {unit:?}"
19934            );
19935            assert_eq!(
19936                via_wrapper,
19937                Some(*unit),
19938                "RateLimitUnit::from_window({window:?}) via const fn \
19939                 wrapper must return Some({unit:?}) for the peer \
19940                 window() output"
19941            );
19942        }
19943        assert!(from_window_via_const_fn(Duration::from_millis(500)).is_none());
19944        assert!(from_window_via_const_fn(Duration::from_secs(30)).is_none());
19945    }
19946
19947    #[test]
19948    fn rate_limit_unit_from_window_composes_through_window_accessor() {
19949        // Composition-witness pin on the routing-through-peer discipline:
19950        // [`RateLimitUnit::from_window`]'s per-arm probes each dispatch
19951        // through the peer `pub const fn` [`RateLimitUnit::window`]
19952        // canonical-`Duration` projection rather than a hand-authored
19953        // per-arm second-magnitude literal — a future arm-magnitude edit
19954        // on the sibling `window()` accessor (a `Second → 2s` typo, a
19955        // `Hour → 3599s` off-by-one) must therefore reach this reverse
19956        // resolver by construction. A pin that hard-coded the three
19957        // second-magnitudes here would silently split from the peer
19958        // emitter on any such edit; instead, this pin asserts the
19959        // composition invariant `from_window(u.window()) == Some(u)`
19960        // holds byte-for-byte on every closed-set [`RateLimitUnit::ALL`]
19961        // arm — a violation means either the peer `Self::window`
19962        // accessor drifted (breaking every downstream consumer that
19963        // reads through it), or the reverse resolver stopped routing
19964        // through the peer (introducing a hand-authored literal that
19965        // silently disagrees with the emitter). Either failure is a
19966        // caixa-core-build-time surface, not a downstream renderer
19967        // round-trip regression.
19968        //
19969        // Peer of the sibling
19970        // [`crate::render::assert_str_reexport_identity`] discipline on
19971        // the substrate-primitive `&'static str` re-export axis and the
19972        // [`rate_limit_unit_from_window_and_window_round_trip`]
19973        // round-trip pin on the peer projection direction; extends the
19974        // one-canonical-dispatch-per-projection discipline onto the
19975        // reverse-resolver's per-arm probe axis.
19976        for unit in super::RateLimitUnit::ALL {
19977            let window_via_peer = unit.window();
19978            let resolved = super::RateLimitUnit::from_window(window_via_peer);
19979            assert_eq!(
19980                resolved,
19981                Some(*unit),
19982                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
19983                 must return Some({unit:?}) — the reverse resolver's per-arm \
19984                 probes must route through the peer `Self::window` accessor \
19985                 so any future arm-magnitude edit reaches both projection \
19986                 directions by construction"
19987            );
19988        }
19989    }
19990
19991    #[test]
19992    fn rate_limit_canonical_unit_accessor_is_const_fn() {
19993        // Fail-before-pass-after pin: witnesses the
19994        // [`RateLimit::canonical_unit`] `const`-eval posture via a
19995        // `const fn` wrapper
19996        // `canonical_unit_via_const_fn(rl: &RateLimit) -> Option<RateLimitUnit>`
19997        // whose body calls `rl.canonical_unit()`, well-formed only when
19998        // the callee is itself `const fn` (any future downgrade to
19999        // non-`const` fails at caixa-core build time with E0015 `cannot
20000        // call non-const method`). The runtime body sweeps every
20001        // closed-set [`RateLimitUnit::ALL`] arm — for each arm,
20002        // constructs a typed [`RateLimit`] with the peer `Self::window`
20003        // canonical `Duration`, then asserts both the wrapper and the
20004        // direct dispatch agree and both return `Some(unit)`. Composes
20005        // with the sibling
20006        // [`rate_limit_unit_from_window_accessor_is_const_fn`] pin: the
20007        // typed [`RateLimit`] projection layer's `const`-posture is
20008        // load-bearing on the reverse resolver's `const`-posture, and
20009        // both must migrate together (a downgrade of either surface
20010        // splits the paired `const`-eval-surface pass on the M3
20011        // mesh-slot rate-limit `Duration ↔ Self` bijection).
20012        const fn canonical_unit_via_const_fn(
20013            rl: &super::RateLimit,
20014        ) -> Option<super::RateLimitUnit> {
20015            rl.canonical_unit()
20016        }
20017        for unit in super::RateLimitUnit::ALL {
20018            let rl = super::RateLimit {
20019                rate: 1,
20020                window: unit.window(),
20021            };
20022            let via_wrapper = canonical_unit_via_const_fn(&rl);
20023            let direct = rl.canonical_unit();
20024            assert_eq!(
20025                via_wrapper, direct,
20026                "RateLimit::canonical_unit() via const fn wrapper must \
20027                 agree with direct dispatch for {unit:?}"
20028            );
20029            assert_eq!(
20030                via_wrapper,
20031                Some(*unit),
20032                "RateLimit::canonical_unit() via const fn wrapper must \
20033                 return Some({unit:?}) for a RateLimit whose window is \
20034                 the peer RateLimitUnit::{unit:?}.window() output"
20035            );
20036        }
20037    }
20038
20039    #[test]
20040    fn rate_limit_unit_projections_are_pairwise_distinct() {
20041        // Distinctness pin: [`RateLimitUnit::as_suffix`] and
20042        // [`RateLimitUnit::window`] outputs must be pairwise distinct
20043        // across every arm — an accidental copy-paste flip that
20044        // reroutes one arm's suffix or window to also match another
20045        // silently collapses two arms onto one, so
20046        // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
20047        // (both using `find` on `Self::ALL`) would return whichever
20048        // arm the linear scan lands on first — a match-arm-ordering-
20049        // dependent outcome the closed-set typed-enum shape is meant
20050        // to rule out structurally. Peer of the sibling
20051        // `caixa_kind_wire_consts_are_pairwise_distinct` /
20052        // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
20053        // other closed-set typed-enum discriminator axes.
20054        let all = super::RateLimitUnit::ALL;
20055        for (i, a) in all.iter().enumerate() {
20056            for (j, b) in all.iter().enumerate() {
20057                if i != j {
20058                    assert_ne!(
20059                        a.as_suffix(),
20060                        b.as_suffix(),
20061                        "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
20062                         must be distinct — a collision silently collapses two \
20063                         arms onto one under from_suffix's linear scan"
20064                    );
20065                    assert_ne!(
20066                        a.window(),
20067                        b.window(),
20068                        "RateLimitUnit::{a:?}.window() and {b:?}.window() \
20069                         must be distinct — a collision silently collapses two \
20070                         arms onto one under from_window's linear scan"
20071                    );
20072                }
20073            }
20074        }
20075    }
20076
20077    #[test]
20078    fn rate_limit_unit_display_routes_through_as_suffix() {
20079        // Route pin: [`std::fmt::Display`] must byte-equal
20080        // [`RateLimitUnit::as_suffix`] on every arm — the single
20081        // source of truth for the canonical suffix. A future
20082        // reimplementation that hand-rolls the arms instead of
20083        // delegating to [`RateLimitUnit::as_suffix`] would silently
20084        // desynchronize `format!("{u}")` from the codec's parse arm
20085        // (which uses `as_suffix` to compare suffixes). Peer of the
20086        // sibling `caixa_kind_display_routes_through_as_str_helper` /
20087        // `placement_strategy_display_routes_through_as_str_helper`
20088        // pins on the peer closed-set typed-enum Display axes.
20089        for unit in super::RateLimitUnit::ALL {
20090            assert_eq!(
20091                unit.to_string(),
20092                unit.as_suffix(),
20093                "RateLimitUnit::{unit:?} Display must route through \
20094                 as_suffix (single source of truth: the canonical suffix \
20095                 the codec parses and renders)"
20096            );
20097        }
20098    }
20099
20100    #[test]
20101    fn rate_limit_unit_from_window_rejects_non_canonical() {
20102        // Rejection pin on the parser's accept-set: any Duration
20103        // outside the three-arm [`RateLimitUnit::window`] output set
20104        // (sub-second residue, or a second-magnitude outside `{1, 60,
20105        // 3600}`) must return `None`. A future accidental widening of
20106        // the accept-set (rounding down sub-second residue to the
20107        // nearest arm, admitting `Duration::from_secs(30)` as a
20108        // half-minute unit) would silently drift the parser's accept-
20109        // set from the emitter's — a validated slot with a
20110        // non-canonical window would then round-trip through the
20111        // codec to a canonical form the author never wrote.
20112        assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
20113        assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
20114        assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
20115        assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
20116        assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
20117        assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
20118        assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
20119    }
20120
20121    #[test]
20122    fn rate_limit_unit_from_suffix_rejects_unknown() {
20123        // Rejection pin on the suffix parser's accept-set: any string
20124        // outside the three-arm [`RateLimitUnit::as_suffix`] output
20125        // set must return `None`. Peer of the sibling
20126        // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
20127        // the [`crate::CaixaKind`] `from_wire` accept-set.
20128        for bad in [
20129            "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
20130            " s",
20131        ] {
20132            assert!(
20133                super::RateLimitUnit::from_suffix(bad).is_none(),
20134                "RateLimitUnit::from_suffix({bad:?}) must return None — the \
20135                 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
20136                 outputs"
20137            );
20138        }
20139    }
20140
20141    #[test]
20142    fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
20143        // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
20144        // every canonical `:window` magnitude the validate gate
20145        // accepts must map to the paired [`RateLimitUnit`] arm through
20146        // this accessor. A future validate-gate rebrand that widened
20147        // the accepted-window set without extending [`RateLimitUnit`]
20148        // would silently split the accessor's `Some`-return set from
20149        // the validate gate's accept-set — a slot that satisfies
20150        // validate would land at the accessor with `None`, so a
20151        // consumer past validate that pattern-matches on the returned
20152        // `Some` would silently miss the newly-accepted magnitude.
20153        for (window_secs, expected) in [
20154            (1u64, super::RateLimitUnit::Second),
20155            (60, super::RateLimitUnit::Minute),
20156            (3600, super::RateLimitUnit::Hour),
20157        ] {
20158            let rl = RateLimit {
20159                rate: 100,
20160                window: Duration::from_secs(window_secs),
20161            };
20162            assert_eq!(
20163                rl.canonical_unit(),
20164                Some(expected),
20165                "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
20166                 must return Some({expected:?})"
20167            );
20168        }
20169        // Non-canonical windows the validate gate rejects also return
20170        // None here — the accessor is the typed-enum projection of
20171        // the sibling `is_canonical_rate_limit_window` predicate.
20172        let bad = RateLimit {
20173            rate: 100,
20174            window: Duration::from_secs(30),
20175        };
20176        assert!(
20177            bad.canonical_unit().is_none(),
20178            "RateLimit with a non-canonical window must return None from \
20179             canonical_unit — the validate gate rejects the same set"
20180        );
20181    }
20182
20183    #[test]
20184    fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
20185        // Fail-before-pass-after byte-parity pin: for every canonical
20186        // window the [`rate_limit_codec::render`] arm's emitted string
20187        // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
20188        // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
20189        // the vestigial free helper [`rate_limit_window_unit`] (a
20190        // `find_map`-walked `Duration → &'static str` delegate) onto the
20191        // substrate primitive [`RateLimit::canonical_unit`] typed method
20192        // (a closed-set `match self.window` arm on
20193        // [`RateLimitUnit::from_window`], projected through
20194        // [`RateLimitUnit::as_suffix`] via the enum's
20195        // [`std::fmt::Display`] impl). A future re-routing of the render
20196        // arm through a differently-computed unit projection would break
20197        // this pin at build time rather than as a silent per-consumer
20198        // codec round-trip drift far from the substrate primitive edit.
20199        //
20200        // Sibling to the peer
20201        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
20202        // on the free-helper axis: that pin locks the two projections
20203        // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
20204        // on the closed-set arm table; this pin locks the codec's render
20205        // arm reads through the typed accessor rather than the free
20206        // helper. Two production consumers of the canonical-unit axis
20207        // now key off one typed dispatch on the substrate primitive.
20208        for (window_secs, unit) in [
20209            (1u64, super::RateLimitUnit::Second),
20210            (60, super::RateLimitUnit::Minute),
20211            (3600, super::RateLimitUnit::Hour),
20212        ] {
20213            let rl = RateLimit {
20214                rate: 42,
20215                window: Duration::from_secs(window_secs),
20216            };
20217            let policy = MeshPolicy {
20218                rate_limit: Some(rl),
20219                ..Default::default()
20220            };
20221            let json = serde_json::to_string(&policy).unwrap();
20222            let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
20223            assert!(
20224                json.contains(&expected),
20225                "rate_limit_codec::render must emit {expected} (via \
20226                 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
20227                 for a {window_secs}s window; serialized MeshPolicy was: {json}"
20228            );
20229            // And the accessor route resolves to the same typed unit
20230            // the render arm's Display formatting is asked to produce —
20231            // so a future edit that split the two paths (one through
20232            // the accessor, one through a re-introduced free helper)
20233            // trips this pin.
20234            assert_eq!(
20235                rl.canonical_unit(),
20236                Some(unit),
20237                "RateLimit::canonical_unit must return Some({unit:?}) for a \
20238                 {window_secs}s window; the codec render arm reads the same \
20239                 typed unit through this accessor"
20240            );
20241        }
20242    }
20243
20244    #[test]
20245    fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
20246        // Fail-before-pass-after byte-parity pin on the validate gate's
20247        // canonical-window shape probe: every non-canonical `:window`
20248        // the free-helper predicate [`is_canonical_rate_limit_window`]
20249        // rejects is also rejected by the substrate primitive
20250        // [`RateLimit::canonical_unit`] `.is_none()` route the validate
20251        // gate now reads through, and vice versa on the accepted set
20252        // (the three canonical windows). Locks the migration from the
20253        // free helper onto the substrate primitive: a future re-routing
20254        // of one of the two paths through a differently-computed unit
20255        // projection would silently split the codec's accepted set from
20256        // the validate gate's accepted set — a two-consumer drift the
20257        // codec-round-trip pin
20258        // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
20259        // above closes on the render arm and this pin closes on the
20260        // validate arm.
20261        for canonical_window_secs in [1u64, 60, 3600] {
20262            let mut s = three_member_spec();
20263            let rl = RateLimit {
20264                rate: 100,
20265                window: Duration::from_secs(canonical_window_secs),
20266            };
20267            s.politicas.rate_limit = Some(rl);
20268            assert!(
20269                s.validate().is_ok(),
20270                "canonical {canonical_window_secs}s window must pass \
20271                 validate_politicas — the validate gate now reads \
20272                 RateLimit::canonical_unit().is_none() and the accessor \
20273                 returns Some on every canonical arm"
20274            );
20275            assert!(
20276                rl.canonical_unit().is_some(),
20277                "canonical {canonical_window_secs}s window must resolve to \
20278                 Some on RateLimit::canonical_unit — the validate gate reads \
20279                 this accessor directly"
20280            );
20281        }
20282        for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
20283            let mut s = three_member_spec();
20284            let rl = RateLimit {
20285                rate: 100,
20286                window: Duration::from_secs(non_canonical_window_secs),
20287            };
20288            s.politicas.rate_limit = Some(rl);
20289            assert_eq!(
20290                s.validate().unwrap_err(),
20291                AplicacaoError::PolicyRateLimitWindowNotCanonical {
20292                    window: rl.window(),
20293                },
20294                "non-canonical {non_canonical_window_secs}s window must be \
20295                 rejected by validate_politicas — the validate gate now \
20296                 keys off RateLimit::canonical_unit().is_none()"
20297            );
20298            assert!(
20299                rl.canonical_unit().is_none(),
20300                "non-canonical {non_canonical_window_secs}s window must \
20301                 resolve to None on RateLimit::canonical_unit — the two \
20302                 paths (the free helper the validate gate previously read \
20303                 and the substrate primitive the validate gate now reads) \
20304                 must agree on the same rejected set"
20305            );
20306        }
20307        // And the substrate-primitive [`RateLimit::canonical_unit`]
20308        // accessor's accepted-window set matches the codec's parse arm's
20309        // accepted-suffix set on every canonical / non-canonical shape,
20310        // so a future silent drift between the codec's accepted set and
20311        // the validate gate's accepted set is a build error at test time
20312        // (both consumers key off the same closed-set enum's `match self`
20313        // arms). The predecessor free helper `is_canonical_rate_limit_window`
20314        // — a delegate that composed [`RateLimitUnit::from_window`] with
20315        // `.is_some()` — was deleted after this migration; the
20316        // canonical-window set now lives on exactly one typed dispatch
20317        // on the substrate primitive.
20318        for (secs, expected) in [
20319            (1u64, true),
20320            (60, true),
20321            (3600, true),
20322            (2, false),
20323            (30, false),
20324            (86_400, false),
20325        ] {
20326            let window = Duration::from_secs(secs);
20327            let rl = RateLimit { rate: 1, window };
20328            assert_eq!(
20329                rl.canonical_unit().is_some(),
20330                expected,
20331                "RateLimit::canonical_unit().is_some() must agree with the \
20332                 codec-accepted canonical-window set on {secs}s"
20333            );
20334            let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
20335                1 => "s",
20336                60 => "m",
20337                3600 => "h",
20338                _ => return,
20339            })
20340            .is_some_and(|d| d == window);
20341            if expected {
20342                assert!(
20343                    suffix_from_axis,
20344                    "the codec's `&str → Duration` axis \
20345                     ({secs}s) must round-trip to the same Duration the \
20346                     substrate primitive's accessor returns Some on"
20347                );
20348            }
20349        }
20350    }
20351
20352    #[test]
20353    fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
20354        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
20355        // derive: for each of the three variants, exactly one of the
20356        // generated `is_second` / `is_minute` / `is_hour` predicates
20357        // returns `true` and the other two return `false`. Peer of
20358        // the sibling
20359        // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
20360        // sibling `IsVariant`-derived closed-set typed-enum pins.
20361        let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
20362            (super::RateLimitUnit::Second, [true, false, false]),
20363            (super::RateLimitUnit::Minute, [false, true, false]),
20364            (super::RateLimitUnit::Hour, [false, false, true]),
20365        ];
20366        for (variant, expected) in rows {
20367            let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
20368            assert_eq!(
20369                observed, expected,
20370                "RateLimitUnit::{variant:?} is_* predicates must partition \
20371                 the arm set (second, minute, hour); got {observed:?}"
20372            );
20373        }
20374    }
20375
20376    #[test]
20377    fn rejects_policy_timeout_sub_millisecond() {
20378        // A purely sub-millisecond `Duration` (`from_micros(500)` =
20379        // 500_000 ns) is not the zero `Duration` — the `is_zero()`
20380        // arm passes — but `as_millis() == 0`, so the shared codec's
20381        // `render` arm returns the literal `"0s"`, which the
20382        // codec's `parse` arm then deserializes as `Duration::ZERO`
20383        // and the `PolicyTimeoutZero` zero-floor gate would reject
20384        // on re-validate. Pin the rejection at the typed slot's
20385        // canonical-floor gate so the round-trip break surfaces at
20386        // validate time, naming the offending `Duration`, rather
20387        // than at the next serialize → deserialize round-trip far
20388        // from the source `caixa.lisp`.
20389        let mut s = three_member_spec();
20390        let timeout = Duration::from_micros(500);
20391        s.politicas.timeout = Some(timeout);
20392        assert_eq!(
20393            s.validate().unwrap_err(),
20394            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
20395        );
20396    }
20397
20398    #[test]
20399    fn rejects_policy_timeout_non_integer_millisecond() {
20400        // A `Duration` with non-integer-millisecond residue
20401        // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
20402        // through the shared codec's `render` arm as `"1ms"` (the
20403        // `as_millis()` floor truncates), which the codec's `parse`
20404        // arm then deserializes as `Duration::from_millis(1)` =
20405        // 1_000_000 ns — silently *different* from the original.
20406        // Pin the rejection so this round-trip break surfaces at
20407        // validate time, where the offending `Duration` is named,
20408        // rather than as a silent value-laundered round-trip on the
20409        // next codec round-trip.
20410        let mut s = three_member_spec();
20411        let timeout = Duration::from_micros(1500);
20412        s.politicas.timeout = Some(timeout);
20413        assert_eq!(
20414            s.validate().unwrap_err(),
20415            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
20416        );
20417    }
20418
20419    #[test]
20420    fn accepts_policy_timeout_integer_millisecond_forms() {
20421        // The codec's accepted set — integer multiples of 1ms — is
20422        // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
20423        // `1h` all pass the canonical gate. Pin the canonical-forms
20424        // sweep so a future tightening of the codec's grammar (e.g.
20425        // dropping `:ms`) surfaces here as a test failure rather
20426        // than a silent contract narrowing on the typed slot.
20427        for timeout in [
20428            Duration::from_millis(1),
20429            Duration::from_millis(500),
20430            Duration::from_millis(1500),
20431            Duration::from_secs(30),
20432            Duration::from_secs(120),
20433            Duration::from_secs(3600),
20434        ] {
20435            let mut s = three_member_spec();
20436            s.politicas.timeout = Some(timeout);
20437            s.validate()
20438                .expect("integer-millisecond :timeout must validate");
20439        }
20440    }
20441
20442    #[test]
20443    fn policy_timeout_zero_takes_precedence_over_canonical() {
20444        // `Duration::ZERO` carries `subsec_nanos() == 0` and would
20445        // pass the canonical-millisecond gate; the more self-locating
20446        // `PolicyTimeoutZero` arm (which names the omit-axis
20447        // remediation directly) must fire first. Pin the ordering so
20448        // a future refactor that reorders the arms surfaces here as a
20449        // test failure rather than a silent diagnostic regression.
20450        let mut s = three_member_spec();
20451        s.politicas.timeout = Some(Duration::ZERO);
20452        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
20453    }
20454
20455    #[test]
20456    fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
20457        // The diagnostic envelope carries the offending `Duration`
20458        // verbatim so the author can grep their `caixa.lisp` for
20459        // `:timeout "<value>"` and fix it in one edit. Same
20460        // diagnostic shape every other typed-slot canonical-form
20461        // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
20462        // peer `:rate-limit :window` axis.
20463        let mut s = three_member_spec();
20464        let timeout = Duration::from_nanos(1_000_001);
20465        s.politicas.timeout = Some(timeout);
20466        match s.validate().unwrap_err() {
20467            AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
20468                assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
20469            }
20470            other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
20471        }
20472    }
20473
20474    #[test]
20475    fn rejects_policy_timeout_above_cap() {
20476        // The fail-before-pass-after pin: 3601s = 1h + 1s is
20477        // structurally one canonical-tick past the
20478        // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
20479        // integer-millisecond magnitude the canonical-form arm above
20480        // accepts cleanly, that the codec round-trips losslessly as
20481        // `"3601s"`, and that silently passed validate on every
20482        // pre-gate codebase because the typed slot's only checks were
20483        // the zero-floor and canonical-form arms. The mesh-level
20484        // deadline degenerates only at the runtime substrate (Envoy
20485        // / Cilium L7 timeout overlay) far from the source
20486        // `caixa.lisp` with no field naming the offending policy.
20487        let mut s = three_member_spec();
20488        let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
20489        s.politicas.timeout = Some(timeout);
20490        assert_eq!(
20491            s.validate().unwrap_err(),
20492            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
20493        );
20494    }
20495
20496    #[test]
20497    fn rejects_policy_timeout_one_millisecond_above_cap() {
20498        // Boundary case: exactly 1ms past the cap (the granularity
20499        // the canonical-form gate enforces). Catches a future
20500        // "strictly less than" half-measure and pins the diagnostic
20501        // to name the offending `Duration` verbatim. Peer of
20502        // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
20503        // boundary pin on the sibling `:limits :memory` top edge.
20504        let mut s = three_member_spec();
20505        let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
20506        s.politicas.timeout = Some(timeout);
20507        assert_eq!(
20508            s.validate().unwrap_err(),
20509            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
20510        );
20511    }
20512
20513    #[test]
20514    fn rejects_policy_timeout_far_above_cap() {
20515        // The "obvious authoring footgun" case: a `(:timeout "24h")`
20516        // or `(:timeout "86400s")` — values the canonical-form arm
20517        // accepts as integer-millisecond magnitudes, the codec
20518        // round-trips losslessly through serde, but the mesh-level
20519        // policy cannot honor (a 24-hour synchronous-`:contratos`
20520        // deadline is operationally indistinguishable from
20521        // omit-the-axis). Until this gate landed validate accepted
20522        // it. Pin both common above-cap values (24h, 7d) so a future
20523        // relaxation that drops the upper bound surfaces here.
20524        for timeout in [
20525            Duration::from_secs(86_400),    // 24h
20526            Duration::from_secs(604_800),   // 7d
20527            Duration::from_secs(1_000_000), // ~11.5 days
20528        ] {
20529            let mut s = three_member_spec();
20530            s.politicas.timeout = Some(timeout);
20531            assert_eq!(
20532                s.validate().unwrap_err(),
20533                AplicacaoError::PolicyTimeoutExceedsCap { timeout }
20534            );
20535        }
20536    }
20537
20538    #[test]
20539    fn accepts_policy_timeout_at_cap() {
20540        // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
20541        // must validate. The cap is inclusive on the top edge,
20542        // matching the [`POLICY_RETRIES_MAX`] /
20543        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
20544        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
20545        // sibling capped axes. Pin the boundary explicitly so a
20546        // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
20547        // instead of `>`) surfaces here as a test failure rather
20548        // than a silent contract narrowing.
20549        let mut s = three_member_spec();
20550        s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
20551        s.validate()
20552            .expect("timeout == POLICY_TIMEOUT_MAX must validate");
20553    }
20554
20555    #[test]
20556    fn accepts_policy_timeout_typical_values() {
20557        // The documented production-playbook band positive-control
20558        // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
20559        // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
20560        // plus a sweep through the long-running-workflow band
20561        // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
20562        // validated set explicitly so a future tightening of the
20563        // ceiling surfaces here as a deliberate test edit, not a
20564        // silent contract narrowing.
20565        for timeout in [
20566            Duration::from_millis(1),
20567            Duration::from_millis(500),
20568            Duration::from_secs(1),
20569            Duration::from_secs(10),
20570            Duration::from_secs(15), // Envoy default
20571            Duration::from_secs(30),
20572            Duration::from_secs(60), // AWS App Mesh typical
20573            Duration::from_secs(300),
20574            Duration::from_secs(900),
20575            Duration::from_secs(1800),
20576            Duration::from_secs(3600), // exactly 1h, the cap
20577        ] {
20578            let mut s = three_member_spec();
20579            s.politicas.timeout = Some(timeout);
20580            s.validate()
20581                .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
20582        }
20583    }
20584
20585    #[test]
20586    fn policy_timeout_zero_takes_precedence_over_cap() {
20587        // The cross-arm ordering pin: `Duration::ZERO` is
20588        // structurally outside both `>= 1ms` (zero-floor) and
20589        // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
20590        // diagnostic is the more self-locating one (it directly
20591        // names the omit-axis remediation), so the validate gate
20592        // must fire on zero first. Same shape every other
20593        // zero-then-shape ordering on this surface uses
20594        // ([`AplicacaoError::PolicyRetriesZero`] then
20595        // [`AplicacaoError::PolicyRetriesExceedsCap`];
20596        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
20597        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
20598        let mut s = three_member_spec();
20599        s.politicas.timeout = Some(Duration::ZERO);
20600        assert_eq!(
20601            s.validate().unwrap_err(),
20602            AplicacaoError::PolicyTimeoutZero,
20603            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
20604        );
20605    }
20606
20607    #[test]
20608    fn policy_timeout_canonical_takes_precedence_over_cap() {
20609        // The cross-arm ordering pin: a `Duration` that is *both*
20610        // sub-millisecond (non-canonical-form) and structurally
20611        // above the cap surfaces the canonical-form diagnostic
20612        // first, because the round-trip-shape break is the more
20613        // fundamental issue (the value can't even round-trip
20614        // through the codec, so the cap diagnostic naming
20615        // `1ms..=1h` would be misleading — there's no integer-ms
20616        // form of the offending value). Pin the order so a future
20617        // refactor that reorders the arms surfaces here as a test
20618        // failure rather than a silent diagnostic regression.
20619        let mut s = three_member_spec();
20620        // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
20621        // *and* total magnitude above the 1h cap.
20622        let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
20623        s.politicas.timeout = Some(timeout);
20624        assert_eq!(
20625            s.validate().unwrap_err(),
20626            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
20627            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
20628        );
20629    }
20630
20631    #[test]
20632    fn policy_timeout_cap_diagnostic_carries_offending_value() {
20633        // The diagnostic-shape pin: the offending `Duration` is
20634        // carried verbatim into the
20635        // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
20636        // surfaced error message names the value the author wrote
20637        // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
20638        // exceeds the mesh-policy ceiling …"`), not just the cap.
20639        // Same self-locating diagnostic shape every other typed-cap
20640        // arm on this surface carries
20641        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
20642        // offending retry count verbatim).
20643        let mut s = three_member_spec();
20644        let timeout = Duration::from_secs(7200); // 2h
20645        s.politicas.timeout = Some(timeout);
20646        let err = s.validate().unwrap_err();
20647        assert!(
20648            matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
20649            "got {err:?}"
20650        );
20651        let msg = err.to_string();
20652        assert!(
20653            msg.contains("7200"),
20654            ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
20655        );
20656    }
20657
20658    #[test]
20659    fn policy_timeout_cap_pins_canonical_value() {
20660        // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
20661        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
20662        // the shared duration codec emits as a clean canonical
20663        // string (`"<n>h"`). Pinning the literal value here surfaces
20664        // a future drift (a relaxation to 24h, a tightening to 5m)
20665        // as a deliberate test edit, not a silent contract
20666        // narrowing. Same shape every other typed-cap value pin on
20667        // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
20668        assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
20669        assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
20670    }
20671
20672    #[test]
20673    fn policy_timeout_cap_value_round_trips_through_codec() {
20674        // The codec round-trip property the cap arm preserves: the
20675        // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
20676        // the shared duration codec — every value at the cap renders
20677        // to a clean canonical string (`"1h"`) and parses back to
20678        // the same `Duration`. Pin this so a future drift between
20679        // the cap constant and the codec's largest emitted unit
20680        // surfaces here. Same shape every other typed boundary pin
20681        // on this surface uses
20682        // (`wasm32_memory_cap_matches_parsed_4_gib`).
20683        let policy = MeshPolicy {
20684            timeout: Some(POLICY_TIMEOUT_MAX),
20685            ..Default::default()
20686        };
20687        let json = serde_json::to_string(&policy).unwrap();
20688        // The codec emits `"1h"` for the canonical 1-hour magnitude.
20689        assert!(
20690            json.contains("\"1h\""),
20691            "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
20692        );
20693        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
20694        assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
20695    }
20696
20697    #[test]
20698    fn rejects_circuit_breaker_window_sub_millisecond() {
20699        // Peer of the `:timeout` sub-millisecond arm on the second
20700        // typed-`Duration` `:politicas` axis: a purely sub-ms
20701        // `Duration` (`from_micros(500)`) renders through the shared
20702        // codec as `"0s"`, which the codec parses back to
20703        // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
20704        // zero-floor gate then rejects on re-validate.
20705        let mut s = three_member_spec();
20706        let window = Duration::from_micros(500);
20707        s.politicas.circuit_breaker = Some(CircuitBreaker {
20708            max_failures: 5,
20709            window,
20710        });
20711        assert_eq!(
20712            s.validate().unwrap_err(),
20713            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
20714        );
20715    }
20716
20717    #[test]
20718    fn rejects_circuit_breaker_window_non_integer_millisecond() {
20719        // Peer of the `:timeout` non-integer-ms arm: a `Duration`
20720        // with non-integer-millisecond residue renders through the
20721        // shared codec as the truncated `"<n>ms"` form, parsing back
20722        // to a *different* `Duration` on the next round-trip.
20723        let mut s = three_member_spec();
20724        let window = Duration::from_micros(1500);
20725        s.politicas.circuit_breaker = Some(CircuitBreaker {
20726            max_failures: 5,
20727            window,
20728        });
20729        assert_eq!(
20730            s.validate().unwrap_err(),
20731            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
20732        );
20733    }
20734
20735    #[test]
20736    fn accepts_circuit_breaker_window_integer_millisecond_forms() {
20737        // The canonical-forms sweep on the breaker axis: every
20738        // integer-ms multiple the codec round-trips losslessly
20739        // passes the canonical gate.
20740        //
20741        // Clears `:timeout` from the fixture so this per-axis sweep
20742        // covers windows shorter than the fixture's 30s timeout
20743        // (1ms, 500ms, 1500ms) — the sub-timeout arm is a
20744        // structurally-inert breaker
20745        // ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]) that
20746        // the cross-axis gate at the end of
20747        // [`AplicacaoSpec::validate_politicas`] rejects on the paired
20748        // `(:timeout, :window)` shape, not on the per-axis
20749        // integer-millisecond canonical-form shape this test pins.
20750        // The paired shape is covered by
20751        // `rejects_circuit_breaker_window_below_timeout`.
20752        for window in [
20753            Duration::from_millis(1),
20754            Duration::from_millis(500),
20755            Duration::from_millis(1500),
20756            Duration::from_secs(30),
20757            Duration::from_secs(60),
20758            Duration::from_secs(3600),
20759        ] {
20760            let mut s = three_member_spec();
20761            s.politicas.timeout = None;
20762            s.politicas.circuit_breaker = Some(CircuitBreaker {
20763                max_failures: 5,
20764                window,
20765            });
20766            s.validate()
20767                .expect("integer-millisecond :circuit-breaker :window must validate");
20768        }
20769    }
20770
20771    #[test]
20772    fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
20773        // `Duration::ZERO` would pass the canonical-ms gate (the
20774        // sub-ns residue is zero) but must surface the narrower
20775        // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
20776        // remediation.
20777        let mut s = three_member_spec();
20778        s.politicas.circuit_breaker = Some(CircuitBreaker {
20779            max_failures: 5,
20780            window: Duration::ZERO,
20781        });
20782        assert_eq!(
20783            s.validate().unwrap_err(),
20784            AplicacaoError::PolicyBreakerZeroWindow
20785        );
20786    }
20787
20788    #[test]
20789    fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
20790        // Both axes invalid: max_failures == 0 *and* window is
20791        // sub-ms. The validate gate must fire on max_failures first
20792        // (matching the existing ordering pin
20793        // `rejects_circuit_breaker_zero_max_failures` enshrines), so
20794        // the existing diagnostic continues to lead with the simpler
20795        // "zero threshold" framing.
20796        let mut s = three_member_spec();
20797        s.politicas.circuit_breaker = Some(CircuitBreaker {
20798            max_failures: 0,
20799            window: Duration::from_micros(500),
20800        });
20801        assert_eq!(
20802            s.validate().unwrap_err(),
20803            AplicacaoError::PolicyBreakerZeroFailures
20804        );
20805    }
20806
20807    #[test]
20808    fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
20809        let mut s = three_member_spec();
20810        let window = Duration::from_nanos(60_000_000_001);
20811        s.politicas.circuit_breaker = Some(CircuitBreaker {
20812            max_failures: 5,
20813            window,
20814        });
20815        match s.validate().unwrap_err() {
20816            AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
20817                assert_eq!(w, window, "diagnostic must carry the offending Duration");
20818            }
20819            other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
20820        }
20821    }
20822
20823    #[test]
20824    fn rejects_circuit_breaker_window_above_cap() {
20825        // The fail-before-pass-after pin: 3601s = 1h + 1s is
20826        // structurally one canonical-tick past the
20827        // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
20828        // integer-millisecond magnitude the canonical-form arm above
20829        // accepts cleanly, that the codec round-trips losslessly as
20830        // `"3601s"`, and that silently passed validate on every
20831        // pre-gate codebase because the typed slot's only checks were
20832        // the zero-floor and canonical-form arms. The
20833        // rolling-window-to-lifetime-counter degeneration surfaces
20834        // only at the runtime substrate (Envoy's outlier_detection
20835        // interval, the future CiliumClusterwideEnvoyConfig overlay)
20836        // far from the source `caixa.lisp` with no field naming the
20837        // offending policy.
20838        let mut s = three_member_spec();
20839        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
20840        s.politicas.circuit_breaker = Some(CircuitBreaker {
20841            max_failures: 5,
20842            window,
20843        });
20844        assert_eq!(
20845            s.validate().unwrap_err(),
20846            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
20847        );
20848    }
20849
20850    #[test]
20851    fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
20852        // Boundary case: exactly 1ms past the cap (the granularity the
20853        // canonical-form gate enforces). Catches a future "strictly
20854        // less than" half-measure and pins the diagnostic to name the
20855        // offending `Duration` verbatim. Peer of
20856        // `rejects_policy_timeout_one_millisecond_above_cap` on the
20857        // sibling duration-typed `:politicas :timeout` top edge.
20858        let mut s = three_member_spec();
20859        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
20860        s.politicas.circuit_breaker = Some(CircuitBreaker {
20861            max_failures: 5,
20862            window,
20863        });
20864        assert_eq!(
20865            s.validate().unwrap_err(),
20866            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
20867        );
20868    }
20869
20870    #[test]
20871    fn rejects_circuit_breaker_window_far_above_cap() {
20872        // The "obvious authoring footgun" case: a `(:window "24h")` or
20873        // `(:window "86400s")` — values the canonical-form arm
20874        // accepts as integer-millisecond magnitudes, the codec
20875        // round-trips losslessly through serde, but the
20876        // rolling-window breaker contract cannot honor (a 24-hour
20877        // rolling failure window is operationally a lifetime counter).
20878        // Until this gate landed validate accepted it. Pin both common
20879        // above-cap values (24h, 7d) so a future relaxation that
20880        // drops the upper bound surfaces here.
20881        for window in [
20882            Duration::from_secs(86_400),    // 24h
20883            Duration::from_secs(604_800),   // 7d
20884            Duration::from_secs(1_000_000), // ~11.5 days
20885        ] {
20886            let mut s = three_member_spec();
20887            s.politicas.circuit_breaker = Some(CircuitBreaker {
20888                max_failures: 5,
20889                window,
20890            });
20891            assert_eq!(
20892                s.validate().unwrap_err(),
20893                AplicacaoError::PolicyBreakerWindowExceedsCap { window }
20894            );
20895        }
20896    }
20897
20898    #[test]
20899    fn accepts_circuit_breaker_window_at_cap() {
20900        // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
20901        // (1h) — must validate. The cap is inclusive on the top edge,
20902        // matching the [`POLICY_TIMEOUT_MAX`] /
20903        // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
20904        // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
20905        // sibling capped axes. Pin the boundary explicitly so a
20906        // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
20907        // instead of `>`) surfaces here as a test failure rather than
20908        // a silent contract narrowing.
20909        let mut s = three_member_spec();
20910        s.politicas.circuit_breaker = Some(CircuitBreaker {
20911            max_failures: 5,
20912            window: POLICY_BREAKER_WINDOW_MAX,
20913        });
20914        s.validate()
20915            .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
20916    }
20917
20918    #[test]
20919    fn accepts_circuit_breaker_window_typical_values() {
20920        // The documented production-playbook band positive-control
20921        // sweep — every value Hystrix / resilience4j / Istio / Envoy
20922        // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
20923        // through the long-tail failure-detection band (15m, 30m, 1h)
20924        // the cap accepts. Pin the inclusive validated set explicitly
20925        // so a future tightening of the ceiling surfaces here as a
20926        // deliberate test edit, not a silent contract narrowing.
20927        //
20928        // Clears `:timeout` from the fixture so this per-axis sweep
20929        // covers windows shorter than the fixture's 30s timeout
20930        // (Hystrix's 10s default, resilience4j's 30s, and the
20931        // sub-second warm-up band) — every such value is a
20932        // structurally-inert breaker under the cross-axis gate at the
20933        // end of [`AplicacaoSpec::validate_politicas`]
20934        // ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]), and
20935        // the paired `(:timeout, :window)` shape is covered by
20936        // `rejects_circuit_breaker_window_below_timeout`; this
20937        // per-axis pin ranges only over the per-axis-bracket accept set.
20938        for window in [
20939            Duration::from_millis(1),
20940            Duration::from_millis(500),
20941            Duration::from_secs(1),
20942            Duration::from_secs(10), // Hystrix / Istio / Envoy default
20943            Duration::from_secs(30),
20944            Duration::from_secs(60),  // resilience4j typical
20945            Duration::from_secs(300), // AWS App Mesh typical
20946            Duration::from_secs(900),
20947            Duration::from_secs(1800),
20948            Duration::from_secs(3600), // exactly 1h, the cap
20949        ] {
20950            let mut s = three_member_spec();
20951            s.politicas.timeout = None;
20952            s.politicas.circuit_breaker = Some(CircuitBreaker {
20953                max_failures: 5,
20954                window,
20955            });
20956            s.validate()
20957                .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
20958        }
20959    }
20960
20961    #[test]
20962    fn circuit_breaker_zero_window_takes_precedence_over_cap() {
20963        // The cross-arm ordering pin: `Duration::ZERO` is structurally
20964        // outside both `>= 1ms` (zero-floor) and
20965        // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
20966        // diagnostic is the more self-locating one (it directly names
20967        // the omit-axis remediation), so the validate gate must fire
20968        // on zero first. Same shape every other zero-then-cap
20969        // ordering on this surface uses
20970        // ([`AplicacaoError::PolicyTimeoutZero`] then
20971        // [`AplicacaoError::PolicyTimeoutExceedsCap`];
20972        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
20973        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
20974        let mut s = three_member_spec();
20975        s.politicas.circuit_breaker = Some(CircuitBreaker {
20976            max_failures: 5,
20977            window: Duration::ZERO,
20978        });
20979        assert_eq!(
20980            s.validate().unwrap_err(),
20981            AplicacaoError::PolicyBreakerZeroWindow,
20982            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
20983        );
20984    }
20985
20986    #[test]
20987    fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
20988        // The cross-arm ordering pin: a `Duration` that is *both*
20989        // sub-millisecond (non-canonical-form) and structurally above
20990        // the cap surfaces the canonical-form diagnostic first,
20991        // because the round-trip-shape break is the more fundamental
20992        // issue (the value can't even round-trip through the codec, so
20993        // the cap diagnostic naming `1ms..=1h` would be misleading —
20994        // there's no integer-ms form of the offending value). Pin the
20995        // order so a future refactor that reorders the arms surfaces
20996        // here as a test failure rather than a silent diagnostic
20997        // regression. Peer of
20998        // `policy_timeout_canonical_takes_precedence_over_cap` on the
20999        // sibling duration-typed `:politicas :timeout` axis.
21000        let mut s = three_member_spec();
21001        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
21002        s.politicas.circuit_breaker = Some(CircuitBreaker {
21003            max_failures: 5,
21004            window,
21005        });
21006        assert_eq!(
21007            s.validate().unwrap_err(),
21008            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
21009            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
21010        );
21011    }
21012
21013    #[test]
21014    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
21015        // The cross-arm ordering pin between the two breaker axes: a
21016        // `CircuitBreaker` whose *both* `max_failures` is above its
21017        // cap *and* `window` is above its cap surfaces the
21018        // max-failures cap diagnostic first, because the validate
21019        // gate visits the failures arm before the window arm. Pin the
21020        // order so a future refactor that reorders the breaker arms
21021        // surfaces here.
21022        let mut s = three_member_spec();
21023        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
21024        s.politicas.circuit_breaker = Some(CircuitBreaker {
21025            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
21026            window,
21027        });
21028        assert_eq!(
21029            s.validate().unwrap_err(),
21030            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
21031                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
21032            },
21033            "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
21034        );
21035    }
21036
21037    #[test]
21038    fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
21039        // The diagnostic-shape pin: the offending `Duration` is
21040        // carried verbatim into the
21041        // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
21042        // the surfaced error message names the value the author wrote
21043        // (`":politicas :circuit-breaker :window (Duration { secs:
21044        // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
21045        // just the cap. Same self-locating diagnostic shape every
21046        // other typed-cap arm on this surface carries
21047        // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
21048        // offending `Duration` verbatim).
21049        let mut s = three_member_spec();
21050        let window = Duration::from_secs(7200); // 2h
21051        s.politicas.circuit_breaker = Some(CircuitBreaker {
21052            max_failures: 5,
21053            window,
21054        });
21055        let err = s.validate().unwrap_err();
21056        assert!(
21057            matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
21058            "got {err:?}"
21059        );
21060        let msg = err.to_string();
21061        assert!(
21062            msg.contains("7200"),
21063            ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
21064        );
21065    }
21066
21067    #[test]
21068    fn circuit_breaker_window_cap_pins_canonical_value() {
21069        // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
21070        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
21071        // shared duration codec emits as a clean canonical string
21072        // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
21073        // the sibling duration-typed `:politicas :timeout` axis (the
21074        // two duration-typed `:politicas` axes share a uniform top
21075        // edge). Pinning the literal value here surfaces a future
21076        // drift (a relaxation to 24h, a tightening to 5m) as a
21077        // deliberate test edit, not a silent contract narrowing. Same
21078        // shape every other typed-cap value pin on this surface uses
21079        // (`policy_timeout_cap_pins_canonical_value`).
21080        assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
21081        assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
21082        assert_eq!(
21083            POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
21084            "the two duration-typed `:politicas` caps share the same top edge"
21085        );
21086    }
21087
21088    #[test]
21089    fn circuit_breaker_window_cap_value_round_trips_through_codec() {
21090        // The codec round-trip property the cap arm preserves: the
21091        // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
21092        // through the shared duration codec — every value at the cap
21093        // renders to a clean canonical string (`"1h"`) and parses back
21094        // to the same `Duration`. Pin this so a future drift between
21095        // the cap constant and the codec's largest emitted unit
21096        // surfaces here. Same shape every other typed boundary pin on
21097        // this surface uses
21098        // (`policy_timeout_cap_value_round_trips_through_codec`).
21099        let policy = MeshPolicy {
21100            circuit_breaker: Some(CircuitBreaker {
21101                max_failures: 5,
21102                window: POLICY_BREAKER_WINDOW_MAX,
21103            }),
21104            ..Default::default()
21105        };
21106        let json = serde_json::to_string(&policy).unwrap();
21107        // The codec emits `"1h"` for the canonical 1-hour magnitude.
21108        assert!(
21109            json.contains("\"1h\""),
21110            "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
21111        );
21112        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
21113        assert_eq!(
21114            back.circuit_breaker.unwrap().window,
21115            POLICY_BREAKER_WINDOW_MAX
21116        );
21117    }
21118
21119    #[test]
21120    fn is_integer_millisecond_duration_predicate_tracks_codec() {
21121        // Pin the predicate's accepted set against the codec's
21122        // accepted set explicitly. The codec parses
21123        // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
21124        // accepted value is an integer-millisecond multiple — so the
21125        // predicate must accept exactly that set. Same shape every
21126        // other predicate-on-the-typed-slot helper carries
21127        // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
21128        // Read directly from the codec-owned predicate — the crate's
21129        // single source of truth every typed-`Duration` axis now routes
21130        // through via
21131        // [`crate::render::require_positive_canonical_bounded_duration`].
21132        use super::supervisor::duration_codec::is_integer_millisecond_duration;
21133        assert!(is_integer_millisecond_duration(Duration::ZERO));
21134        assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
21135        assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
21136        assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
21137        assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
21138        assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
21139        // Non-integer-millisecond residue: rejected.
21140        assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
21141        assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
21142        assert!(!is_integer_millisecond_duration(Duration::from_micros(
21143            1500
21144        )));
21145        assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
21146        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
21147            999_999
21148        )));
21149        // The 1-ns-past-1ms boundary: rejected (no longer a clean
21150        // integer-millisecond multiple).
21151        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
21152            1_000_001
21153        )));
21154    }
21155
21156    #[test]
21157    fn policy_timeout_validated_value_round_trips_through_codec() {
21158        // The structural property the canonical-ms gate enforces:
21159        // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
21160        // round-trips losslessly through the shared `duration_codec`
21161        // (serialize → string → deserialize → equal value). Pin this
21162        // end-to-end so a future change to either side (the validate
21163        // gate's accepted granularity, the codec's parse/render unit
21164        // set) that breaks the alignment surfaces here. The
21165        // previous-state shape (typed slot accepts arbitrary
21166        // `Duration`, codec only round-trips integer-ms) would fail
21167        // this test for any `Duration::from_micros(1500)` timeout —
21168        // the validate gate now forecloses that.
21169        for timeout in [
21170            Duration::from_millis(1),
21171            Duration::from_millis(1500),
21172            Duration::from_secs(30),
21173            Duration::from_secs(3600),
21174        ] {
21175            let mut s = three_member_spec();
21176            s.politicas.timeout = Some(timeout);
21177            s.validate().unwrap();
21178            let json = serde_json::to_string(&s.politicas).unwrap();
21179            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
21180            assert_eq!(
21181                back.timeout, s.politicas.timeout,
21182                "every validated :timeout must round-trip losslessly through the codec"
21183            );
21184        }
21185    }
21186
21187    #[test]
21188    fn circuit_breaker_window_validated_value_round_trips_through_codec() {
21189        // Peer of the `:timeout` round-trip property on the breaker
21190        // axis.
21191        //
21192        // Clears `:timeout` from the fixture so the round-trip pin
21193        // ranges over sub-timeout `Duration` values (1ms, 1500ms) the
21194        // cross-axis gate would otherwise reject as structurally-inert
21195        // breakers ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]);
21196        // the paired `(:timeout, :window)` cross-axis relation is
21197        // pinned separately by
21198        // `rejects_circuit_breaker_window_below_timeout`, and this
21199        // property is a pure serde-codec round-trip on the per-axis
21200        // slot.
21201        for window in [
21202            Duration::from_millis(1),
21203            Duration::from_millis(1500),
21204            Duration::from_secs(30),
21205            Duration::from_secs(3600),
21206        ] {
21207            let mut s = three_member_spec();
21208            s.politicas.timeout = None;
21209            s.politicas.circuit_breaker = Some(CircuitBreaker {
21210                max_failures: 5,
21211                window,
21212            });
21213            s.validate().unwrap();
21214            let json = serde_json::to_string(&s.politicas).unwrap();
21215            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
21216            assert_eq!(
21217                back.circuit_breaker.unwrap().window,
21218                window,
21219                "every validated :circuit-breaker :window must round-trip losslessly"
21220            );
21221        }
21222    }
21223
21224    #[test]
21225    fn rejects_circuit_breaker_window_below_timeout() {
21226        // The fail-before-pass-after pin on the cross-axis
21227        // `(:timeout, :circuit-breaker :window)` invariant. Each axis
21228        // is individually well-formed under its own per-axis bracket
21229        // (both integer-millisecond, both above the zero floor, both
21230        // below the cap), but the pair is a structurally-inert
21231        // breaker: a call dispatched at t=0 is declared failed at
21232        // t=30s, by which point the 10s rolling window open at
21233        // dispatch has already rolled twice, so no window can hold
21234        // a timeout-derived failure however high the call volume.
21235        //
21236        // Envoy's `outlier_detection.interval` against the per-route
21237        // request timeout carries the identical relation; Hystrix
21238        // ships the canonical ratio in its defaults (10s window
21239        // against a 1s timeout — a 10× ratio, not a 3× under-ratio).
21240        //
21241        // Pin both the diagnostic arm and the payload values so a
21242        // future re-shape of the arm surfaces here as a deliberate
21243        // test edit.
21244        let mut s = three_member_spec();
21245        s.politicas.timeout = Some(Duration::from_secs(30));
21246        s.politicas.circuit_breaker = Some(CircuitBreaker {
21247            max_failures: 5,
21248            window: Duration::from_secs(10),
21249        });
21250        assert_eq!(
21251            s.validate().unwrap_err(),
21252            AplicacaoError::PolicyBreakerWindowBelowTimeout {
21253                window: Duration::from_secs(10),
21254                timeout: Duration::from_secs(30),
21255            }
21256        );
21257    }
21258
21259    #[test]
21260    fn accepts_circuit_breaker_window_equal_to_timeout() {
21261        // Boundary pin: `:window == :timeout` is the smallest window
21262        // that structurally admits at least one full timeout-derived
21263        // failure before the rolling interval closes (the invariant
21264        // is `:window >= :timeout`, not strict inequality). Catches
21265        // a future off-by-one tightening that would drift the accept
21266        // set away from the codified [`MeshPolicy::breaker_window_
21267        // observes_timeout`] predicate.
21268        let mut s = three_member_spec();
21269        s.politicas.timeout = Some(Duration::from_secs(30));
21270        s.politicas.circuit_breaker = Some(CircuitBreaker {
21271            max_failures: 5,
21272            window: Duration::from_secs(30),
21273        });
21274        s.validate()
21275            .expect("window == timeout is the boundary accept case");
21276    }
21277
21278    #[test]
21279    fn accepts_circuit_breaker_window_above_timeout() {
21280        // Positive-control sweep across the production-playbook band —
21281        // Hystrix (1s timeout / 10s window, 10× ratio), Istio (5s /
21282        // 30s, 6×), Envoy (10s / 60s, 6×), resilience4j (30s / 300s,
21283        // 10×), AWS App Mesh (60s / 300s, 5×). Every pair a real
21284        // playbook recommends must validate under the cross-axis gate.
21285        for (timeout, window) in [
21286            (Duration::from_secs(1), Duration::from_secs(10)),
21287            (Duration::from_secs(5), Duration::from_secs(30)),
21288            (Duration::from_secs(10), Duration::from_secs(60)),
21289            (Duration::from_secs(30), Duration::from_secs(300)),
21290            (Duration::from_secs(60), Duration::from_secs(300)),
21291        ] {
21292            let mut s = three_member_spec();
21293            s.politicas.timeout = Some(timeout);
21294            s.politicas.circuit_breaker = Some(CircuitBreaker {
21295                max_failures: 5,
21296                window,
21297            });
21298            s.validate().unwrap_or_else(|e| {
21299                panic!(
21300                    "production-playbook pair timeout={timeout:?}/window={window:?} must \
21301                     validate; got {e:?}"
21302                )
21303            });
21304        }
21305    }
21306
21307    #[test]
21308    fn circuit_breaker_window_below_timeout_by_one_millisecond_rejected() {
21309        // Off-by-one boundary pin: a window exactly 1ms shy of the
21310        // timeout is still structurally inert under the invariant
21311        // (the dispatch-to-report lag is `timeout`, so the window
21312        // must span at least one such lag). Catches a future
21313        // strict-inequality relaxation that would silently drift
21314        // the accept boundary.
21315        let timeout = Duration::from_secs(30);
21316        let window = Duration::from_millis(29_999);
21317        let mut s = three_member_spec();
21318        s.politicas.timeout = Some(timeout);
21319        s.politicas.circuit_breaker = Some(CircuitBreaker {
21320            max_failures: 5,
21321            window,
21322        });
21323        assert_eq!(
21324            s.validate().unwrap_err(),
21325            AplicacaoError::PolicyBreakerWindowBelowTimeout { window, timeout }
21326        );
21327    }
21328
21329    #[test]
21330    fn cross_axis_gate_vacuous_when_timeout_absent() {
21331        // The predicate is vacuously `true` when `:timeout` is None —
21332        // a `:circuit-breaker` alone declares no relation to a
21333        // substrate-imposed deadline (the failure signal reaches the
21334        // breaker from the transport's own error surface, so no
21335        // dispatch-to-report lag is knowable at author time). Pin so
21336        // a future tightening that made the gate opinionated on
21337        // half-declared pairs surfaces here.
21338        let mut s = three_member_spec();
21339        s.politicas.timeout = None;
21340        s.politicas.circuit_breaker = Some(CircuitBreaker {
21341            max_failures: 5,
21342            window: Duration::from_millis(1),
21343        });
21344        s.validate().expect(
21345            "cross-axis gate must be vacuous when :timeout is None, however small :window is",
21346        );
21347    }
21348
21349    #[test]
21350    fn cross_axis_gate_vacuous_when_circuit_breaker_absent() {
21351        // Peer of the sibling `:timeout`-absent case: a `:timeout`
21352        // without a `:circuit-breaker` declares a per-call deadline
21353        // without any rolling-window failure accounting, so the pair
21354        // is undeclared and the cross-axis gate has nothing to check.
21355        let mut s = three_member_spec();
21356        s.politicas.timeout = Some(Duration::from_secs(3600));
21357        s.politicas.circuit_breaker = None;
21358        s.validate().expect(
21359            "cross-axis gate must be vacuous when :circuit-breaker is None, \
21360             however large :timeout is",
21361        );
21362    }
21363
21364    #[test]
21365    fn cross_axis_gate_runs_after_per_axis_brackets() {
21366        // Ordering pin: a pair whose window is *both* zero-floor-
21367        // violating and structurally below the timeout must surface
21368        // the per-axis zero-floor arm first — the zero-floor
21369        // diagnostic is more self-locating (its omit-axis remediation
21370        // is directly named), where the cross-axis arm would send the
21371        // author to reconcile two values one of which is not a
21372        // meaningful window at all. Same ordering discipline every
21373        // per-axis bracket carries internally (zero-floor before
21374        // canonical-form before cap).
21375        let mut s = three_member_spec();
21376        s.politicas.timeout = Some(Duration::from_secs(30));
21377        s.politicas.circuit_breaker = Some(CircuitBreaker {
21378            max_failures: 5,
21379            window: Duration::ZERO,
21380        });
21381        assert_eq!(
21382            s.validate().unwrap_err(),
21383            AplicacaoError::PolicyBreakerZeroWindow,
21384            "per-axis zero-floor arm must fire before the cross-axis gate"
21385        );
21386    }
21387
21388    #[test]
21389    fn breaker_window_observes_timeout_predicate_matches_gate_semantic() {
21390        // Equivalence pin: the substrate-canonical
21391        // [`MeshPolicy::breaker_window_observes_timeout`] predicate
21392        // and the [`AplicacaoSpec::validate_politicas`] cross-axis
21393        // arm must discriminate the same set on every pair covered
21394        // by their shared invariant. A future refactor of either
21395        // side that breaks the equivalence trips here rather than as
21396        // a divergence between the predicate's Boolean answer and
21397        // the validate gate's Ok/Err arm — the same
21398        // predicate-vs-gate coherence discipline the peer
21399        // [`PlacementStrategy::is_shard_keyed`] predicate carries
21400        // against `AplicacaoSpec::validate_placement`. The sweep
21401        // covers both arms of the invariant (below, equal, above)
21402        // and both vacuous arms (None `:timeout`, None
21403        // `:circuit-breaker`), so the equivalence holds
21404        // exhaustively over the axis-covered accept and reject sets.
21405        let cases: &[(Option<Duration>, Option<Duration>)] = &[
21406            (Some(Duration::from_secs(30)), Some(Duration::from_secs(10))),
21407            (Some(Duration::from_secs(30)), Some(Duration::from_secs(29))),
21408            (Some(Duration::from_secs(30)), Some(Duration::from_secs(30))),
21409            (Some(Duration::from_secs(30)), Some(Duration::from_secs(60))),
21410            (Some(Duration::from_secs(1)), Some(Duration::from_secs(10))),
21411            (None, Some(Duration::from_secs(1))),
21412            (Some(Duration::from_secs(30)), None),
21413            (None, None),
21414        ];
21415        for (timeout, window) in cases.iter().copied() {
21416            let politicas = MeshPolicy {
21417                timeout,
21418                circuit_breaker: window.map(|w| CircuitBreaker {
21419                    max_failures: 5,
21420                    window: w,
21421                }),
21422                ..Default::default()
21423            };
21424            let predicate = politicas.breaker_window_observes_timeout();
21425
21426            let mut s = three_member_spec();
21427            s.politicas = politicas.clone();
21428            let gate_ok = !matches!(
21429                s.validate(),
21430                Err(AplicacaoError::PolicyBreakerWindowBelowTimeout { .. })
21431            );
21432
21433            assert_eq!(
21434                predicate, gate_ok,
21435                "predicate must agree with validate arm on pair \
21436                 (timeout={timeout:?}, window={window:?})"
21437            );
21438        }
21439    }
21440
21441    #[test]
21442    fn rejects_rate_limit_starves_circuit_breaker() {
21443        // The fail-before-pass-after pin on the cross-axis
21444        // `(:rate-limit, :circuit-breaker)` invariant. Each axis is
21445        // individually well-formed under its own per-axis bracket
21446        // (both above the zero floor, both below the cap, rate-limit
21447        // window canonical), but the pair is a structurally-inert
21448        // breaker: the token bucket admits `1 × 10s / 3600s` ≈ 0
21449        // calls per rolling breaker window, so no window can
21450        // accumulate five failures however catastrophic the upstream
21451        // failure rate.
21452        //
21453        // Envoy's `outlier_detection.consecutive_5xx` paired against
21454        // `local_rate_limit.token_bucket.max_tokens` /
21455        // `fill_interval` carries the identical relation; every
21456        // production playbook that pairs the two axes (Envoy, Istio,
21457        // AWS App Mesh, Kong) sizes the rate at or above the
21458        // breaker's minimum-request-volume threshold for exactly this
21459        // reason.
21460        //
21461        // Pin both the diagnostic arm and the payload values so a
21462        // future re-shape of the arm surfaces here as a deliberate
21463        // test edit. Clears `:timeout` so the sibling
21464        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] gate
21465        // does not fire first on the ordering-precedent it holds
21466        // over this arm.
21467        let mut s = three_member_spec();
21468        s.politicas.timeout = None;
21469        s.politicas.circuit_breaker = Some(CircuitBreaker {
21470            max_failures: 5,
21471            window: Duration::from_secs(10),
21472        });
21473        s.politicas.rate_limit = Some(RateLimit {
21474            rate: 1,
21475            window: Duration::from_secs(3600),
21476        });
21477        assert_eq!(
21478            s.validate().unwrap_err(),
21479            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
21480                rate: 1,
21481                rl_window: Duration::from_secs(3600),
21482                max_failures: 5,
21483                cb_window: Duration::from_secs(10),
21484            }
21485        );
21486    }
21487
21488    #[test]
21489    fn accepts_rate_limit_can_trip_circuit_breaker() {
21490        // Positive-control sweep across the production-playbook band
21491        // — every pair a real playbook recommends where the rate
21492        // clearly admits enough calls per breaker window to reach
21493        // `:max-failures` must validate. Envoy default 5 failures
21494        // in 10s with 100/s (1000 calls / window, 200× the threshold),
21495        // Istio 5 in 30s with 50/s (1500 calls, 300×), Hystrix 20 in
21496        // 10s with 1000/s (10000 calls, 500×), AWS App Mesh 5 in
21497        // 300s with 10/s (3000 calls, 600×). Clears `:timeout` so
21498        // the sibling cross-axis arm is vacuous on this sweep.
21499        for (rate, rl_window, max_failures, cb_window) in [
21500            (
21501                100u32,
21502                Duration::from_secs(1),
21503                5u32,
21504                Duration::from_secs(10),
21505            ),
21506            (50, Duration::from_secs(1), 5, Duration::from_secs(30)),
21507            (1000, Duration::from_secs(1), 20, Duration::from_secs(10)),
21508            (10, Duration::from_secs(1), 5, Duration::from_secs(300)),
21509            (5000, Duration::from_secs(60), 50, Duration::from_secs(60)),
21510        ] {
21511            let mut s = three_member_spec();
21512            s.politicas.timeout = None;
21513            s.politicas.circuit_breaker = Some(CircuitBreaker {
21514                max_failures,
21515                window: cb_window,
21516            });
21517            s.politicas.rate_limit = Some(RateLimit {
21518                rate,
21519                window: rl_window,
21520            });
21521            s.validate().unwrap_or_else(|e| {
21522                panic!(
21523                    "production-playbook pair rate={rate}/{rl_window:?} \
21524                     max_failures={max_failures}/{cb_window:?} must validate; got {e:?}"
21525                )
21526            });
21527        }
21528    }
21529
21530    #[test]
21531    fn accepts_rate_limit_exactly_at_trip_threshold_per_cb_window() {
21532        // Boundary pin: `rate × cb_window == max_failures × rl_window`
21533        // is the smallest bucket capacity that structurally admits
21534        // exactly `max_failures` calls per rolling breaker window
21535        // (the invariant is `≥`, not strict inequality). Catches a
21536        // future off-by-one tightening to strict inequality that
21537        // would drift the accept set away from the codified
21538        // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicate.
21539        // 5 calls/s over a 1s breaker window == 5 max_failures.
21540        let mut s = three_member_spec();
21541        s.politicas.timeout = None;
21542        s.politicas.circuit_breaker = Some(CircuitBreaker {
21543            max_failures: 5,
21544            window: Duration::from_secs(1),
21545        });
21546        s.politicas.rate_limit = Some(RateLimit {
21547            rate: 5,
21548            window: Duration::from_secs(1),
21549        });
21550        s.validate()
21551            .expect("rate × cb_window == max_failures × rl_window is the boundary accept case");
21552    }
21553
21554    #[test]
21555    fn rejects_rate_limit_one_call_short_per_cb_window() {
21556        // Off-by-one boundary pin: exactly one call short of the trip
21557        // threshold per breaker window is still structurally inert
21558        // (the invariant is `≥`, so `<` refuses even a one-call
21559        // shortfall). 4 calls/s over a 1s window == 4 admissible
21560        // failures, one shy of the 5-`max_failures` threshold.
21561        // Catches a future strict-inequality relaxation that would
21562        // silently drift the accept boundary.
21563        let mut s = three_member_spec();
21564        s.politicas.timeout = None;
21565        s.politicas.circuit_breaker = Some(CircuitBreaker {
21566            max_failures: 5,
21567            window: Duration::from_secs(1),
21568        });
21569        s.politicas.rate_limit = Some(RateLimit {
21570            rate: 4,
21571            window: Duration::from_secs(1),
21572        });
21573        assert_eq!(
21574            s.validate().unwrap_err(),
21575            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
21576                rate: 4,
21577                rl_window: Duration::from_secs(1),
21578                max_failures: 5,
21579                cb_window: Duration::from_secs(1),
21580            }
21581        );
21582    }
21583
21584    #[test]
21585    fn cross_axis_starve_gate_vacuous_when_rate_limit_absent() {
21586        // The predicate is vacuously `true` when `:rate-limit` is
21587        // None — a `:circuit-breaker` alone declares no relation to
21588        // a substrate-imposed call rate (the failure signal reaches
21589        // the breaker from the transport's own error surface, at
21590        // whatever rate upstream callers push traffic). Pin so a
21591        // future tightening that made the gate opinionated on
21592        // half-declared pairs surfaces here.
21593        let mut s = three_member_spec();
21594        s.politicas.timeout = None;
21595        s.politicas.circuit_breaker = Some(CircuitBreaker {
21596            max_failures: 1000,
21597            window: Duration::from_millis(1),
21598        });
21599        s.politicas.rate_limit = None;
21600        s.validate().expect(
21601            "cross-axis starve gate must be vacuous when :rate-limit is None, \
21602             however high :max-failures and however small :window are",
21603        );
21604    }
21605
21606    #[test]
21607    fn cross_axis_starve_gate_vacuous_when_circuit_breaker_absent() {
21608        // Peer of the sibling `:rate-limit`-absent case: a
21609        // `:rate-limit` without a `:circuit-breaker` declares a
21610        // per-edge token-bucket rate without any failure counter to
21611        // starve, so the pair is undeclared and the cross-axis gate
21612        // has nothing to check.
21613        //
21614        // Also clears the fixture's `:retries` (which is `Some(3)`) so
21615        // the sibling cross-axis
21616        // [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] arm
21617        // (which reasons across the paired `(:retries, :rate-limit)`
21618        // pair independent of `:circuit-breaker`) is vacuous on this
21619        // pin — this test names the *starve* arm's vacuity on the
21620        // `:circuit-breaker`-absent case, not the burst arm's.
21621        let mut s = three_member_spec();
21622        s.politicas.timeout = None;
21623        s.politicas.retries = None;
21624        s.politicas.circuit_breaker = None;
21625        s.politicas.rate_limit = Some(RateLimit {
21626            rate: 1,
21627            window: Duration::from_secs(3600),
21628        });
21629        s.validate().expect(
21630            "cross-axis starve gate must be vacuous when :circuit-breaker is None, \
21631             however low :rate is",
21632        );
21633    }
21634
21635    #[test]
21636    fn cross_axis_starve_gate_runs_after_per_axis_brackets() {
21637        // Ordering pin: a pair whose rate is *both* zero-floor-
21638        // violating and structurally below the trip threshold must
21639        // surface the per-axis zero-floor arm first — the zero-floor
21640        // diagnostic is more self-locating (its omit-axis remediation
21641        // is directly named), where the cross-axis arm would send the
21642        // author to reconcile four values one of which is not a
21643        // meaningful rate at all. Same ordering discipline every
21644        // per-axis bracket carries internally (zero-floor before
21645        // canonical-form before cap), and the sibling cross-axis
21646        // `PolicyBreakerZeroWindow`-before-`PolicyBreakerWindowBelowTimeout`
21647        // ordering pins on the `(:timeout, :window)` pair.
21648        let mut s = three_member_spec();
21649        s.politicas.timeout = None;
21650        s.politicas.circuit_breaker = Some(CircuitBreaker {
21651            max_failures: 5,
21652            window: Duration::from_secs(10),
21653        });
21654        s.politicas.rate_limit = Some(RateLimit {
21655            rate: 0,
21656            window: Duration::from_secs(1),
21657        });
21658        assert_eq!(
21659            s.validate().unwrap_err(),
21660            AplicacaoError::PolicyRateLimitZero,
21661            "per-axis rate zero-floor arm must fire before the cross-axis starve gate"
21662        );
21663    }
21664
21665    #[test]
21666    fn cross_axis_starve_gate_runs_after_sibling_window_below_timeout_gate() {
21667        // Cross-axis ordering pin: a `:politicas` whose axes trip
21668        // BOTH cross-axis arms — `:window < :timeout` (the sibling
21669        // `PolicyBreakerWindowBelowTimeout` invariant) AND
21670        // `:rate-limit` starves the breaker within `:window` (this
21671        // arm) — must surface the timeout-relation diagnostic first.
21672        // The timeout arm is the per-call-deadline invariant every
21673        // synchronous edge carries whether or not `:rate-limit` is
21674        // declared, so its diagnostic is more self-locating; the
21675        // starve arm needs the reader to reason across three axes,
21676        // where the timeout arm names only two.
21677        //
21678        // A `{ timeout: 30s, window: 10s, rate: 1/h, max_failures: 5 }`
21679        // pair trips both: the window is below the timeout, and the
21680        // rate (1 call/hour) admits far fewer than 5 calls per 10s
21681        // breaker window.
21682        let mut s = three_member_spec();
21683        s.politicas.timeout = Some(Duration::from_secs(30));
21684        s.politicas.circuit_breaker = Some(CircuitBreaker {
21685            max_failures: 5,
21686            window: Duration::from_secs(10),
21687        });
21688        s.politicas.rate_limit = Some(RateLimit {
21689            rate: 1,
21690            window: Duration::from_secs(3600),
21691        });
21692        assert_eq!(
21693            s.validate().unwrap_err(),
21694            AplicacaoError::PolicyBreakerWindowBelowTimeout {
21695                window: Duration::from_secs(10),
21696                timeout: Duration::from_secs(30),
21697            },
21698            "sibling :window<:timeout cross-axis arm must fire before the \
21699             starve arm when both apply"
21700        );
21701    }
21702
21703    #[test]
21704    fn breaker_can_trip_under_rate_limit_predicate_matches_gate_semantic() {
21705        // Equivalence pin: the substrate-canonical
21706        // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicate
21707        // and the [`AplicacaoSpec::validate_politicas`] cross-axis
21708        // arm must discriminate the same set on every pair covered
21709        // by their shared invariant. A future refactor of either
21710        // side that breaks the equivalence trips here rather than as
21711        // a divergence between the predicate's Boolean answer and
21712        // the validate gate's Ok/Err arm — the same
21713        // predicate-vs-gate coherence discipline the sibling
21714        // [`MeshPolicy::breaker_window_observes_timeout`] predicate
21715        // carries against `AplicacaoSpec::validate_politicas`. The
21716        // sweep covers both arms of the invariant (strictly below,
21717        // exactly at, strictly above) and both vacuous arms (None
21718        // `:rate-limit`, None `:circuit-breaker`), so the
21719        // equivalence holds exhaustively over the axis-covered
21720        // accept and reject sets. Clears `:timeout` throughout so
21721        // the sibling `:window<:timeout` gate is vacuous on every
21722        // input.
21723        let rl = |rate: u32, secs: u64| {
21724            Some(RateLimit {
21725                rate,
21726                window: Duration::from_secs(secs),
21727            })
21728        };
21729        let cb = |max_failures: u32, secs: u64| {
21730            Some(CircuitBreaker {
21731                max_failures,
21732                window: Duration::from_secs(secs),
21733            })
21734        };
21735        let cases: &[(Option<RateLimit>, Option<CircuitBreaker>)] = &[
21736            // starving pairs (predicate = false, gate = Err)
21737            (rl(1, 3600), cb(5, 10)),
21738            (rl(4, 1), cb(5, 1)),
21739            // boundary + coherent pairs (predicate = true, gate = Ok)
21740            (rl(5, 1), cb(5, 1)),
21741            (rl(100, 1), cb(5, 10)),
21742            // vacuous arms
21743            (None, cb(5, 10)),
21744            (rl(1, 3600), None),
21745            (None, None),
21746        ];
21747        for (rate_limit, circuit_breaker) in cases.iter().copied() {
21748            let politicas = MeshPolicy {
21749                circuit_breaker,
21750                rate_limit,
21751                ..Default::default()
21752            };
21753            let predicate = politicas.breaker_can_trip_under_rate_limit();
21754
21755            let mut s = three_member_spec();
21756            s.politicas = politicas.clone();
21757            s.politicas.timeout = None;
21758            let gate_ok = !matches!(
21759                s.validate(),
21760                Err(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit { .. })
21761            );
21762
21763            assert_eq!(
21764                predicate, gate_ok,
21765                "predicate must agree with validate arm on pair \
21766                 (rate_limit={rate_limit:?}, circuit_breaker={circuit_breaker:?})"
21767            );
21768        }
21769    }
21770
21771    #[test]
21772    fn rejects_retries_saturate_breaker_trip_threshold() {
21773        // The fail-before-pass-after pin on the cross-axis
21774        // `(:retries, :circuit-breaker :max-failures)` invariant. Each
21775        // axis is individually well-formed under its own per-axis
21776        // bracket (both above the zero floor, both below the cap), but
21777        // the pair is a structurally-truncated retry policy: one
21778        // client's `retries + 1 = 4` failing attempts hit the trip
21779        // threshold on the third attempt, the breaker opens, and the
21780        // fourth attempt (the last declared retry) is blocked by the
21781        // open breaker — the substrate declared four attempts and
21782        // structurally allows three.
21783        //
21784        // Envoy's `retry_policy.num_retries` paired against
21785        // `outlier_detection.consecutive_5xx` carries the identical
21786        // relation; every production playbook that pairs the two axes
21787        // (Envoy, Istio, resilience4j, Hystrix) sizes the breaker's
21788        // trip threshold strictly above any single client's retry
21789        // budget so the breaker distinguishes one persistently-failing
21790        // client from sustained multi-client failure.
21791        //
21792        // Pin both the diagnostic arm and the payload values so a
21793        // future re-shape of the arm surfaces here as a deliberate
21794        // test edit. Clears `:timeout` and `:rate-limit` so the
21795        // sibling cross-axis
21796        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] /
21797        // [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`]
21798        // arms do not fire first on the ordering-precedent they hold
21799        // over this arm.
21800        let mut s = three_member_spec();
21801        s.politicas.timeout = None;
21802        s.politicas.retries = Some(3);
21803        s.politicas.circuit_breaker = Some(CircuitBreaker {
21804            max_failures: 3,
21805            window: Duration::from_secs(1),
21806        });
21807        s.politicas.rate_limit = None;
21808        assert_eq!(
21809            s.validate().unwrap_err(),
21810            AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
21811                retries: 3,
21812                max_failures: 3,
21813            }
21814        );
21815    }
21816
21817    #[test]
21818    fn accepts_retries_below_breaker_trip_threshold() {
21819        // Positive-control sweep across the production-playbook band
21820        // — every pair a real playbook recommends where the breaker's
21821        // trip threshold is strictly above the client's retry budget
21822        // must validate. Envoy default `num_retries: 3` with
21823        // `consecutive_5xx: 5` (breaker admits one client's 4 attempts,
21824        // opens on multi-client failures beyond that); Istio
21825        // `attempts: 3` with `consecutive5xxErrors: 5`; Hystrix
21826        // `execution.isolation.thread.timeoutInMilliseconds` + 3
21827        // retries with `requestVolumeThreshold: 20`; AWS App Mesh
21828        // `maxRetries: 5` with a `maxEjectionPercent`-derived threshold
21829        // of 10; resilience4j 2 retries with `slidingWindowSize: 10`.
21830        // Clears `:timeout` and `:rate-limit` so the sibling cross-axis
21831        // arms are vacuous on this sweep.
21832        for (retries, max_failures) in [(1u32, 5u32), (3, 5), (3, 20), (5, 10), (2, 10), (10, 1000)]
21833        {
21834            let mut s = three_member_spec();
21835            s.politicas.timeout = None;
21836            s.politicas.retries = Some(retries);
21837            s.politicas.circuit_breaker = Some(CircuitBreaker {
21838                max_failures,
21839                window: Duration::from_secs(60),
21840            });
21841            s.politicas.rate_limit = None;
21842            s.validate().unwrap_or_else(|e| {
21843                panic!(
21844                    "production-playbook pair retries={retries} \
21845                     max_failures={max_failures} must validate; got {e:?}"
21846                )
21847            });
21848        }
21849    }
21850
21851    #[test]
21852    fn accepts_retries_exactly_at_boundary_below_trip_threshold() {
21853        // Boundary pin: `max_failures == retries + 1` is the smallest
21854        // trip threshold that admits one client's exhausted retries
21855        // through completion (the R+1th failure — the last declared
21856        // retry — trips the breaker exactly as it completes, so
21857        // retries fully executed). The invariant is `>`, not `>=`,
21858        // stated in the coherent direction `max_failures > retries`.
21859        // Catches a future off-by-one tightening to
21860        // `max_failures > retries + 1` that would drift the accept set
21861        // away from the codified
21862        // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]
21863        // predicate.
21864        let mut s = three_member_spec();
21865        s.politicas.timeout = None;
21866        s.politicas.retries = Some(3);
21867        s.politicas.circuit_breaker = Some(CircuitBreaker {
21868            max_failures: 4,
21869            window: Duration::from_secs(60),
21870        });
21871        s.politicas.rate_limit = None;
21872        s.validate()
21873            .expect("max_failures == retries + 1 is the boundary accept case");
21874    }
21875
21876    #[test]
21877    fn rejects_retries_equal_to_breaker_trip_threshold() {
21878        // Off-by-one boundary pin: exactly at the trip threshold is
21879        // still structurally truncating (the invariant is `>`, so `<=`
21880        // refuses even the tight boundary). `retries = 3` with
21881        // `max_failures = 3` means the breaker trips on the third
21882        // failure — the last declared retry attempt is blocked.
21883        // Catches a future relaxation to `>=` that would silently
21884        // drift the accept boundary.
21885        let mut s = three_member_spec();
21886        s.politicas.timeout = None;
21887        s.politicas.retries = Some(3);
21888        s.politicas.circuit_breaker = Some(CircuitBreaker {
21889            max_failures: 3,
21890            window: Duration::from_secs(60),
21891        });
21892        s.politicas.rate_limit = None;
21893        assert_eq!(
21894            s.validate().unwrap_err(),
21895            AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
21896                retries: 3,
21897                max_failures: 3,
21898            }
21899        );
21900    }
21901
21902    #[test]
21903    fn cross_axis_retries_gate_vacuous_when_retries_absent() {
21904        // The predicate is vacuously `true` when `:retries` is None —
21905        // a `:circuit-breaker` alone declares a failure counter whose
21906        // per-client attempt count is unconstrained by the substrate,
21907        // so no per-client saturation bound on failures-per-client-call
21908        // is knowable at author time. The substrate takes no position
21909        // on whether an omitted `:retries` axis means zero retries or
21910        // "the client picks its own retry policy" — either way, the
21911        // pair is undeclared and the cross-axis gate has nothing to
21912        // check. Pin so a future tightening that made the gate
21913        // opinionated on half-declared pairs surfaces here.
21914        let mut s = three_member_spec();
21915        s.politicas.timeout = None;
21916        s.politicas.retries = None;
21917        s.politicas.circuit_breaker = Some(CircuitBreaker {
21918            max_failures: 1,
21919            window: Duration::from_secs(60),
21920        });
21921        s.politicas.rate_limit = None;
21922        s.validate().expect(
21923            "cross-axis retries gate must be vacuous when :retries is None, \
21924             however low :max-failures is",
21925        );
21926    }
21927
21928    #[test]
21929    fn cross_axis_retries_gate_vacuous_when_circuit_breaker_absent() {
21930        // Peer of the sibling `:retries`-absent case: a `:retries`
21931        // without a `:circuit-breaker` declares a client-retry policy
21932        // with no failure counter to trip, so the pair is undeclared
21933        // and the cross-axis gate has nothing to check.
21934        let mut s = three_member_spec();
21935        s.politicas.timeout = None;
21936        s.politicas.retries = Some(POLICY_RETRIES_MAX);
21937        s.politicas.circuit_breaker = None;
21938        s.politicas.rate_limit = None;
21939        s.validate().expect(
21940            "cross-axis retries gate must be vacuous when :circuit-breaker is None, \
21941             however high :retries is",
21942        );
21943    }
21944
21945    #[test]
21946    fn cross_axis_retries_gate_runs_after_per_axis_brackets() {
21947        // Ordering pin: a pair whose retries is *both* zero-floor-
21948        // violating and structurally at-or-below the trip threshold
21949        // must surface the per-axis zero-floor arm first — the
21950        // zero-floor diagnostic is more self-locating (its omit-axis
21951        // remediation is directly named), where the cross-axis arm
21952        // would send the author to reconcile two values one of which
21953        // is not a meaningful retry count at all. Same ordering
21954        // discipline every per-axis bracket carries internally
21955        // (zero-floor before canonical-form before cap), and the
21956        // sibling cross-axis
21957        // `PolicyRateLimitZero`-before-`PolicyBreakerCannotTripUnderRateLimit`
21958        // ordering pins on the `(:rate-limit, :circuit-breaker)` pair.
21959        let mut s = three_member_spec();
21960        s.politicas.timeout = None;
21961        s.politicas.retries = Some(0);
21962        s.politicas.circuit_breaker = Some(CircuitBreaker {
21963            max_failures: 3,
21964            window: Duration::from_secs(60),
21965        });
21966        s.politicas.rate_limit = None;
21967        assert_eq!(
21968            s.validate().unwrap_err(),
21969            AplicacaoError::PolicyRetriesZero,
21970            "per-axis retries zero-floor arm must fire before the cross-axis retries gate"
21971        );
21972    }
21973
21974    #[test]
21975    fn cross_axis_retries_gate_runs_after_sibling_starve_gate() {
21976        // Cross-axis ordering pin: a `:politicas` whose axes trip
21977        // BOTH cross-axis arms — `:rate-limit` starves the breaker
21978        // within `:window` (the sibling
21979        // `PolicyBreakerCannotTripUnderRateLimit` invariant) AND
21980        // `:retries + 1` saturates `:max-failures` (this arm) — must
21981        // surface the rate-limit-starve diagnostic first. The
21982        // rate-limit-starve arm reasons across the token-bucket
21983        // admission axis every rate-limited edge carries whether or
21984        // not `:retries` is declared, so its diagnostic is more
21985        // self-locating; the retries-saturate arm reasons across a
21986        // per-client retry-policy budget the starve arm does not
21987        // touch.
21988        //
21989        // A `{ retries: 5, rate: 1/h, max_failures: 5, cb_window: 10s }`
21990        // pair trips both: the rate structurally cannot deliver 5
21991        // failures per 10s breaker window, and simultaneously
21992        // one client's `retries + 1 = 6` attempts alone would
21993        // saturate the 5-`max_failures` threshold.
21994        let mut s = three_member_spec();
21995        s.politicas.timeout = None;
21996        s.politicas.retries = Some(5);
21997        s.politicas.circuit_breaker = Some(CircuitBreaker {
21998            max_failures: 5,
21999            window: Duration::from_secs(10),
22000        });
22001        s.politicas.rate_limit = Some(RateLimit {
22002            rate: 1,
22003            window: Duration::from_secs(3600),
22004        });
22005        assert_eq!(
22006            s.validate().unwrap_err(),
22007            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
22008                rate: 1,
22009                rl_window: Duration::from_secs(3600),
22010                max_failures: 5,
22011                cb_window: Duration::from_secs(10),
22012            },
22013            "sibling :rate-limit-starve cross-axis arm must fire before the \
22014             retries-saturate arm when both apply"
22015        );
22016    }
22017
22018    #[test]
22019    fn retries_fit_under_breaker_trip_threshold_predicate_matches_gate_semantic() {
22020        // Equivalence pin: the substrate-canonical
22021        // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]
22022        // predicate and the [`AplicacaoSpec::validate_politicas`]
22023        // cross-axis arm must discriminate the same set on every pair
22024        // covered by their shared invariant. A future refactor of
22025        // either side that breaks the equivalence trips here rather
22026        // than as a divergence between the predicate's Boolean answer
22027        // and the validate gate's Ok/Err arm — the same
22028        // predicate-vs-gate coherence discipline the sibling
22029        // [`MeshPolicy::breaker_window_observes_timeout`] and
22030        // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
22031        // carry against `AplicacaoSpec::validate_politicas`. The
22032        // sweep covers both arms of the invariant (strictly below,
22033        // exactly at the boundary, strictly above) and both vacuous
22034        // arms (None `:retries`, None `:circuit-breaker`), so the
22035        // equivalence holds exhaustively over the axis-covered accept
22036        // and reject sets. Clears `:timeout` and `:rate-limit`
22037        // throughout so the sibling cross-axis arms are vacuous on
22038        // every input.
22039        let cb = |max_failures: u32| {
22040            Some(CircuitBreaker {
22041                max_failures,
22042                window: Duration::from_secs(60),
22043            })
22044        };
22045        let cases: &[(Option<u32>, Option<CircuitBreaker>)] = &[
22046            // saturating pairs (predicate = false, gate = Err)
22047            (Some(3), cb(3)),
22048            (Some(3), cb(1)),
22049            (Some(10), cb(5)),
22050            // boundary + coherent pairs (predicate = true, gate = Ok)
22051            (Some(3), cb(4)),
22052            (Some(1), cb(5)),
22053            (Some(3), cb(20)),
22054            // vacuous arms
22055            (None, cb(1)),
22056            (Some(10), None),
22057            (None, None),
22058        ];
22059        for (retries, circuit_breaker) in cases.iter().copied() {
22060            let politicas = MeshPolicy {
22061                retries,
22062                circuit_breaker,
22063                ..Default::default()
22064            };
22065            let predicate = politicas.retries_fit_under_breaker_trip_threshold();
22066
22067            let mut s = three_member_spec();
22068            s.politicas = politicas.clone();
22069            let gate_ok = !matches!(
22070                s.validate(),
22071                Err(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted { .. })
22072            );
22073
22074            assert_eq!(
22075                predicate, gate_ok,
22076                "predicate must agree with validate arm on pair \
22077                 (retries={retries:?}, circuit_breaker={circuit_breaker:?})"
22078            );
22079        }
22080    }
22081
22082    #[test]
22083    fn rejects_rate_limit_cannot_admit_retry_burst() {
22084        // The fail-before-pass-after pin on the cross-axis
22085        // `(:retries, :rate-limit)` invariant. Each axis is
22086        // individually well-formed under its own per-axis bracket (both
22087        // above the zero floor, both below the cap), but the pair is a
22088        // structurally-truncated retry policy: one client's
22089        // `retries + 1 = 6` failing attempts consume 6 tokens from a
22090        // bucket that admits at most 3 per refill window, so the fourth
22091        // attempt onward is 429ed by the local rate limiter and the
22092        // declared retry policy is silently truncated by the same rate
22093        // limiter it feeds through — the substrate declared six
22094        // attempts and structurally allows three.
22095        //
22096        // Envoy's `local_rate_limit.token_bucket.max_tokens` paired
22097        // against `retry_policy.num_retries` carries the identical
22098        // relation; every production playbook that pairs the two axes
22099        // (Envoy, Istio, resilience4j, AWS App Mesh) sizes the bucket
22100        // capacity strictly above any single client's retry budget so
22101        // the limiter distinguishes one client's declared retries from
22102        // sustained multi-client load.
22103        //
22104        // Pin both the diagnostic arm and the payload values so a
22105        // future re-shape of the arm surfaces here as a deliberate
22106        // test edit. Clears `:timeout` and `:circuit-breaker` so the
22107        // sibling cross-axis
22108        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] /
22109        // [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`] /
22110        // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
22111        // arms do not fire first on the ordering-precedent they hold
22112        // over this arm.
22113        let mut s = three_member_spec();
22114        s.politicas.timeout = None;
22115        s.politicas.retries = Some(5);
22116        s.politicas.circuit_breaker = None;
22117        s.politicas.rate_limit = Some(RateLimit {
22118            rate: 3,
22119            window: Duration::from_secs(1),
22120        });
22121        assert_eq!(
22122            s.validate().unwrap_err(),
22123            AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
22124                retries: 5,
22125                rate: 3,
22126            }
22127        );
22128    }
22129
22130    #[test]
22131    fn accepts_rate_limit_admits_retry_burst() {
22132        // Positive-control sweep across the production-playbook band
22133        // — every pair a real playbook recommends where the bucket
22134        // capacity is strictly above the client's retry budget must
22135        // validate. Envoy default `num_retries: 3` with 100/s (100
22136        // tokens per window admits 4 attempts per client with 96 to
22137        // spare); Istio `attempts: 3` with 50/s (50 admits 4);
22138        // resilience4j 2 retries with 10/s (10 admits 3); AWS App
22139        // Mesh `maxRetries: 5` with 1000/s (1000 admits 6); Cloudflare
22140        // Enterprise 3 retries with 1_000_000/h (1M admits 4). Clears
22141        // `:timeout` and `:circuit-breaker` so the sibling cross-axis
22142        // arms are vacuous on this sweep.
22143        for (retries, rate, secs) in [
22144            (3u32, 100u32, 1u64),
22145            (3, 50, 1),
22146            (2, 10, 1),
22147            (5, 1000, 1),
22148            (3, 1_000_000, 3600),
22149            (10, POLICY_RATE_LIMIT_MAX, 1),
22150        ] {
22151            let mut s = three_member_spec();
22152            s.politicas.timeout = None;
22153            s.politicas.retries = Some(retries);
22154            s.politicas.circuit_breaker = None;
22155            s.politicas.rate_limit = Some(RateLimit {
22156                rate,
22157                window: Duration::from_secs(secs),
22158            });
22159            s.validate().unwrap_or_else(|e| {
22160                panic!(
22161                    "production-playbook pair retries={retries} rate={rate}/{secs}s \
22162                     must validate; got {e:?}"
22163                )
22164            });
22165        }
22166    }
22167
22168    #[test]
22169    fn accepts_rate_exactly_at_boundary_admits_retry_burst() {
22170        // Boundary pin: `rate == retries + 1` is the smallest bucket
22171        // capacity that structurally admits one client's exhausted
22172        // retries through completion (each attempt draws exactly one
22173        // token; `retries + 1` tokens available admits `retries + 1`
22174        // attempts, retries fully executed). The invariant is `>=`,
22175        // stated in the coherent direction `rate >= retries + 1`.
22176        // Catches a future off-by-one tightening to `rate > retries + 1`
22177        // that would drift the accept set away from the codified
22178        // [`MeshPolicy::rate_limit_admits_retry_burst`] predicate.
22179        let mut s = three_member_spec();
22180        s.politicas.timeout = None;
22181        s.politicas.retries = Some(3);
22182        s.politicas.circuit_breaker = None;
22183        s.politicas.rate_limit = Some(RateLimit {
22184            rate: 4,
22185            window: Duration::from_secs(1),
22186        });
22187        s.validate()
22188            .expect("rate == retries + 1 is the boundary accept case");
22189    }
22190
22191    #[test]
22192    fn rejects_rate_one_below_retry_burst() {
22193        // Off-by-one boundary pin: exactly one token short of the
22194        // retry burst is still structurally truncating (the invariant
22195        // is `>=`, so `<` refuses even a one-token shortfall).
22196        // `retries = 3` with `rate = 3` means one client's four
22197        // attempts consume four tokens from a three-token bucket —
22198        // the fourth attempt is 429ed. Catches a future relaxation to
22199        // `>` on the wrong side (`rate > retries`, accepting equal)
22200        // that would silently drift the accept boundary and admit a
22201        // structurally-truncated retry policy at the emit boundary.
22202        let mut s = three_member_spec();
22203        s.politicas.timeout = None;
22204        s.politicas.retries = Some(3);
22205        s.politicas.circuit_breaker = None;
22206        s.politicas.rate_limit = Some(RateLimit {
22207            rate: 3,
22208            window: Duration::from_secs(1),
22209        });
22210        assert_eq!(
22211            s.validate().unwrap_err(),
22212            AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
22213                retries: 3,
22214                rate: 3,
22215            }
22216        );
22217    }
22218
22219    #[test]
22220    fn cross_axis_burst_gate_vacuous_when_retries_absent() {
22221        // The predicate is vacuously `true` when `:retries` is None —
22222        // a `:rate-limit` alone declares a token-bucket rate whose
22223        // per-client attempt count is unconstrained by the substrate,
22224        // so no per-client saturation bound on tokens-per-client-call
22225        // is knowable at author time. The substrate takes no position
22226        // on whether an omitted `:retries` axis means zero retries or
22227        // "the client picks its own retry policy" — either way, the
22228        // pair is undeclared and the cross-axis gate has nothing to
22229        // check. Pin so a future tightening that made the gate
22230        // opinionated on half-declared pairs surfaces here.
22231        let mut s = three_member_spec();
22232        s.politicas.timeout = None;
22233        s.politicas.retries = None;
22234        s.politicas.circuit_breaker = None;
22235        s.politicas.rate_limit = Some(RateLimit {
22236            rate: 1,
22237            window: Duration::from_secs(1),
22238        });
22239        s.validate().expect(
22240            "cross-axis burst gate must be vacuous when :retries is None, \
22241             however low :rate is",
22242        );
22243    }
22244
22245    #[test]
22246    fn cross_axis_burst_gate_vacuous_when_rate_limit_absent() {
22247        // Peer of the sibling `:retries`-absent case: a `:retries`
22248        // without a `:rate-limit` declares a client-retry policy with
22249        // no rate limiter to saturate, so the pair is undeclared and
22250        // the cross-axis gate has nothing to check. Uses
22251        // [`POLICY_RETRIES_MAX`] to pin the vacuity across the widest
22252        // authored retry budget the per-axis cap admits — a `:retries
22253        // POLICY_RETRIES_MAX` alone must remain a clean pass whether
22254        // or not `:rate-limit` is declared.
22255        let mut s = three_member_spec();
22256        s.politicas.timeout = None;
22257        s.politicas.retries = Some(POLICY_RETRIES_MAX);
22258        s.politicas.circuit_breaker = None;
22259        s.politicas.rate_limit = None;
22260        s.validate().expect(
22261            "cross-axis burst gate must be vacuous when :rate-limit is None, \
22262             however high :retries is",
22263        );
22264    }
22265
22266    #[test]
22267    fn cross_axis_burst_gate_runs_after_per_axis_brackets() {
22268        // Ordering pin: a pair whose retries is *both* zero-floor-
22269        // violating and structurally below the retry-burst threshold
22270        // must surface the per-axis zero-floor arm first — the
22271        // zero-floor diagnostic is more self-locating (its omit-axis
22272        // remediation is directly named), where the cross-axis arm
22273        // would send the author to reconcile two values one of which
22274        // is not a meaningful retry count at all. Same ordering
22275        // discipline every per-axis bracket carries internally
22276        // (zero-floor before canonical-form before cap), and the
22277        // sibling cross-axis
22278        // `PolicyRetriesZero`-before-`PolicyBreakerTripsBeforeRetriesExhausted`
22279        // ordering pin on the `(:retries, :max-failures)` pair.
22280        let mut s = three_member_spec();
22281        s.politicas.timeout = None;
22282        s.politicas.retries = Some(0);
22283        s.politicas.circuit_breaker = None;
22284        s.politicas.rate_limit = Some(RateLimit {
22285            rate: 1,
22286            window: Duration::from_secs(1),
22287        });
22288        assert_eq!(
22289            s.validate().unwrap_err(),
22290            AplicacaoError::PolicyRetriesZero,
22291            "per-axis retries zero-floor arm must fire before the cross-axis burst gate"
22292        );
22293    }
22294
22295    #[test]
22296    fn cross_axis_burst_gate_runs_after_sibling_starve_gate() {
22297        // Cross-axis ordering pin: a `:politicas` whose axes trip
22298        // BOTH cross-axis arms — `:rate-limit` starves the breaker
22299        // within `:window` (the sibling
22300        // `PolicyBreakerCannotTripUnderRateLimit` invariant) AND
22301        // `:retries + 1` exceeds the bucket capacity (this arm) —
22302        // must surface the rate-limit-starve diagnostic first. The
22303        // starve arm is the token-bucket admission invariant every
22304        // rate-limited edge carries against the breaker whether or
22305        // not `:retries` is declared, so its diagnostic is more
22306        // self-locating; the burst arm reasons across a per-client
22307        // retry-policy budget the starve arm does not touch. Same
22308        // "more foundational cross-axis first" ordering discipline the
22309        // sibling
22310        // `PolicyBreakerCannotTripUnderRateLimit`-before-`PolicyBreakerTripsBeforeRetriesExhausted`
22311        // pin on the peer pair carries.
22312        //
22313        // A `{ retries: 5, rate: 1/h, max_failures: 5, cb_window: 10s }`
22314        // pair trips both: the rate structurally cannot deliver 5
22315        // failures per 10s breaker window (starve arm), and
22316        // simultaneously one client's `retries + 1 = 6` attempts alone
22317        // would exhaust the 1-token bucket (burst arm).
22318        let mut s = three_member_spec();
22319        s.politicas.timeout = None;
22320        s.politicas.retries = Some(5);
22321        s.politicas.circuit_breaker = Some(CircuitBreaker {
22322            max_failures: 5,
22323            window: Duration::from_secs(10),
22324        });
22325        s.politicas.rate_limit = Some(RateLimit {
22326            rate: 1,
22327            window: Duration::from_secs(3600),
22328        });
22329        assert_eq!(
22330            s.validate().unwrap_err(),
22331            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
22332                rate: 1,
22333                rl_window: Duration::from_secs(3600),
22334                max_failures: 5,
22335                cb_window: Duration::from_secs(10),
22336            },
22337            "sibling :rate-limit-starve cross-axis arm must fire before the \
22338             burst arm when both apply"
22339        );
22340    }
22341
22342    #[test]
22343    fn cross_axis_burst_gate_runs_after_sibling_retries_saturate_gate() {
22344        // Cross-axis ordering pin: a `:politicas` whose axes trip
22345        // BOTH the retries-saturate arm and this burst arm — one
22346        // client's `retries + 1` failures saturate the breaker's trip
22347        // threshold (the sibling
22348        // `PolicyBreakerTripsBeforeRetriesExhausted` invariant) AND
22349        // `retries + 1` exceeds the bucket capacity (this arm) —
22350        // must surface the retries-saturate diagnostic first. The
22351        // saturate arm is the per-client-vs-breaker relation every
22352        // retry-with-breaker pair carries whether or not `:rate-limit`
22353        // is declared, so its diagnostic is more self-locating; the
22354        // burst arm reasons across the rate-limit token-bucket
22355        // admission axis the saturate arm does not touch. Same
22356        // "more foundational cross-axis first" ordering discipline
22357        // carries here.
22358        //
22359        // A `{ retries: 5, max_failures: 3, cb_window: 60s,
22360        // rate: 3/s }` pair trips both: the breaker's `max_failures
22361        // = 3` is `<= retries = 5` (saturate arm), and simultaneously
22362        // one client's `retries + 1 = 6` attempts alone would exhaust
22363        // the 3-token bucket (burst arm). Clears `:timeout` so the
22364        // sibling `:window<:timeout` gate is vacuous, and the
22365        // `(rate=3/s, max_failures=3, cb_window=60s)` triple keeps
22366        // the starve arm coherent (`3 × 60s >= 3 × 1s`) so it is not
22367        // the arm that fires first.
22368        let mut s = three_member_spec();
22369        s.politicas.timeout = None;
22370        s.politicas.retries = Some(5);
22371        s.politicas.circuit_breaker = Some(CircuitBreaker {
22372            max_failures: 3,
22373            window: Duration::from_secs(60),
22374        });
22375        s.politicas.rate_limit = Some(RateLimit {
22376            rate: 3,
22377            window: Duration::from_secs(1),
22378        });
22379        assert_eq!(
22380            s.validate().unwrap_err(),
22381            AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
22382                retries: 5,
22383                max_failures: 3,
22384            },
22385            "sibling :retries-saturate cross-axis arm must fire before the \
22386             burst arm when both apply"
22387        );
22388    }
22389
22390    #[test]
22391    fn rate_limit_admits_retry_burst_predicate_matches_gate_semantic() {
22392        // Equivalence pin: the substrate-canonical
22393        // [`MeshPolicy::rate_limit_admits_retry_burst`] predicate and
22394        // the [`AplicacaoSpec::validate_politicas`] cross-axis arm
22395        // must discriminate the same set on every pair covered by
22396        // their shared invariant. A future refactor of either side
22397        // that breaks the equivalence trips here rather than as a
22398        // divergence between the predicate's Boolean answer and the
22399        // validate gate's Ok/Err arm — the same predicate-vs-gate
22400        // coherence discipline the three sibling cross-axis
22401        // predicates ([`MeshPolicy::breaker_window_observes_timeout`],
22402        // [`MeshPolicy::breaker_can_trip_under_rate_limit`],
22403        // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`])
22404        // carry against `AplicacaoSpec::validate_politicas`. The sweep
22405        // covers both arms of the invariant (strictly below, exactly
22406        // at the boundary, strictly above) and both vacuous arms
22407        // (None `:retries`, None `:rate-limit`), so the equivalence
22408        // holds exhaustively over the axis-covered accept and reject
22409        // sets. Clears `:timeout` and `:circuit-breaker` throughout
22410        // so the three sibling cross-axis arms are vacuous on every
22411        // input.
22412        let rl = |rate: u32, secs: u64| {
22413            Some(RateLimit {
22414                rate,
22415                window: Duration::from_secs(secs),
22416            })
22417        };
22418        let cases: &[(Option<u32>, Option<RateLimit>)] = &[
22419            // burst-exceeding pairs (predicate = false, gate = Err)
22420            (Some(3), rl(3, 1)),
22421            (Some(5), rl(1, 1)),
22422            (Some(10), rl(5, 1)),
22423            // boundary + coherent pairs (predicate = true, gate = Ok)
22424            (Some(3), rl(4, 1)),
22425            (Some(1), rl(5, 1)),
22426            (Some(3), rl(1_000_000, 3600)),
22427            // vacuous arms
22428            (None, rl(1, 1)),
22429            (Some(10), None),
22430            (None, None),
22431        ];
22432        for (retries, rate_limit) in cases.iter().copied() {
22433            let politicas = MeshPolicy {
22434                retries,
22435                rate_limit,
22436                ..Default::default()
22437            };
22438            let predicate = politicas.rate_limit_admits_retry_burst();
22439
22440            let mut s = three_member_spec();
22441            s.politicas = politicas.clone();
22442            let gate_ok = !matches!(
22443                s.validate(),
22444                Err(AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst { .. })
22445            );
22446
22447            assert_eq!(
22448                predicate, gate_ok,
22449                "predicate must agree with validate arm on pair \
22450                 (retries={retries:?}, rate_limit={rate_limit:?})"
22451            );
22452        }
22453    }
22454
22455    /// Sweep body shared by every `first_cross_axis_violation` ≡ gate
22456    /// equivalence pin — assert that on each `(label, politicas,
22457    /// expected)` case the substrate-canonical fold and the validate
22458    /// cascade agree byte-for-byte. Extracted so each pin's own body
22459    /// stays under `clippy::too_many_lines`.
22460    fn assert_first_cross_axis_violation_agrees_with_gate(
22461        cases: &[(&str, MeshPolicy, Option<AplicacaoError>)],
22462    ) {
22463        for (label, politicas, expected) in cases {
22464            let fold = politicas.first_cross_axis_violation();
22465            assert_eq!(
22466                fold.as_ref(),
22467                expected.as_ref(),
22468                "fold must return {expected:?} on `{label}`; got {fold:?}"
22469            );
22470
22471            let mut s = three_member_spec();
22472            s.politicas = politicas.clone();
22473            let gate = s.validate();
22474            match expected {
22475                None => {
22476                    // No cross-axis violation: validate must pass (the
22477                    // per-axis brackets pass by construction on every
22478                    // fixture above; every fixture's non-`:politicas`
22479                    // slots come from `three_member_spec`).
22480                    gate.as_ref()
22481                        .unwrap_or_else(|e| panic!("`{label}` must validate cleanly; got {e:?}"));
22482                }
22483                Some(want) => {
22484                    let got =
22485                        gate.expect_err(&format!("`{label}` must surface a cross-axis violation"));
22486                    assert_eq!(
22487                        &got, want,
22488                        "validate cross-axis cascade must return {want:?} on `{label}`; got {got:?}"
22489                    );
22490                }
22491            }
22492        }
22493    }
22494
22495    #[test]
22496    fn first_cross_axis_violation_matches_gate_on_single_arm_and_vacuous_shapes() {
22497        // Equivalence pin on the compound cross-axis fold: the
22498        // substrate-canonical [`MeshPolicy::first_cross_axis_violation`]
22499        // and the [`AplicacaoSpec::validate_politicas`] cross-axis
22500        // cascade must return identical `AplicacaoError` variants on
22501        // every axis-covered input — the "compound-fold ≡ gate"
22502        // contract that generalizes the four sibling per-arm pins
22503        // onto the compound primitive that folds all four. A future
22504        // refactor of either side that breaks the equivalence trips
22505        // here rather than as a divergence between what the substrate
22506        // primitive answers and what `feira build` accepts.
22507        //
22508        // Half-A of the sweep: every single-arm violation (one arm
22509        // fires with the three sibling arms vacuous), the vacuous
22510        // shape (empty policy — no arm fires), and the fully-coherent
22511        // shape (every axis declared inside the coherence surface —
22512        // no arm fires). Half-B (pairwise-ordering coverage — the
22513        // "which arm wins when two apply" contract) lives in the
22514        // sibling `first_cross_axis_violation_matches_gate_on_pairwise_orderings`
22515        // pin; splitting keeps each pin's body under
22516        // `clippy::too_many_lines`.
22517        let cb = |max_failures: u32, secs: u64| CircuitBreaker {
22518            max_failures,
22519            window: Duration::from_secs(secs),
22520        };
22521        let rl = |rate: u32, secs: u64| RateLimit {
22522            rate,
22523            window: Duration::from_secs(secs),
22524        };
22525        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
22526            (
22527                "window-below-timeout only",
22528                MeshPolicy {
22529                    timeout: Some(Duration::from_secs(30)),
22530                    circuit_breaker: Some(cb(5, 10)),
22531                    ..Default::default()
22532                },
22533                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
22534                    window: Duration::from_secs(10),
22535                    timeout: Duration::from_secs(30),
22536                }),
22537            ),
22538            (
22539                "starve only",
22540                MeshPolicy {
22541                    rate_limit: Some(rl(1, 3600)),
22542                    circuit_breaker: Some(cb(5, 10)),
22543                    ..Default::default()
22544                },
22545                Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
22546                    rate: 1,
22547                    rl_window: Duration::from_secs(3600),
22548                    max_failures: 5,
22549                    cb_window: Duration::from_secs(10),
22550                }),
22551            ),
22552            (
22553                "retries-saturate only",
22554                MeshPolicy {
22555                    retries: Some(3),
22556                    circuit_breaker: Some(cb(3, 60)),
22557                    ..Default::default()
22558                },
22559                Some(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
22560                    retries: 3,
22561                    max_failures: 3,
22562                }),
22563            ),
22564            (
22565                "retries-burst only",
22566                MeshPolicy {
22567                    retries: Some(5),
22568                    rate_limit: Some(rl(3, 1)),
22569                    ..Default::default()
22570                },
22571                Some(AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
22572                    retries: 5,
22573                    rate: 3,
22574                }),
22575            ),
22576            ("empty policy", MeshPolicy::default(), None),
22577            (
22578                "fully-coherent policy",
22579                MeshPolicy {
22580                    timeout: Some(Duration::from_secs(30)),
22581                    retries: Some(3),
22582                    circuit_breaker: Some(cb(5, 60)),
22583                    mtls_required: Some(true),
22584                    rate_limit: Some(rl(100, 1)),
22585                },
22586                None,
22587            ),
22588        ];
22589        assert_first_cross_axis_violation_agrees_with_gate(cases);
22590    }
22591
22592    #[test]
22593    fn first_cross_axis_violation_matches_gate_on_pairwise_orderings() {
22594        // Half-B of the compound-fold ≡ gate equivalence pin: the
22595        // load-bearing pairwise-ordering coverage. Every ordered pair
22596        // of the four cross-axis arms — six combinations — where two
22597        // arms are simultaneously eligible must surface the
22598        // more-foundational arm's diagnostic verbatim. Pins the fold's
22599        // arm-ordering byte-for-byte against the validate cascade's
22600        // arm-ordering, so a future reshuffle of either side that
22601        // silently drifts the ordering trips here rather than as a
22602        // per-arm miss the sibling per-arm `_predicate_matches_gate_semantic`
22603        // pins cannot catch (they clear every sibling arm, so their
22604        // sweeps are pairwise-ordering-agnostic by construction).
22605        //
22606        // The six pairs the four-arm cascade admits:
22607        // window-before-starve, window-before-saturate,
22608        // window-before-burst, starve-before-saturate,
22609        // starve-before-burst, saturate-before-burst.
22610        let cb = |max_failures: u32, secs: u64| CircuitBreaker {
22611            max_failures,
22612            window: Duration::from_secs(secs),
22613        };
22614        let rl = |rate: u32, secs: u64| RateLimit {
22615            rate,
22616            window: Duration::from_secs(secs),
22617        };
22618        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
22619            (
22620                "window+starve → window wins",
22621                MeshPolicy {
22622                    timeout: Some(Duration::from_secs(30)),
22623                    rate_limit: Some(rl(1, 3600)),
22624                    circuit_breaker: Some(cb(5, 10)),
22625                    ..Default::default()
22626                },
22627                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
22628                    window: Duration::from_secs(10),
22629                    timeout: Duration::from_secs(30),
22630                }),
22631            ),
22632            (
22633                "window+retries-saturate → window wins",
22634                MeshPolicy {
22635                    timeout: Some(Duration::from_secs(30)),
22636                    retries: Some(5),
22637                    circuit_breaker: Some(cb(3, 10)),
22638                    ..Default::default()
22639                },
22640                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
22641                    window: Duration::from_secs(10),
22642                    timeout: Duration::from_secs(30),
22643                }),
22644            ),
22645            (
22646                "window+retries-burst → window wins",
22647                MeshPolicy {
22648                    timeout: Some(Duration::from_secs(30)),
22649                    retries: Some(5),
22650                    rate_limit: Some(rl(3, 1)),
22651                    circuit_breaker: Some(cb(5, 10)),
22652                    ..Default::default()
22653                },
22654                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
22655                    window: Duration::from_secs(10),
22656                    timeout: Duration::from_secs(30),
22657                }),
22658            ),
22659            (
22660                "starve+retries-saturate → starve wins",
22661                MeshPolicy {
22662                    retries: Some(5),
22663                    rate_limit: Some(rl(1, 3600)),
22664                    circuit_breaker: Some(cb(5, 10)),
22665                    ..Default::default()
22666                },
22667                Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
22668                    rate: 1,
22669                    rl_window: Duration::from_secs(3600),
22670                    max_failures: 5,
22671                    cb_window: Duration::from_secs(10),
22672                }),
22673            ),
22674            (
22675                "starve+retries-burst → starve wins",
22676                MeshPolicy {
22677                    retries: Some(5),
22678                    rate_limit: Some(rl(1, 3600)),
22679                    circuit_breaker: Some(cb(10, 10)),
22680                    ..Default::default()
22681                },
22682                Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
22683                    rate: 1,
22684                    rl_window: Duration::from_secs(3600),
22685                    max_failures: 10,
22686                    cb_window: Duration::from_secs(10),
22687                }),
22688            ),
22689            (
22690                "retries-saturate+retries-burst → saturate wins",
22691                MeshPolicy {
22692                    retries: Some(5),
22693                    rate_limit: Some(rl(3, 1)),
22694                    circuit_breaker: Some(cb(3, 60)),
22695                    ..Default::default()
22696                },
22697                Some(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
22698                    retries: 5,
22699                    max_failures: 3,
22700                }),
22701            ),
22702        ];
22703        assert_first_cross_axis_violation_agrees_with_gate(cases);
22704    }
22705
22706    /// Sweep body shared by every `MeshPolicy::validate` ≡ gate
22707    /// equivalence pin — assert that on each `(label, politicas,
22708    /// expected)` case both the substrate primitive
22709    /// [`MeshPolicy::validate`] and the [`AplicacaoSpec::validate_politicas`]
22710    /// cascade (reached through `AplicacaoSpec::validate`, keying off the
22711    /// same `three_member_spec` fixture whose non-`:politicas` slots
22712    /// always validate cleanly) return identical `AplicacaoError` variants.
22713    /// Peer of [`assert_first_cross_axis_violation_agrees_with_gate`] on
22714    /// the sibling cross-axis-only surface — extended here onto the
22715    /// compound per-axis + cross-axis entry gate. Extracted so each pin's
22716    /// own body stays under `clippy::too_many_lines`.
22717    fn assert_validate_matches_gate(cases: &[(&str, MeshPolicy, Option<AplicacaoError>)]) {
22718        for (label, politicas, expected) in cases {
22719            let direct = politicas.validate();
22720            match (expected, &direct) {
22721                (None, Ok(())) => {}
22722                (None, Err(got)) => {
22723                    panic!("`{label}`: MeshPolicy::validate must pass; got {got:?}")
22724                }
22725                (Some(want), Ok(())) => {
22726                    panic!("`{label}`: MeshPolicy::validate must return {want:?}; got Ok")
22727                }
22728                (Some(want), Err(got)) => assert_eq!(
22729                    got, want,
22730                    "`{label}`: MeshPolicy::validate must return {want:?}; got {got:?}"
22731                ),
22732            }
22733
22734            let mut s = three_member_spec();
22735            s.politicas = politicas.clone();
22736            let gate = s.validate();
22737            match (expected, &gate) {
22738                (None, Ok(())) => {}
22739                (None, Err(got)) => {
22740                    panic!("`{label}`: validate_politicas gate must pass; got {got:?}")
22741                }
22742                (Some(want), Ok(())) => {
22743                    panic!("`{label}`: validate_politicas gate must return {want:?}; got Ok")
22744                }
22745                (Some(want), Err(got)) => assert_eq!(
22746                    got, want,
22747                    "`{label}`: validate_politicas gate must return {want:?}; got {got:?}"
22748                ),
22749            }
22750        }
22751    }
22752
22753    #[test]
22754    fn validate_matches_gate_on_per_axis_and_phase_boundary_shapes() {
22755        // Half-A of the compound-per-axis-+-cross-axis-fold ≡ gate
22756        // equivalence pin on [`MeshPolicy::validate`]: the four per-axis
22757        // zero-floor arms (`:timeout`, `:retries`, `:circuit-breaker
22758        // :max-failures`, `:rate-limit` rate) that discriminate the
22759        // "per-axis phase fires" arm of the compound gate, plus one
22760        // per-axis-before-cross-axis case (`{ timeout: 30s, cb.window:
22761        // ZERO }`) that pins the phase-boundary ordering — the per-axis
22762        // `PolicyBreakerZeroWindow` arm strictly precedes the cross-axis
22763        // `PolicyBreakerWindowBelowTimeout` arm, so the zero-window
22764        // diagnostic wins over the window-below-timeout diagnostic. Peer
22765        // of the sibling
22766        // `first_cross_axis_violation_matches_gate_on_single_arm_and_vacuous_shapes`
22767        // + `_on_pairwise_orderings` pins on the compound cross-axis
22768        // fold, extended here onto the outer compound entry gate that
22769        // folds per-axis + cross-axis surfaces. Half-B (cross-axis and
22770        // clean-pass surfaces) lives in the sibling
22771        // `validate_matches_gate_on_cross_axis_and_clean_pass_shapes`
22772        // pin; splitting keeps each pin's body under
22773        // `clippy::too_many_lines`.
22774        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
22775            (
22776                "per-axis: timeout zero",
22777                MeshPolicy {
22778                    timeout: Some(Duration::ZERO),
22779                    ..Default::default()
22780                },
22781                Some(AplicacaoError::PolicyTimeoutZero),
22782            ),
22783            (
22784                "per-axis: retries zero",
22785                MeshPolicy {
22786                    retries: Some(0),
22787                    ..Default::default()
22788                },
22789                Some(AplicacaoError::PolicyRetriesZero),
22790            ),
22791            (
22792                "per-axis: breaker max-failures zero",
22793                MeshPolicy {
22794                    circuit_breaker: Some(CircuitBreaker {
22795                        max_failures: 0,
22796                        window: Duration::from_secs(60),
22797                    }),
22798                    ..Default::default()
22799                },
22800                Some(AplicacaoError::PolicyBreakerZeroFailures),
22801            ),
22802            (
22803                "per-axis: rate-limit rate zero",
22804                MeshPolicy {
22805                    rate_limit: Some(RateLimit {
22806                        rate: 0,
22807                        window: Duration::from_secs(1),
22808                    }),
22809                    ..Default::default()
22810                },
22811                Some(AplicacaoError::PolicyRateLimitZero),
22812            ),
22813            (
22814                "per-axis before cross-axis: zero-window wins over window-below-timeout",
22815                MeshPolicy {
22816                    timeout: Some(Duration::from_secs(30)),
22817                    circuit_breaker: Some(CircuitBreaker {
22818                        max_failures: 5,
22819                        window: Duration::ZERO,
22820                    }),
22821                    ..Default::default()
22822                },
22823                Some(AplicacaoError::PolicyBreakerZeroWindow),
22824            ),
22825        ];
22826        assert_validate_matches_gate(cases);
22827    }
22828
22829    #[test]
22830    fn validate_matches_gate_on_cross_axis_and_clean_pass_shapes() {
22831        // Half-B of the compound-per-axis-+-cross-axis-fold ≡ gate
22832        // equivalence pin on [`MeshPolicy::validate`]: the cross-axis
22833        // arm that discriminates the "cross-axis phase fires" arm of
22834        // the compound gate (window-below-timeout — sibling per-arm
22835        // coverage lives in the two
22836        // `first_cross_axis_violation_matches_gate_on_*` pins above),
22837        // plus the two clean-pass shapes (empty policy — every axis
22838        // absent — and fully-coherent — every axis inside the coherence
22839        // surface) that pin the compound gate's `Ok(())` arm. Half-A
22840        // (per-axis + phase-boundary surfaces) lives in the sibling
22841        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
22842        // pin; splitting keeps each pin's body under
22843        // `clippy::too_many_lines`.
22844        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
22845            (
22846                "cross-axis: window-below-timeout",
22847                MeshPolicy {
22848                    timeout: Some(Duration::from_secs(30)),
22849                    circuit_breaker: Some(CircuitBreaker {
22850                        max_failures: 5,
22851                        window: Duration::from_secs(10),
22852                    }),
22853                    ..Default::default()
22854                },
22855                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
22856                    window: Duration::from_secs(10),
22857                    timeout: Duration::from_secs(30),
22858                }),
22859            ),
22860            ("clean pass: empty policy", MeshPolicy::default(), None),
22861            (
22862                "clean pass: every axis coherent",
22863                MeshPolicy {
22864                    timeout: Some(Duration::from_secs(30)),
22865                    retries: Some(3),
22866                    circuit_breaker: Some(CircuitBreaker {
22867                        max_failures: 5,
22868                        window: Duration::from_secs(60),
22869                    }),
22870                    mtls_required: Some(true),
22871                    rate_limit: Some(RateLimit {
22872                        rate: 100,
22873                        window: Duration::from_secs(1),
22874                    }),
22875                },
22876                None,
22877            ),
22878        ];
22879        assert_validate_matches_gate(cases);
22880    }
22881
22882    #[test]
22883    fn empty_politicas_validates() {
22884        // Omitting every policy axis is fine — defaults express "no
22885        // policy on this axis", not "policy = 0". The fixture's typical
22886        // values continue to validate; this test pins that
22887        // MeshPolicy::default() is a clean pass through validate().
22888        let mut s = three_member_spec();
22889        s.politicas = MeshPolicy::default();
22890        s.validate().unwrap();
22891    }
22892
22893    #[test]
22894    fn typical_politicas_validates_with_every_axis_set() {
22895        // The full §III.1 example block (timeout + retries + breaker +
22896        // mtls + rate-limit) — every axis nonzero — must remain a
22897        // clean pass.
22898        let mut s = three_member_spec();
22899        s.politicas = MeshPolicy {
22900            timeout: Some(Duration::from_secs(30)),
22901            retries: Some(3),
22902            circuit_breaker: Some(CircuitBreaker {
22903                max_failures: 5,
22904                window: Duration::from_secs(60),
22905            }),
22906            mtls_required: Some(true),
22907            rate_limit: Some(RateLimit {
22908                rate: 100,
22909                window: Duration::from_secs(1),
22910            }),
22911        };
22912        s.validate().unwrap();
22913    }
22914
22915    #[test]
22916    fn rejects_empty_cluster_name() {
22917        let mut s = three_member_spec();
22918        s.placement.clusters = vec!["rio".into(), String::new()];
22919        assert_eq!(
22920            s.validate().unwrap_err(),
22921            AplicacaoError::PlacementClusterEmpty
22922        );
22923    }
22924
22925    #[test]
22926    fn rejects_duplicate_cluster_names() {
22927        let mut s = three_member_spec();
22928        s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
22929        let err = s.validate().unwrap_err();
22930        assert!(
22931            matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
22932            "got {err:?}"
22933        );
22934    }
22935
22936    #[test]
22937    fn rejects_placement_cluster_with_uppercase() {
22938        // The canonical "I copied the cluster's display name verbatim"
22939        // typo — K8s context names are lowercase per DNS-1123 label
22940        // rule, but org docs often round-trip a TitleCase identifier
22941        // (`Rio`, `Mar-East`) from an ADR. Mirrors the
22942        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
22943        // on the peer name axis.
22944        let mut s = three_member_spec();
22945        s.placement.clusters = vec!["Rio".into(), "mar".into()];
22946        let err = s.validate().unwrap_err();
22947        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
22948            panic!("expected PlacementClusterInvalid, got other variant");
22949        };
22950        assert_eq!(cluster, "Rio");
22951        assert!(
22952            reason.contains("uppercase"),
22953            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
22954        );
22955        assert!(
22956            reason.contains("\"rio\""),
22957            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
22958        );
22959    }
22960
22961    #[test]
22962    fn rejects_placement_cluster_with_underscore() {
22963        // The canonical "I'm thinking of an env var / hostname slug"
22964        // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
22965        // schema. K8s context filtering on `my_cluster` silently misses
22966        // the cluster the author intended; the gate moves it to caixa-
22967        // build time. Same shape as `rejects_membro_caixa_with_underscore`
22968        // (3f9d7a0).
22969        let mut s = three_member_spec();
22970        s.placement.clusters = vec!["my_cluster".into()];
22971        let err = s.validate().unwrap_err();
22972        assert!(
22973            matches!(
22974                err,
22975                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
22976                    if cluster == "my_cluster" && reason.contains('_')
22977            ),
22978            "got {err:?}"
22979        );
22980    }
22981
22982    #[test]
22983    fn rejects_placement_cluster_with_dot() {
22984        // A `:placement :clusters` entry is a single DNS-1123 *label*,
22985        // not a subdomain — even though K8s context names sometimes
22986        // carry a dotted form via kubeconfig conventions, the strictest
22987        // floor among the use sites (DNS-1035 cluster.x-k8s.io
22988        // `metadata.name`, Cilium identity label values) wins. The "I
22989        // want to namespace my cluster names with `.`" intent is
22990        // expressed via `-` (`mar-east`).
22991        let mut s = three_member_spec();
22992        s.placement.clusters = vec!["team.rio".into()];
22993        let err = s.validate().unwrap_err();
22994        assert!(
22995            matches!(
22996                err,
22997                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
22998                    if cluster == "team.rio" && reason.contains('.')
22999            ),
23000            "got {err:?}"
23001        );
23002    }
23003
23004    #[test]
23005    fn rejects_placement_cluster_with_leading_hyphen() {
23006        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
23007        // with an alphanumeric. The K8s apiserver rejects `-rio`
23008        // outright; the rendered fan-out would emit a `metadata.name:
23009        // "-rio"` that fails admission far from the source caixa.lisp.
23010        let mut s = three_member_spec();
23011        s.placement.clusters = vec!["-rio".into()];
23012        let err = s.validate().unwrap_err();
23013        assert!(
23014            matches!(
23015                err,
23016                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
23017                    if cluster == "-rio" && reason.contains("start and end")
23018            ),
23019            "got {err:?}"
23020        );
23021    }
23022
23023    #[test]
23024    fn rejects_placement_cluster_with_trailing_hyphen() {
23025        // The symmetric arm of the boundary rule. Pin separately so
23026        // both ends are covered against a future relaxation that only
23027        // checks one boundary (parallel to
23028        // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
23029        let mut s = three_member_spec();
23030        s.placement.clusters = vec!["rio-".into()];
23031        let err = s.validate().unwrap_err();
23032        assert!(
23033            matches!(
23034                err,
23035                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
23036                    if cluster == "rio-"
23037            ),
23038            "got {err:?}"
23039        );
23040    }
23041
23042    #[test]
23043    fn rejects_placement_cluster_with_unicode() {
23044        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
23045        // before it reaches K8s. The byte-by-byte ASCII validity check
23046        // rejects multi-byte UTF-8 sequences by the first byte that
23047        // fails `[a-z0-9-]`.
23048        let mut s = three_member_spec();
23049        s.placement.clusters = vec!["rió".into()];
23050        let err = s.validate().unwrap_err();
23051        assert!(
23052            matches!(
23053                err,
23054                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
23055                    if cluster == "rió"
23056            ),
23057            "got {err:?}"
23058        );
23059    }
23060
23061    #[test]
23062    fn rejects_placement_cluster_with_whitespace() {
23063        // Whitespace is the canonical "I pasted from a sketch / doc"
23064        // footgun. The apiserver rejects every cluster `metadata.name`
23065        // value carrying whitespace.
23066        let mut s = three_member_spec();
23067        s.placement.clusters = vec!["rio cluster".into()];
23068        let err = s.validate().unwrap_err();
23069        assert!(
23070            matches!(
23071                err,
23072                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
23073                    if cluster == "rio cluster"
23074            ),
23075            "got {err:?}"
23076        );
23077    }
23078
23079    #[test]
23080    fn rejects_placement_cluster_too_long() {
23081        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
23082        // pin. The diagnostic names both the cap (63) and the actual
23083        // length so the author can shorten in one edit. Mirrors
23084        // `rejects_membro_caixa_too_long` (3f9d7a0).
23085        let mut s = three_member_spec();
23086        let too_long = "a".repeat(64);
23087        s.placement.clusters = vec![too_long.clone()];
23088        let err = s.validate().unwrap_err();
23089        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
23090            panic!("expected PlacementClusterInvalid");
23091        };
23092        assert_eq!(cluster, too_long);
23093        assert!(
23094            reason.contains("63") && reason.contains("64"),
23095            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
23096        );
23097    }
23098
23099    #[test]
23100    fn placement_cluster_max_length_validates() {
23101        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
23102        // future tightening (e.g. dropping to 62) surfaces here as a
23103        // regression, mirroring `membro_caixa_max_length_validates`
23104        // (3f9d7a0).
23105        let mut s = three_member_spec();
23106        s.placement.clusters = vec!["a".repeat(63)];
23107        s.validate().unwrap();
23108    }
23109
23110    #[test]
23111    fn accepts_canonical_placement_cluster_forms() {
23112        // The DNS-1123 label shapes a caixa author is realistically
23113        // going to write for cluster names: single-word lowercase
23114        // (`rio`), regional hyphen-joined (`mar-east`), single
23115        // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
23116        // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
23117        // Pin every leg so a future tightening that bans (e.g.) digit-
23118        // start identifiers surfaces here.
23119        for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
23120            let mut s = three_member_spec();
23121            s.placement.clusters = vec![form.into()];
23122            s.validate().unwrap_or_else(|e| {
23123                panic!("canonical cluster form {form:?} must validate, got {e:?}")
23124            });
23125        }
23126    }
23127
23128    #[test]
23129    fn placement_cluster_empty_takes_precedence_over_invalid() {
23130        // Order pin: the existing `PlacementClusterEmpty` diagnostic
23131        // (which doesn't try to parse) fires before the new
23132        // `PlacementClusterInvalid` parse-side diagnostic, so an empty
23133        // `:clusters` entry keeps its narrower error message — the new
23134        // gate would also reject `""`, but the empty-string arm is the
23135        // more self-locating diagnostic. Mirrors the
23136        // `membro_caixa_empty_takes_precedence_over_invalid` pin
23137        // (3f9d7a0).
23138        let mut s = three_member_spec();
23139        s.placement.clusters = vec!["rio".into(), String::new()];
23140        let err = s.validate().unwrap_err();
23141        assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
23142    }
23143
23144    #[test]
23145    fn placement_cluster_invalid_fires_before_duplicate_check() {
23146        // Order pin: a malformed-shape `:clusters` entry surfaces *its
23147        // own* diagnostic, even when a later entry would otherwise
23148        // collapse onto a duplicate name. The per-entry shape gate runs
23149        // inline before the duplicate-key insert, parallel to
23150        // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
23151        let mut s = three_member_spec();
23152        s.placement.clusters = vec!["Rio".into(), "rio".into()];
23153        let err = s.validate().unwrap_err();
23154        assert!(
23155            matches!(
23156                err,
23157                AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
23158            ),
23159            "got {err:?}"
23160        );
23161    }
23162
23163    #[test]
23164    fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
23165        // The diagnostic-shape pin: the error names the offending
23166        // `:clusters` value verbatim so the author can grep their
23167        // caixa.lisp without re-running the build, and carries a
23168        // non-empty `reason` naming the specific violation. Same shape
23169        // every typed-shape gate enshrines
23170        // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
23171        // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
23172        let mut s = three_member_spec();
23173        s.placement.clusters = vec!["BAD_CLUSTER".into()];
23174        let err = s.validate().unwrap_err();
23175        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
23176            panic!("expected PlacementClusterInvalid");
23177        };
23178        assert_eq!(cluster, "BAD_CLUSTER");
23179        assert!(
23180            !reason.is_empty(),
23181            "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
23182        );
23183    }
23184
23185    #[test]
23186    fn rejects_sharded_with_empty_clusters() {
23187        // §III.1: Sharded uses :clusters as the shard pool. An empty
23188        // pool means "shard across no clusters" — meaningless, same as
23189        // Replicated with no hosts.
23190        let mut s = three_member_spec();
23191        s.placement.estrategia = PlacementStrategy::Sharded;
23192        s.placement.shard_key = Some("$tenantId".into());
23193        s.placement.clusters = vec![];
23194        assert!(matches!(
23195            s.validate().unwrap_err(),
23196            AplicacaoError::PlacementWithoutClusters {
23197                estrategia: PlacementStrategy::Sharded
23198            }
23199        ));
23200    }
23201
23202    #[test]
23203    fn rejects_sharded_with_empty_shard_key() {
23204        let mut s = three_member_spec();
23205        s.placement.estrategia = PlacementStrategy::Sharded;
23206        s.placement.shard_key = Some(String::new());
23207        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
23208    }
23209
23210    #[test]
23211    fn rejects_shard_key_under_replicated_strategy() {
23212        // The fail-before-pass-after pin: a `:placement (:estrategia
23213        // Replicated :shard-key "tenantId")` manifest carries the
23214        // hash-keyed-distribution slot on a strategy that never consumes
23215        // it. Before the gate the typed slot's value silently vanished
23216        // at the renderer layer (caixa-mesh emits `placement.shardKey`
23217        // verbatim regardless of strategy; the Akka-style cluster-
23218        // sharding reconciler keys off `estrategia == Sharded` and
23219        // ignores the slot otherwise), with no diagnostic. Lifting the
23220        // rejection to a build-time gate makes the
23221        // `shard_key.is_some() == matches!(estrategia, Sharded)`
23222        // partition a structural property of every validated
23223        // [`Placement`].
23224        let mut s = three_member_spec();
23225        // The fixture already uses Replicated; just add a shard-key.
23226        s.placement.shard_key = Some("$tenantId".into());
23227        let err = s.validate().unwrap_err();
23228        let AplicacaoError::ShardKeyOnNonSharded {
23229            estrategia,
23230            shard_key,
23231        } = err
23232        else {
23233            panic!("expected ShardKeyOnNonSharded, got {err:?}");
23234        };
23235        assert_eq!(estrategia, PlacementStrategy::Replicated);
23236        assert_eq!(shard_key, "$tenantId");
23237    }
23238
23239    #[test]
23240    fn rejects_shard_key_under_singlenode_strategy() {
23241        // Peer of the Replicated case above on the SingleNode arm: OTP
23242        // distributed-app takeover (one cluster runs at a time) has no
23243        // hash-keyed routing axis to consume `:shard-key` either, so
23244        // the rejection fires on both non-Sharded arms uniformly.
23245        let mut s = three_member_spec();
23246        s.placement.estrategia = PlacementStrategy::SingleNode;
23247        s.placement.shard_key = Some("$tenantId".into());
23248        let err = s.validate().unwrap_err();
23249        let AplicacaoError::ShardKeyOnNonSharded {
23250            estrategia,
23251            shard_key,
23252        } = err
23253        else {
23254            panic!("expected ShardKeyOnNonSharded, got {err:?}");
23255        };
23256        assert_eq!(estrategia, PlacementStrategy::SingleNode);
23257        assert_eq!(shard_key, "$tenantId");
23258    }
23259
23260    #[test]
23261    fn rejects_empty_shard_key_under_replicated_strategy() {
23262        // The `Some("")` case under non-Sharded is rejected by
23263        // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
23264        // fires before the empty-value gate), not
23265        // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
23266        // the `Sharded` arm). Pin the partition so a future reorder of
23267        // the validate_placement match arms doesn't silently swap which
23268        // diagnostic the author sees — both are author errors, but
23269        // ShardKeyOnNonSharded names which strategy is the actual fix
23270        // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
23271        // only says "pick a non-empty key".
23272        let mut s = three_member_spec();
23273        s.placement.shard_key = Some(String::new());
23274        let err = s.validate().unwrap_err();
23275        assert!(
23276            matches!(
23277                err,
23278                AplicacaoError::ShardKeyOnNonSharded {
23279                    estrategia: PlacementStrategy::Replicated,
23280                    ref shard_key,
23281                } if shard_key.is_empty()
23282            ),
23283            "got {err:?}"
23284        );
23285    }
23286
23287    #[test]
23288    fn replicated_without_shard_key_validates() {
23289        // The complement of the rejection: `:placement :estrategia
23290        // Replicated` with `:shard-key None` is the canonical happy
23291        // path on every existing fixture. Pin the no-shard-key case so
23292        // the new gate doesn't accidentally fire on `None`.
23293        let mut s = three_member_spec();
23294        assert!(matches!(
23295            s.placement.estrategia,
23296            PlacementStrategy::Replicated
23297        ));
23298        s.placement.shard_key = None;
23299        s.validate().unwrap();
23300    }
23301
23302    #[test]
23303    fn singlenode_without_shard_key_validates() {
23304        // Peer of the Replicated no-shard-key case on the SingleNode
23305        // arm — both non-Sharded strategies must validate cleanly when
23306        // the slot is omitted.
23307        let mut s = three_member_spec();
23308        s.placement.estrategia = PlacementStrategy::SingleNode;
23309        s.placement.shard_key = None;
23310        s.validate().unwrap();
23311    }
23312
23313    #[test]
23314    fn shard_key_on_non_sharded_ctor_matches_struct_literal_wrap() {
23315        // Fail-before-pass-after pin on
23316        // [`AplicacaoError::shard_key_on_non_sharded`]'s
23317        // substrate-primitive posture: byte-identity + `Display`
23318        // byte-string parity against the open-coded struct-literal
23319        // for every non-`Sharded` [`PlacementStrategy`] arm across a
23320        // representative `:shard-key` value the sole in-crate wire-up
23321        // site (`AplicacaoSpec::validate_placement`'s
23322        // `PlacementStrategy::Replicated | PlacementStrategy::SingleNode`
23323        // arm) emits. Any wrapper-side silent normalization, `.into()`
23324        // divergence, or accidental field rebrand on the ctor body
23325        // surfaces at assert time rather than at a downstream consumer
23326        // that reads `err.estrategia` / `err.shard_key` back and gets a
23327        // different value than the one it stored.
23328        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
23329            let placement = Placement {
23330                estrategia,
23331                clusters: vec!["cluster-a".to_string()],
23332                shard_key: Some("$tenantId".to_string()),
23333                affinity: None,
23334            };
23335            let via_ctor = AplicacaoError::shard_key_on_non_sharded(&placement, "$tenantId");
23336            let via_literal = AplicacaoError::ShardKeyOnNonSharded {
23337                estrategia,
23338                shard_key: "$tenantId".to_string(),
23339            };
23340            assert_eq!(
23341                via_ctor, via_literal,
23342                "shard_key_on_non_sharded(&placement, k) must byte-equal the \
23343                 open-coded ShardKeyOnNonSharded struct-literal for {estrategia:?}"
23344            );
23345            assert_eq!(
23346                via_ctor.to_string(),
23347                via_literal.to_string(),
23348                "Display byte-string must byte-equal the open-coded struct-literal \
23349                 for {estrategia:?}"
23350            );
23351        }
23352    }
23353
23354    #[test]
23355    fn shard_key_on_non_sharded_routes_estrategia_through_placement_accessor() {
23356        // Boundary-sweep pin on the ctor's substrate-primitive
23357        // projection: the `estrategia` slot is stored verbatim from
23358        // [`Placement::estrategia`] on every arm the accessor can
23359        // return, and the `shard_key` slot preserves the caller-side
23360        // `&str` byte-for-byte. Sweeping every arm of
23361        // [`PlacementStrategy::ALL`] (including the `Sharded` arm the
23362        // current caller never reaches, since the ctor is a substrate
23363        // primitive independent of any single caller's dispatch gate)
23364        // catches a future silent field-rebrand or per-arm ctor
23365        // divergence at caixa-core build time rather than at a
23366        // downstream consumer far from the wire-up commit.
23367        for &estrategia in PlacementStrategy::ALL {
23368            let placement = Placement {
23369                estrategia,
23370                clusters: vec!["cluster-a".to_string()],
23371                shard_key: Some("$tenantId".to_string()),
23372                affinity: None,
23373            };
23374            let err = AplicacaoError::shard_key_on_non_sharded(&placement, "$tenantId");
23375            let AplicacaoError::ShardKeyOnNonSharded {
23376                estrategia: stored_estrategia,
23377                shard_key: stored_shard_key,
23378            } = err
23379            else {
23380                panic!(
23381                    "shard_key_on_non_sharded must construct ShardKeyOnNonSharded for {estrategia:?}"
23382                );
23383            };
23384            assert_eq!(
23385                stored_estrategia, estrategia,
23386                "estrategia slot must round-trip verbatim through Placement::estrategia \
23387                 for {estrategia:?}"
23388            );
23389            assert_eq!(
23390                stored_shard_key, "$tenantId",
23391                "shard_key slot must preserve the caller-side &str byte-for-byte \
23392                 for {estrategia:?}"
23393            );
23394        }
23395    }
23396
23397    #[test]
23398    fn validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor() {
23399        // End-to-end pin: the sole in-crate wire-up site
23400        // (`AplicacaoSpec::validate_placement`'s non-`Sharded`-arm
23401        // refusal) routes through
23402        // [`AplicacaoError::shard_key_on_non_sharded`] and the observed
23403        // `Err` byte-equals the ctor's output on the same non-`Sharded`
23404        // fixture. A future silent de-lift of the wire-up back to the
23405        // open-coded struct-literal trips this test at caixa-core build
23406        // time rather than at a downstream diagnostic consumer far from
23407        // the wire-up commit.
23408        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
23409            let mut s = three_member_spec();
23410            s.placement.estrategia = estrategia;
23411            s.placement.shard_key = Some("$tenantId".to_string());
23412            let observed = s.validate().unwrap_err();
23413            let expected = AplicacaoError::shard_key_on_non_sharded(&s.placement, "$tenantId");
23414            assert_eq!(
23415                observed, expected,
23416                "validate_placement's non-Sharded-arm Err must byte-equal \
23417                 shard_key_on_non_sharded(&placement, k) for {estrategia:?}"
23418            );
23419            assert_eq!(
23420                observed.to_string(),
23421                expected.to_string(),
23422                "Display byte-string parity for {estrategia:?}"
23423            );
23424        }
23425    }
23426
23427    fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
23428        // Fixture builder for the `:placement :shard-key` shape gate
23429        // tests: a three-member Aplicacao on the `Sharded` strategy
23430        // with the supplied `:shard-key` slot. Co-locates the
23431        // arm-construction so every test below carries one line of
23432        // setup (the offending `:shard-key` value) and the assertion.
23433        let mut s = three_member_spec();
23434        s.placement.estrategia = PlacementStrategy::Sharded;
23435        s.placement.shard_key = Some(key.into());
23436        s
23437    }
23438
23439    #[test]
23440    fn rejects_shard_key_with_embedded_space() {
23441        // The canonical paste-from-aligned-doc footgun:
23442        // `:shard-key "$tenant Id"` — the Akka-style entity-id
23443        // extractor reads the slot as a single-token reference, and an
23444        // embedded space breaks the token boundary at the runtime
23445        // hash-extractor pass with no diagnostic naming the offending
23446        // entry.
23447        let s = sharded_spec_with_key("$tenant Id");
23448        let err = s.validate().unwrap_err();
23449        assert!(
23450            matches!(
23451                err,
23452                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
23453                    if shard_key == "$tenant Id" && reason.contains("space")
23454            ),
23455            "got {err:?}"
23456        );
23457    }
23458
23459    #[test]
23460    fn rejects_shard_key_with_leading_space() {
23461        // Leading-space arm of the embedded-whitespace footgun — the
23462        // paste-from-aligned-doc / paste-from-CSV-cell variant where
23463        // the leading column-padding leaked into the slot.
23464        let s = sharded_spec_with_key(" $tenantId");
23465        let err = s.validate().unwrap_err();
23466        assert!(
23467            matches!(
23468                err,
23469                AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
23470                    if shard_key == " $tenantId"
23471            ),
23472            "got {err:?}"
23473        );
23474    }
23475
23476    #[test]
23477    fn rejects_shard_key_with_trailing_newline() {
23478        // The canonical paste-from-shell-heredoc footgun — every
23479        // `<<EOF` heredoc terminator paste leaves a trailing newline
23480        // the YAML emitter then folds away inconsistently across
23481        // emitter implementations.
23482        let s = sharded_spec_with_key("$tenantId\n");
23483        let err = s.validate().unwrap_err();
23484        assert!(
23485            matches!(
23486                err,
23487                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
23488                    if shard_key == "$tenantId\n" && reason.contains("0x0a")
23489            ),
23490            "got {err:?}"
23491        );
23492    }
23493
23494    #[test]
23495    fn rejects_shard_key_with_embedded_tab() {
23496        // The paste-from-aligned-doc tab-stop variant — tabs land
23497        // alongside spaces in copy-paste from formatted columns.
23498        let s = sharded_spec_with_key("$tenant\tId");
23499        let err = s.validate().unwrap_err();
23500        assert!(
23501            matches!(
23502                err,
23503                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
23504                    if shard_key == "$tenant\tId" && reason.contains("tab")
23505            ),
23506            "got {err:?}"
23507        );
23508    }
23509
23510    #[test]
23511    fn rejects_shard_key_with_control_character() {
23512        // The paste-from-binary / paste-from-screen-cleared-terminal
23513        // footgun — an embedded `\x01` (SOH) byte that some YAML
23514        // emitters silently strip and others escape as ``,
23515        // breaking round-trip across emitter implementations.
23516        let s = sharded_spec_with_key("$tenant\u{0001}Id");
23517        let err = s.validate().unwrap_err();
23518        assert!(
23519            matches!(
23520                err,
23521                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
23522                    if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
23523            ),
23524            "got {err:?}"
23525        );
23526    }
23527
23528    #[test]
23529    fn rejects_shard_key_with_non_ascii() {
23530        // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
23531        // footgun — non-ASCII bytes normalize differently between the
23532        // caixa-mesh-side YAML emitter and the in-cluster reconciler's
23533        // YAML parser, the same entity ID can silently map to two
23534        // distinct shards on a re-render.
23535        let s = sharded_spec_with_key("$tenàntId");
23536        let err = s.validate().unwrap_err();
23537        assert!(
23538            matches!(
23539                err,
23540                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
23541                    if shard_key == "$tenàntId" && reason.contains("non-ASCII")
23542            ),
23543            "got {err:?}"
23544        );
23545    }
23546
23547    #[test]
23548    fn rejects_shard_key_too_long() {
23549        // Length cap pin: 64 bytes — one byte over the
23550        // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
23551        // here is a paste-from-doc multi-line blob landing in
23552        // `:shard-key` instead of a single-token extractor expression.
23553        let too_long = "a".repeat(64);
23554        let s = sharded_spec_with_key(&too_long);
23555        let err = s.validate().unwrap_err();
23556        let AplicacaoError::ShardKeyInvalid {
23557            ref shard_key,
23558            ref reason,
23559        } = err
23560        else {
23561            panic!("expected ShardKeyInvalid, got {err:?}");
23562        };
23563        assert_eq!(shard_key, &too_long);
23564        assert!(
23565            reason.contains("63") && reason.contains("64"),
23566            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
23567        );
23568    }
23569
23570    #[test]
23571    fn shard_key_max_length_validates() {
23572        // Boundary pin: 63 bytes exactly — the
23573        // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
23574        // dropping to 62) surfaces here as a regression, mirroring
23575        // `placement_cluster_max_length_validates` /
23576        // `placement_affinity_max_length_validates` on the peer
23577        // identifier-shaped slots.
23578        let s = sharded_spec_with_key(&"a".repeat(63));
23579        s.validate().unwrap();
23580    }
23581
23582    #[test]
23583    fn accepts_canonical_shard_key_forms() {
23584        // The Akka-style entity-id extractor shapes a caixa author is
23585        // realistically going to write — pin every leg so a future
23586        // tightening that bans (e.g.) the `${...}` interpolation
23587        // variant or the `metadata.<field>` JSONPath form surfaces
23588        // here as a regression. The canonical forms span:
23589        //
23590        //   - bare property name (`tenantId`, `customerId`)
23591        //   - Akka `ExtractEntityId` placeholder (`$tenantId`)
23592        //   - JSONPath-style nested reference (`metadata.tenantId`,
23593        //     `$.user.id`)
23594        //   - interpolation-style template (`${tenant}`)
23595        //   - snake_case property name (`customer_id`)
23596        //   - kebab-case property name (`customer-id` — accepted
23597        //     because the slot is a printable-ASCII single-token
23598        //     reference, not a DNS-1123 label like
23599        //     `:placement :affinity` / `:clusters`)
23600        //   - single character (`a`, `$` — boundary)
23601        for form in [
23602            "tenantId",
23603            "customerId",
23604            "$tenantId",
23605            "metadata.tenantId",
23606            "$.user.id",
23607            "${tenant}",
23608            "customer_id",
23609            "customer-id",
23610            "a",
23611            "$",
23612        ] {
23613            let s = sharded_spec_with_key(form);
23614            s.validate().unwrap_or_else(|e| {
23615                panic!("canonical shard-key form {form:?} must validate, got {e:?}")
23616            });
23617        }
23618    }
23619
23620    #[test]
23621    fn shard_key_empty_takes_precedence_over_invalid() {
23622        // Order pin: the existing `ShardedKeyEmpty` diagnostic
23623        // (reserved for the `Sharded` `Some("")` arm) fires before the
23624        // new `ShardKeyInvalid` parse-side diagnostic, so an empty
23625        // `:shard-key` keeps its narrower error message — the new gate
23626        // would also reject `""` defensively, but the empty-string arm
23627        // is the more self-locating diagnostic. Mirrors the
23628        // `placement_cluster_empty_takes_precedence_over_invalid` pin
23629        // on the peer identifier-shaped slot.
23630        let s = sharded_spec_with_key("");
23631        let err = s.validate().unwrap_err();
23632        assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
23633    }
23634
23635    #[test]
23636    fn shard_key_invalid_diagnostic_carries_offending_value() {
23637        // The diagnostic-shape pin: the error names the offending
23638        // `:shard-key` value verbatim so the author can grep their
23639        // caixa.lisp without re-running the build, and carries a
23640        // parser-shaped `reason:` naming the specific violation —
23641        // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
23642        // on the peer identifier-shaped slot.
23643        let s = sharded_spec_with_key("$tenant Id");
23644        let err = s.validate().unwrap_err();
23645        let AplicacaoError::ShardKeyInvalid {
23646            ref shard_key,
23647            ref reason,
23648        } = err
23649        else {
23650            panic!("expected ShardKeyInvalid, got {err:?}");
23651        };
23652        assert_eq!(shard_key, "$tenant Id");
23653        assert!(
23654            !reason.is_empty(),
23655            "reason must name the specific violation, got empty string"
23656        );
23657    }
23658
23659    #[test]
23660    fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
23661        // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
23662        // `:shard-key` carried on non-Sharded strategies) fires before
23663        // the shape gate, so a malformed `:shard-key` carried on (e.g.)
23664        // a `Replicated` strategy surfaces the more self-locating
23665        // strategy-mismatch diagnostic (naming the actual fix — drop
23666        // the slot, or switch to Sharded) rather than the shape
23667        // diagnostic. The strategy-mismatch arm is the more actionable
23668        // diagnostic: a malformed shard-key on Replicated is "you
23669        // shouldn't have a :shard-key here at all", not "your
23670        // :shard-key value is malformed".
23671        let mut s = three_member_spec();
23672        // Replicated is the default fixture strategy.
23673        s.placement.shard_key = Some("$tenant Id".into());
23674        let err = s.validate().unwrap_err();
23675        assert!(
23676            matches!(
23677                err,
23678                AplicacaoError::ShardKeyOnNonSharded {
23679                    estrategia: PlacementStrategy::Replicated,
23680                    ..
23681                }
23682            ),
23683            "got {err:?}"
23684        );
23685    }
23686
23687    #[test]
23688    fn rejects_empty_affinity_hint() {
23689        let mut s = three_member_spec();
23690        s.placement.affinity = Some(String::new());
23691        assert_eq!(
23692            s.validate().unwrap_err(),
23693            AplicacaoError::PlacementAffinityEmpty
23694        );
23695    }
23696
23697    #[test]
23698    fn placement_without_affinity_validates() {
23699        // Omitting :affinity is fine — the placement engine falls back
23700        // to the default heuristic. Pin the no-hint case so the
23701        // affinity-empty rejection doesn't accidentally fire on `None`.
23702        let mut s = three_member_spec();
23703        s.placement.affinity = None;
23704        s.validate().unwrap();
23705    }
23706
23707    #[test]
23708    fn rejects_placement_affinity_with_uppercase() {
23709        // The canonical "I copied the ADR's display name verbatim" typo
23710        // — placement hints land verbatim in K8s label-selector
23711        // territory, where the apiserver enforces the DNS-1123 label
23712        // rule (lowercase-only) on every identity-keyed admission axis.
23713        // Mirrors `rejects_placement_cluster_with_uppercase` on the
23714        // sibling slot.
23715        let mut s = three_member_spec();
23716        s.placement.affinity = Some("DataLocality".into());
23717        let err = s.validate().unwrap_err();
23718        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
23719            panic!("expected PlacementAffinityInvalid, got other variant");
23720        };
23721        assert_eq!(affinity, "DataLocality");
23722        assert!(
23723            reason.contains("uppercase"),
23724            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
23725        );
23726        assert!(
23727            reason.contains("\"datalocality\""),
23728            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
23729        );
23730    }
23731
23732    #[test]
23733    fn rejects_placement_affinity_with_underscore() {
23734        // The canonical "I'm thinking of an env var / Python identifier"
23735        // leak — `_` is forbidden by every DNS-1123 label schema. Same
23736        // shape as `rejects_placement_cluster_with_underscore` on the
23737        // sibling slot.
23738        let mut s = three_member_spec();
23739        s.placement.affinity = Some("data_locality".into());
23740        let err = s.validate().unwrap_err();
23741        assert!(
23742            matches!(
23743                err,
23744                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
23745                    if affinity == "data_locality" && reason.contains('_')
23746            ),
23747            "got {err:?}"
23748        );
23749    }
23750
23751    #[test]
23752    fn rejects_placement_affinity_with_dot() {
23753        // A `:placement :affinity` value is a single DNS-1123 *label*
23754        // (it lands as a K8s label value selector key), not a subdomain.
23755        // The "I want to namespace my hint with `.`" intent is expressed
23756        // via `-` (`data-locality-east`).
23757        let mut s = three_member_spec();
23758        s.placement.affinity = Some("data.locality".into());
23759        let err = s.validate().unwrap_err();
23760        assert!(
23761            matches!(
23762                err,
23763                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
23764                    if affinity == "data.locality" && reason.contains('.')
23765            ),
23766            "got {err:?}"
23767        );
23768    }
23769
23770    #[test]
23771    fn rejects_placement_affinity_with_unicode() {
23772        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
23773        // before it reaches K8s. The byte-by-byte ASCII validity check
23774        // rejects multi-byte UTF-8 sequences by the first byte that
23775        // fails `[a-z0-9-]`.
23776        let mut s = three_member_spec();
23777        s.placement.affinity = Some("data-localité".into());
23778        let err = s.validate().unwrap_err();
23779        assert!(
23780            matches!(
23781                err,
23782                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
23783                    if affinity == "data-localité"
23784            ),
23785            "got {err:?}"
23786        );
23787    }
23788
23789    #[test]
23790    fn rejects_placement_affinity_with_leading_hyphen() {
23791        // DNS-1123 boundary rule: labels must start with an
23792        // alphanumeric. Pin separately from the trailing-hyphen arm so
23793        // a future relaxation that only checks one boundary surfaces
23794        // here as a regression (parallel to
23795        // `rejects_placement_cluster_with_leading_hyphen`).
23796        let mut s = three_member_spec();
23797        s.placement.affinity = Some("-data-locality".into());
23798        let err = s.validate().unwrap_err();
23799        assert!(
23800            matches!(
23801                err,
23802                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
23803                    if affinity == "-data-locality" && reason.contains("start and end")
23804            ),
23805            "got {err:?}"
23806        );
23807    }
23808
23809    #[test]
23810    fn rejects_placement_affinity_with_trailing_hyphen() {
23811        // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
23812        // ends are covered against a future relaxation.
23813        let mut s = three_member_spec();
23814        s.placement.affinity = Some("data-locality-".into());
23815        let err = s.validate().unwrap_err();
23816        assert!(
23817            matches!(
23818                err,
23819                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
23820                    if affinity == "data-locality-"
23821            ),
23822            "got {err:?}"
23823        );
23824    }
23825
23826    #[test]
23827    fn rejects_placement_affinity_with_whitespace() {
23828        // Whitespace is the canonical "I pasted from a sketch / doc"
23829        // footgun. The apiserver rejects every label-selector value
23830        // carrying whitespace.
23831        let mut s = three_member_spec();
23832        s.placement.affinity = Some("data locality".into());
23833        let err = s.validate().unwrap_err();
23834        assert!(
23835            matches!(
23836                err,
23837                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
23838                    if affinity == "data locality"
23839            ),
23840            "got {err:?}"
23841        );
23842    }
23843
23844    #[test]
23845    fn rejects_placement_affinity_too_long() {
23846        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
23847        // pin. The diagnostic names both the cap (63) and the actual
23848        // length so the author can shorten in one edit. Mirrors
23849        // `rejects_placement_cluster_too_long`.
23850        let mut s = three_member_spec();
23851        let too_long = "a".repeat(64);
23852        s.placement.affinity = Some(too_long.clone());
23853        let err = s.validate().unwrap_err();
23854        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
23855            panic!("expected PlacementAffinityInvalid");
23856        };
23857        assert_eq!(affinity, too_long);
23858        assert!(
23859            reason.contains("63") && reason.contains("64"),
23860            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
23861        );
23862    }
23863
23864    #[test]
23865    fn placement_affinity_max_length_validates() {
23866        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
23867        // future tightening (e.g. dropping to 62) surfaces here as a
23868        // regression, mirroring `placement_cluster_max_length_validates`.
23869        let mut s = three_member_spec();
23870        s.placement.affinity = Some("a".repeat(63));
23871        s.validate().unwrap();
23872    }
23873
23874    #[test]
23875    fn accepts_canonical_placement_affinity_forms() {
23876        // The DNS-1123 label shapes a caixa author is realistically
23877        // going to write for placement hints: the M3 canonical examples
23878        // (`data-locality`, `low-latency`, `anti-affinity`), the
23879        // single-token form (`affinity`), the single-character boundary
23880        // (`a`), the digit-start (DNS-1123 allows this, unlike
23881        // DNS-1035), and a regional-suffixed form. Pin every leg so a
23882        // future tightening that bans (e.g.) digit-start identifiers
23883        // surfaces here.
23884        for form in [
23885            "data-locality",
23886            "low-latency",
23887            "anti-affinity",
23888            "affinity",
23889            "a",
23890            "3-tier",
23891            "locality-east",
23892        ] {
23893            let mut s = three_member_spec();
23894            s.placement.affinity = Some(form.into());
23895            s.validate().unwrap_or_else(|e| {
23896                panic!("canonical affinity form {form:?} must validate, got {e:?}")
23897            });
23898        }
23899    }
23900
23901    #[test]
23902    fn placement_affinity_empty_takes_precedence_over_invalid() {
23903        // Order pin: the existing `PlacementAffinityEmpty` diagnostic
23904        // (which doesn't try to parse) fires before the new
23905        // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
23906        // `:affinity` keeps its narrower error message — the new gate
23907        // would also reject `""`, but the empty-string arm is the more
23908        // self-locating diagnostic. Mirrors the
23909        // `placement_cluster_empty_takes_precedence_over_invalid` pin.
23910        let mut s = three_member_spec();
23911        s.placement.affinity = Some(String::new());
23912        let err = s.validate().unwrap_err();
23913        assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
23914    }
23915
23916    #[test]
23917    fn placement_affinity_invalid_diagnostic_carries_offending_value() {
23918        // The diagnostic shape pin: every rejection carries the offending
23919        // `affinity:` verbatim plus a parser-shaped `reason:` so the
23920        // author can grep their caixa.lisp for `:affinity "<hint>"` and
23921        // fix it in one edit. Mirrors the
23922        // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
23923        // pin on the sibling slot.
23924        let mut s = three_member_spec();
23925        s.placement.affinity = Some("Data_Locality".into());
23926        let err = s.validate().unwrap_err();
23927        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
23928            panic!("expected PlacementAffinityInvalid");
23929        };
23930        assert_eq!(affinity, "Data_Locality");
23931        assert!(
23932            !reason.is_empty(),
23933            "diagnostic reason must not be empty (got: {reason:?})"
23934        );
23935    }
23936
23937    #[test]
23938    fn singlenode_with_takeover_candidates_validates() {
23939        // OTP distributed-application convention (MESH-COMPOSITION
23940        // §II.1): SingleNode runs on one cluster at a time but the
23941        // :clusters list enumerates the takeover candidates. Multiple
23942        // entries are not a contradiction — they are the failover pool.
23943        let mut s = three_member_spec();
23944        s.placement.estrategia = PlacementStrategy::SingleNode;
23945        s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
23946        s.validate().unwrap();
23947    }
23948
23949    // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
23950
23951    #[test]
23952    fn mesh_policy_default_is_empty() {
23953        // The Default impl carries None on every axis — the typed
23954        // analog of an unset `:politicas (())` slot. Renderers that
23955        // overlay the policy onto a cluster artifact key off this
23956        // predicate to skip the slot entirely; pinning so a future
23957        // axis added to MeshPolicy can't silently break the contract
23958        // (a new field whose Default is non-None would flip is_empty
23959        // to false on every existing caixa, surfacing here).
23960        assert!(MeshPolicy::default().is_empty());
23961    }
23962
23963    #[test]
23964    fn mesh_policy_with_only_timeout_is_not_empty() {
23965        let p = MeshPolicy {
23966            timeout: Some(Duration::from_secs(30)),
23967            ..Default::default()
23968        };
23969        assert!(!p.is_empty());
23970    }
23971
23972    #[test]
23973    fn mesh_policy_with_only_retries_is_not_empty() {
23974        let p = MeshPolicy {
23975            retries: Some(3),
23976            ..Default::default()
23977        };
23978        assert!(!p.is_empty());
23979    }
23980
23981    #[test]
23982    fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
23983        let p = MeshPolicy {
23984            circuit_breaker: Some(CircuitBreaker {
23985                max_failures: 5,
23986                window: Duration::from_secs(60),
23987            }),
23988            ..Default::default()
23989        };
23990        assert!(!p.is_empty());
23991    }
23992
23993    #[test]
23994    fn mesh_policy_with_only_mtls_required_is_not_empty() {
23995        // Even `mtls_required: Some(false)` (an explicit opt-out) is
23996        // not empty — the author *named* the axis, the renderer needs
23997        // to honor that vs. fall back to the cluster default.
23998        let p = MeshPolicy {
23999            mtls_required: Some(false),
24000            ..Default::default()
24001        };
24002        assert!(!p.is_empty());
24003    }
24004
24005    #[test]
24006    fn mesh_policy_with_only_rate_limit_is_not_empty() {
24007        let p = MeshPolicy {
24008            rate_limit: Some(RateLimit {
24009                rate: 100,
24010                window: Duration::from_secs(1),
24011            }),
24012            ..Default::default()
24013        };
24014        assert!(!p.is_empty());
24015    }
24016
24017    #[test]
24018    fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
24019        // The three-member happy-path fixture sets timeout + retries +
24020        // mtls_required — every populated axis must read non-empty.
24021        // Pin the round-trip so the M3.x per-:politicas emitter (the
24022        // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
24023        // on is_empty() to decide whether to emit at all without
24024        // re-deriving the contract from inline field probes.
24025        assert!(!three_member_spec().politicas.is_empty());
24026    }
24027
24028    // ── shared duration codec: cross-slot integer-magnitude gate ──
24029    //
24030    // The integer-magnitude discipline applied to
24031    // `supervisor::duration_codec::parse` lifts onto every typed slot
24032    // that routes through the shared codec — `MeshPolicy::timeout`
24033    // (`:politicas :timeout`) and `CircuitBreaker::window`
24034    // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
24035    // These cross-slot tests pin that the gate fires at the serde
24036    // layer for both typed slots, not just for the supervisor side.
24037
24038    #[test]
24039    fn policy_timeout_serde_rejects_fractional_seconds() {
24040        // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
24041        // so the shared codec's integer-magnitude gate applies on
24042        // deserialize. `"1.5s"` previously parsed to 1500ms and round-
24043        // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
24044        // deserialize with the canonical-form diagnostic naming the
24045        // offending `"1.5"` and the remediation `"1500ms"`.
24046        let payload = r#"{"timeout":"1.5s"}"#;
24047        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24048        let msg = err.to_string();
24049        assert!(
24050            msg.contains("not a non-negative integer"),
24051            "expected integer-magnitude diagnostic in {msg:?}"
24052        );
24053        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
24054        assert!(
24055            msg.contains("\"1500ms\""),
24056            "missing canonical-form remediation in {msg:?}"
24057        );
24058    }
24059
24060    #[test]
24061    fn policy_timeout_serde_rejects_leading_plus_sign() {
24062        // Pin the leading-`+` arm cross-slot — the prior f64 parser
24063        // accepted `"+30s"` silently and round-tripped to `"30s"`.
24064        let payload = r#"{"timeout":"+30s"}"#;
24065        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24066        let msg = err.to_string();
24067        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
24068    }
24069
24070    #[test]
24071    fn circuit_breaker_window_serde_rejects_fractional_minutes() {
24072        // `CircuitBreaker::window` uses `with =
24073        // "supervisor::duration_codec_required"` (the required-Duration
24074        // variant that delegates to the same shared parser). `"0.5m"`
24075        // parsed to 30s and round-tripped to `"30s"` on next emit —
24076        // DRIFT closed.
24077        let payload = format!(
24078            r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
24079            max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
24080            window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
24081        );
24082        let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
24083        let msg = err.to_string();
24084        assert!(
24085            msg.contains("not a non-negative integer"),
24086            "expected integer-magnitude diagnostic in {msg:?}"
24087        );
24088        assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
24089        assert!(
24090            msg.contains("\"30s\""),
24091            "missing canonical-form remediation in {msg:?}"
24092        );
24093    }
24094
24095    #[test]
24096    fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
24097        // Pin the happy-path on the cross-slot side: every canonical
24098        // author shape `render` ever emits parses cleanly through the
24099        // shared codec on the `CircuitBreaker` slot. The
24100        // codec's accepted set (post-gate) is exactly its emitted set
24101        // for the integer-magnitude class.
24102        for window_lit in ["30s", "500ms", "2m", "1h"] {
24103            let payload = format!(
24104                r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
24105                max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
24106                window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
24107            );
24108            let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
24109                panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
24110            });
24111            assert_eq!(cb.max_failures, 5);
24112        }
24113    }
24114
24115    // ── rate_limit_codec: integer-magnitude gate ──
24116    //
24117    // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
24118    // / 737a676 / d53c922 trajectory landed on every typed-duration /
24119    // typed-byte-size codec in caixa-core lifts onto the fifth typed
24120    // codec — `rate_limit_codec` — through the digit-only magnitude
24121    // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
24122    // These tests pin the gate at the serde layer for `:politicas
24123    // :rate-limit` (the only typed slot the codec backs), and at the
24124    // codec-internal `parse` layer for the canonical positive cases.
24125
24126    #[test]
24127    fn rate_limit_serde_rejects_fractional_rate() {
24128        // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
24129        // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
24130        // wording, which didn't name the canonical-form remediation or
24131        // the round-trip drift the next emit would produce. Now refused
24132        // at deserialize with the canonical-form diagnostic naming the
24133        // offending `"1.5"` magnitude and the round-trip drift wording.
24134        let payload = r#"{"rateLimit":"1.5/s"}"#;
24135        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24136        let msg = err.to_string();
24137        assert!(
24138            msg.contains("not a non-negative integer"),
24139            "expected integer-magnitude diagnostic in {msg:?}"
24140        );
24141        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
24142        assert!(
24143            msg.contains("THEORY.md"),
24144            "missing render-determinism contract citation in {msg:?}"
24145        );
24146    }
24147
24148    #[test]
24149    fn rate_limit_serde_rejects_leading_plus_sign() {
24150        // `u32::from_str("+100")` returns `Ok(100)` (Rust's
24151        // permissive-`+` parse), so `"+100/s"` silently parsed to
24152        // `RateLimit { 100, 1s }` and round-tripped through `render` to
24153        // `"100/s"` — a *different* canonical string on the next emit,
24154        // breaking the THEORY.md Part V render-determinism contract
24155        // exactly the way the peer duration codecs' `"+30s"` case did.
24156        // This is the load-bearing class the digit-only gate closes
24157        // beyond what `u32::from_str`'s strictness covers on its own.
24158        let payload = r#"{"rateLimit":"+100/s"}"#;
24159        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24160        let msg = err.to_string();
24161        assert!(
24162            msg.contains("not a non-negative integer"),
24163            "expected integer-magnitude diagnostic in {msg:?}"
24164        );
24165        assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
24166    }
24167
24168    #[test]
24169    fn rate_limit_serde_rejects_leading_minus_sign() {
24170        // The signed-negative arm: `"-1/s"` lands on the
24171        // non-canonical-but-numeric branch via the `i64` fallback (the
24172        // `f64` parse also succeeds), surfacing the canonical-form
24173        // diagnostic. Replaces the prior value-laundered "not a u32"
24174        // wording with the unified diagnostic across signs.
24175        let payload = r#"{"rateLimit":"-1/s"}"#;
24176        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24177        let msg = err.to_string();
24178        assert!(
24179            msg.contains("not a non-negative integer"),
24180            "expected integer-magnitude diagnostic in {msg:?}"
24181        );
24182        assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
24183    }
24184
24185    #[test]
24186    fn rate_limit_serde_rejects_decimal_shaped_integer() {
24187        // `"100.0/s"` is integer-valued numerically but not in the
24188        // codec's accepted set — `render` emits `"100/s"`, so the
24189        // round-trip would drift. Lifted to the canonical-form
24190        // diagnostic peer with the duration codec's `"1.0s"` case
24191        // (1c55a2a).
24192        let payload = r#"{"rateLimit":"100.0/s"}"#;
24193        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24194        let msg = err.to_string();
24195        assert!(
24196            msg.contains("not a non-negative integer"),
24197            "expected integer-magnitude diagnostic in {msg:?}"
24198        );
24199        assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
24200    }
24201
24202    #[test]
24203    fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
24204        // Non-numeric, non-digit-only input lands on the existing
24205        // narrower `"not a u32"` arm (preserved for diagnostic-shape
24206        // stability on the parser-shape footgun case). Pin this so a
24207        // future relaxation of the numeric-fallback predicate doesn't
24208        // silently collapse garbage onto the canonical-form arm — same
24209        // partition the peer duration codecs draw between
24210        // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
24211        let payload = r#"{"rateLimit":"abc/s"}"#;
24212        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24213        let msg = err.to_string();
24214        assert!(
24215            msg.contains("not a u32"),
24216            "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
24217        );
24218        assert!(
24219            !msg.contains("not a non-negative integer"),
24220            "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
24221        );
24222    }
24223
24224    #[test]
24225    fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
24226        // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
24227        // u32's range. The digit-only gate passes; `u32::from_str`
24228        // fails on overflow. Surface that with the overflow-shaped
24229        // diagnostic naming the offending magnitude verbatim, peer
24230        // with `supervisor::duration_codec`'s overflow arm. Pinning
24231        // the wording so a future refactor doesn't silently collapse
24232        // overflow onto the canonical-form arm.
24233        let payload = r#"{"rateLimit":"4294967296/s"}"#;
24234        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24235        let msg = err.to_string();
24236        assert!(
24237            msg.contains("overflows u32"),
24238            "expected overflow diagnostic in {msg:?}"
24239        );
24240        assert!(
24241            msg.contains("\"4294967296\""),
24242            "missing offending magnitude in {msg:?}"
24243        );
24244    }
24245
24246    #[test]
24247    fn rate_limit_serde_rejects_leading_zero_magnitude() {
24248        // `"0100/s"` is digit-only, so the existing
24249        // non-digit-only / sign / fractional arm doesn't catch it —
24250        // `u32::from_str("0100")` returns `Ok(100)`, so before this
24251        // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
24252        // round-tripped through `render` to `"100/s"` — a *different*
24253        // canonical string on the next emit, breaking the THEORY.md
24254        // Part V render-determinism contract exactly the way the
24255        // peer `"+100/s"` case did before the leading-`+` arm landed.
24256        // This is the load-bearing class the leading-zero gate closes
24257        // beyond what the existing digit-only / sign / fractional
24258        // gates cover, and the peer arm to the leading-`+` test
24259        // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
24260        // canonical-form-drift axis.
24261        let payload = r#"{"rateLimit":"0100/s"}"#;
24262        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24263        let msg = err.to_string();
24264        assert!(
24265            msg.contains("non-canonical leading zero"),
24266            "expected leading-zero diagnostic in {msg:?}"
24267        );
24268        assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
24269        assert!(
24270            msg.contains("THEORY.md"),
24271            "missing render-determinism contract citation in {msg:?}"
24272        );
24273    }
24274
24275    #[test]
24276    fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
24277        // `"00/s"` is the degenerate leading-zero case — every byte
24278        // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
24279        // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
24280        // a *different* canonical string, same render-determinism
24281        // violation. The single-byte `"0/s"` itself is in the
24282        // accepted set (round-trips losslessly through `render`,
24283        // refused downstream by `PolicyRateLimitZero`); the
24284        // multi-byte `"00/s"` is not. Pins the boundary between the
24285        // accepted single-`0` and the rejected leading-zero class.
24286        let payload = r#"{"rateLimit":"00/s"}"#;
24287        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24288        let msg = err.to_string();
24289        assert!(
24290            msg.contains("non-canonical leading zero"),
24291            "expected leading-zero diagnostic in {msg:?}"
24292        );
24293        assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
24294    }
24295
24296    #[test]
24297    fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
24298        // Cross-window pin — the gate is window-agnostic; the
24299        // leading-zero class is a property of the magnitude, not the
24300        // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
24301        // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
24302        // single-window coverage extended across the three canonical
24303        // windows the codec accepts.
24304        let payload = r#"{"rateLimit":"007/h"}"#;
24305        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24306        let msg = err.to_string();
24307        assert!(
24308            msg.contains("non-canonical leading zero"),
24309            "expected leading-zero diagnostic in {msg:?}"
24310        );
24311        assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
24312    }
24313
24314    #[test]
24315    fn rate_limit_serde_rejects_leading_whitespace() {
24316        // `" 100/s"` — the canonical paste-from-aligned-doc /
24317        // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
24318        // the top-level `s.trim()` silently ate the leading space and
24319        // parsed the value to `RateLimit { 100, 1s }`, which then
24320        // round-tripped through `render` to `"100/s"` (a *different*
24321        // canonical string on the next emit) — the exact
24322        // canonical-form-drift class the leading-`+` / leading-zero
24323        // arms already close, extended to the whitespace byte class.
24324        let payload = r#"{"rateLimit":" 100/s"}"#;
24325        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24326        let msg = err.to_string();
24327        assert!(
24328            msg.contains("contains whitespace byte"),
24329            "expected whitespace diagnostic in {msg:?}"
24330        );
24331        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
24332        assert!(
24333            msg.contains("THEORY.md"),
24334            "missing render-determinism contract citation in {msg:?}"
24335        );
24336    }
24337
24338    #[test]
24339    fn rate_limit_serde_rejects_trailing_whitespace() {
24340        // `"100/s "` — the canonical shell-history / trailing-space
24341        // paste footgun. Before this gate the top-level `s.trim()`
24342        // silently ate the trailing space and parsed to
24343        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
24344        // next emit — same canonical-form drift as the leading-space
24345        // sibling, closed on the same whitespace-byte arm.
24346        let payload = r#"{"rateLimit":"100/s "}"#;
24347        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24348        let msg = err.to_string();
24349        assert!(
24350            msg.contains("contains whitespace byte"),
24351            "expected whitespace diagnostic in {msg:?}"
24352        );
24353        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
24354    }
24355
24356    #[test]
24357    fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
24358        // `"100 / s"` — the canonical typographically-spaced author
24359        // shape (the same idiom every prose reference to a rate limit
24360        // renders as, mistakenly retained when the value is pasted
24361        // into a codec-shaped slot). Before this gate the per-part
24362        // `rate_str.trim()` / `unit.trim()` calls silently ate both
24363        // spaces on either side of `/` and parsed to
24364        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
24365        // codec's *internal* whitespace-tolerance vector, orthogonal
24366        // to the leading / trailing surface but the same canonical-
24367        // form-drift class. Pins the arm as strictly stronger than the
24368        // pre-existing top-level `s.trim()` behavior: it fires on
24369        // whitespace anywhere in the value, not just at the string
24370        // boundary.
24371        let payload = r#"{"rateLimit":"100 / s"}"#;
24372        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24373        let msg = err.to_string();
24374        assert!(
24375            msg.contains("contains whitespace byte"),
24376            "expected whitespace diagnostic in {msg:?}"
24377        );
24378        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
24379    }
24380
24381    #[test]
24382    fn rate_limit_serde_rejects_tab_byte() {
24383        // `"\t100/s"` — the canonical paste-from-indented-doc /
24384        // paste-from-YAML-block-scalar footgun where a tab byte leads
24385        // the magnitude. Pins that the gate covers tab (`0x09`) as
24386        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
24387        // members and both would be silently swallowed by `s.trim()`
24388        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
24389        // space alone to the full ASCII-whitespace set (space `0x20`,
24390        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
24391        // the tab arm as a representative of the non-space members.
24392        let payload = r#"{"rateLimit":"\t100/s"}"#;
24393        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24394        let msg = err.to_string();
24395        assert!(
24396            msg.contains("contains whitespace byte"),
24397            "expected whitespace diagnostic in {msg:?}"
24398        );
24399        assert!(
24400            msg.contains("0x09"),
24401            "missing offending tab byte in {msg:?}"
24402        );
24403    }
24404
24405    // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
24406    //
24407    // Successor to the ASCII-whitespace arm (1ad7755) on
24408    // `rate_limit_codec` — closes the strictly-complementary class the
24409    // byte-scan cannot see, through the lifted
24410    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
24411
24412    #[test]
24413    fn rate_limit_serde_rejects_leading_nbsp() {
24414        // NBSP prefix — paste-from-typography footgun. Byte-scan
24415        // misses, `str::trim` silently strips it, value drifts to
24416        // `"100/s"` on next serialize.
24417        let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
24418        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24419        let msg = err.to_string();
24420        assert!(
24421            msg.contains("non-ASCII Unicode whitespace character"),
24422            "expected non-ASCII whitespace diagnostic in {msg:?}"
24423        );
24424        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
24425    }
24426
24427    #[test]
24428    fn rate_limit_serde_rejects_internal_em_space() {
24429        // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
24430        // paste-from-typography footgun on the `<integer>/<unit>`
24431        // shape.
24432        let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
24433        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24434        let msg = err.to_string();
24435        assert!(
24436            msg.contains("non-ASCII Unicode whitespace character"),
24437            "expected non-ASCII whitespace diagnostic in {msg:?}"
24438        );
24439        assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
24440    }
24441
24442    #[test]
24443    fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
24444        // Positive-control pin: every ASCII-only canonical form the
24445        // renderer emits stays accepted through the new arm.
24446        for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
24447            let payload = format!(r#"{{"rateLimit":{lit}}}"#);
24448            let p: MeshPolicy = serde_json::from_str(&payload)
24449                .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
24450            assert!(p.rate_limit.is_some());
24451        }
24452    }
24453
24454    #[test]
24455    fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
24456        // The boundary case — `"0/s"` is the canonical form
24457        // `render(RateLimit { 0, 1s })` emits, so the codec accepts
24458        // it at the parse layer; the downstream
24459        // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
24460        // `rate == 0` at the typed-validate layer above. Pins the
24461        // partition: the leading-zero gate at the codec layer does
24462        // not poach the rate-zero semantic-validation arm at the
24463        // typed-validate layer above (a future stricter codec must
24464        // not reject `"0/s"` here, or it'd collapse the diagnostic
24465        // partitioning that lets `PolicyRateLimitZero` name the
24466        // offending typed slot).
24467        let payload = r#"{"rateLimit":"0/s"}"#;
24468        let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
24469            panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
24470        });
24471        let rl = policy.rate_limit.expect("rate_limit must be Some");
24472        assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
24473        assert_eq!(
24474            rl.window,
24475            Duration::from_secs(1),
24476            "single-`0` magnitude with `s` unit must parse to window=1s"
24477        );
24478    }
24479
24480    #[test]
24481    fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
24482        // The complementary boundary pin — every magnitude
24483        // `render` emits starts with `[1-9]` (or is the single byte
24484        // `"0"`), so the canonical-form predicate is `(len == 1) ||
24485        // (first byte != '0')`. Pinning the `len > 1 && first byte ==
24486        // '1'` case explicitly so a future tightening of the gate
24487        // (e.g. an over-eager "no leading digit < 5" rule, or a
24488        // mistakenly anchored start-of-magnitude byte check) lands
24489        // here before the canonical-forms-iterating test would catch
24490        // it.
24491        let payload = r#"{"rateLimit":"100/s"}"#;
24492        let policy: MeshPolicy = serde_json::from_str(payload)
24493            .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
24494        let rl = policy.rate_limit.expect("rate_limit must be Some");
24495        assert_eq!(
24496            rl.rate, 100,
24497            "canonical-100 magnitude must parse to rate=100"
24498        );
24499    }
24500
24501    #[test]
24502    fn rate_limit_serde_accepts_integer_canonical_forms() {
24503        // Pin the happy-path: every canonical author shape `render`
24504        // ever emits parses cleanly through the codec post-gate. The
24505        // codec's accepted set (post-gate) is exactly its emitted set
24506        // for the integer-magnitude class — same property
24507        // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
24508        // gates guarantee on the peer codecs. Iterating across rate
24509        // magnitudes (including `"0"`, which the codec accepts even
24510        // though `validate_politicas` rejects `rate == 0` at the typed
24511        // layer above) closes the codec contract at the parse layer
24512        // independently of the validate layer.
24513        for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
24514            for unit_lit in ["s", "m", "h"] {
24515                let lit = format!("{rate_lit}/{unit_lit}");
24516                let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
24517                let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
24518                    panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
24519                });
24520                let rl = policy.rate_limit.expect("rate_limit must be Some");
24521                assert_eq!(
24522                    rl.rate,
24523                    rate_lit.parse::<u32>().unwrap(),
24524                    "rate mismatch for {lit:?}"
24525                );
24526            }
24527        }
24528    }
24529
24530    #[test]
24531    fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
24532        // The structural property the gate enforces: serialize ∘
24533        // deserialize is the identity on every canonical author shape.
24534        // Peer of `parse_byte_size`'s and `parse_duration`'s
24535        // `_round_trips_through_render_for_every_canonical_form` tests
24536        // on the rate-limit axis. Before the gate, `"+100/s"` violated
24537        // this (`parse` → `RateLimit { 100, 1s }` → `render` →
24538        // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
24539        for rate in [1u32, 100, 5000, 1_000_000] {
24540            for (window, unit) in [
24541                (Duration::from_secs(1), "s"),
24542                (Duration::from_secs(60), "m"),
24543                (Duration::from_secs(3600), "h"),
24544            ] {
24545                let policy = MeshPolicy {
24546                    rate_limit: Some(RateLimit { rate, window }),
24547                    ..Default::default()
24548                };
24549                let json = serde_json::to_string(&policy).unwrap();
24550                let expected = format!("\"{rate}/{unit}\"");
24551                assert!(
24552                    json.contains(&expected),
24553                    "expected {expected:?} in {json:?}"
24554                );
24555                let back: MeshPolicy = serde_json::from_str(&json).unwrap();
24556                assert_eq!(
24557                    back.rate_limit, policy.rate_limit,
24558                    "round-trip for {json:?}"
24559                );
24560            }
24561        }
24562    }
24563
24564    // ── self-membership cross-slot gate ──────────────────────────────
24565
24566    #[test]
24567    fn validate_no_self_membership_rejects_self_named_membro() {
24568        // An Aplicacao whose `:membros` lists its own `:nome` is a
24569        // one-node lacre-closure recursion — rejected, naming the parent.
24570        let membros = vec![
24571            membro("catalog", "^0.1"),
24572            membro("checkout", "^0.1"),
24573            membro("cart", "^0.1"),
24574        ];
24575        let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
24576        assert!(
24577            matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
24578            "got {err:?}"
24579        );
24580    }
24581
24582    #[test]
24583    fn validate_no_self_membership_accepts_distinct_membros() {
24584        // Positive control: distinct member names (including a member
24585        // that is itself an Aplicacao — recursive composition is valid,
24586        // MESH-COMPOSITION §V) pass the gate.
24587        let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
24588        validate_no_self_membership(&membros, "checkout").unwrap();
24589    }
24590
24591    #[test]
24592    fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
24593        // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
24594        // `NoMembros` arm (the more-fundamental "graph must have nodes"
24595        // gate), not by this cross-slot self-edge gate. Keeping the
24596        // self-membership predicate vacuously-ok on the empty input
24597        // matches its supervisor-axis peer
24598        // (`validate_no_self_supervision_empty_children_is_ok`) and
24599        // makes the gate composable from any future call site (an M4
24600        // CR materializer's per-membros validator) without re-checking
24601        // emptiness.
24602        validate_no_self_membership(&[], "checkout").unwrap();
24603    }
24604
24605    #[test]
24606    fn validate_no_self_membership_diagnostic_names_offending_caixa() {
24607        // Pinning the Display: the self-membership diagnostic must name
24608        // the offending caixa verbatim + the "lists itself" framing the
24609        // author can grep for, so the cluster-far failure surfaces at
24610        // build time with one-line remediation. Same diagnostic shape
24611        // as the supervisor-axis `ChildSupervisesSelf` peer.
24612        let membros = vec![membro("orquestra", "^0.1")];
24613        let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
24614        let msg = err.to_string();
24615        assert!(
24616            msg.contains("orquestra"),
24617            "diagnostic must name the offending caixa nome (got: {msg:?})"
24618        );
24619        assert!(
24620            msg.contains("lists itself"),
24621            "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
24622        );
24623    }
24624
24625    #[test]
24626    fn default_servico_port_constant_pins_canonical_8080_literal() {
24627        // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
24628        // at the verbatim `8080` literal both consumers (the
24629        // `Entrada::port` serde default via [`default_port`] and the
24630        // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
24631        // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
24632        // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
24633        // discipline (a085b26) on the per-renderer canonical-K8s-axis
24634        // string-constant axis: a future refactor that drifts the
24635        // constant out from under either consumer surfaces here ahead
24636        // of every per-renderer's first emission. The literal value
24637        // matches the well-known HTTP-alt port the `pleme-computeunit`
24638        // library chart already emits as its `trigger.service.port`
24639        // default — by construction the same value the substrate
24640        // assumes about every Servico's in-cluster L4 listener.
24641        assert_eq!(
24642            DEFAULT_SERVICO_PORT, 8080,
24643            "canonical Servico port literal must remain `8080` verbatim — \
24644             this is the value both the `Entrada::port` serde default and the \
24645             caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
24646        );
24647    }
24648
24649    #[test]
24650    fn default_port_helper_returns_canonical_servico_port_constant() {
24651        // The bridge-arm — pins that the [`default_port`] helper
24652        // [`Entrada::port`]'s `#[serde(default = "default_port")]`
24653        // attribute hooks routes through the lifted
24654        // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
24655        // literal. A future refactor that re-introduces the `8080`
24656        // literal at the helper's return site (silently re-opening
24657        // the drift footgun this lift closed) surfaces here ahead of
24658        // every author-side `(:entrada (:host … :para …))` slot
24659        // without an explicit `:port`. Peer with the
24660        // `default_namespace_re_export_points_at_caixa_core_canonical`
24661        // pin on the caixa-mesh-side re-export axis.
24662        assert_eq!(
24663            default_port(),
24664            DEFAULT_SERVICO_PORT,
24665            "the serde-default helper must route through the lifted constant"
24666        );
24667    }
24668
24669    #[test]
24670    fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
24671        // The end-to-end pin — an author-surface `(:entrada (:host …
24672        // :para …))` without an explicit `:port` slot deserializes to
24673        // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
24674        // verbatim. Routes the canonical lifted constant through both
24675        // the serde-default machinery (the `#[serde(default =
24676        // "default_port")]` attribute) and the typed-value-shape
24677        // contract (the resulting [`Entrada::port`] value). A future
24678        // refactor that drifts either axis — replacing the serde
24679        // hook's helper, changing the typed slot's wire shape — would
24680        // surface here before any per-renderer's CNP / Gateway /
24681        // HTTPRoute emission consumed the drifted default.
24682        let entrada: Entrada =
24683            serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
24684        assert_eq!(
24685            entrada.port, DEFAULT_SERVICO_PORT,
24686            "the serde default must materialize as the lifted canonical Servico port"
24687        );
24688    }
24689
24690    #[test]
24691    fn servico_port_min_pins_canonical_accept_set_floor() {
24692        // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
24693        // verbatim `1` literal every typed `:entrada :port` acceptance
24694        // gate keys off. Peer with the
24695        // [`default_servico_port_constant_pins_canonical_8080_literal`]
24696        // discipline on the canonical-Servico-port-constant axis: a
24697        // future refactor that drifts the accept-set floor out from
24698        // under the sole consumer at [`AplicacaoSpec::validate`]'s
24699        // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
24700        // every per-`:entrada` `EntradaPortZero` diagnostic. The
24701        // literal value matches the IANA-registered TCP/UDP port
24702        // space floor (`1..=65535` — port `0` is the "any ephemeral"
24703        // sentinel, not a well-defined destination the substrate's
24704        // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
24705        // axis can honor).
24706        assert_eq!(
24707            SERVICO_PORT_MIN, 1,
24708            "canonical Servico port accept-set floor must remain `1` verbatim — \
24709             this is the value the `AplicacaoSpec::validate` gate at \
24710             `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
24711        );
24712    }
24713
24714    #[test]
24715    fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
24716        // The cross-const invariant pin — the substrate's canonical
24717        // default port must satisfy its own accept-set floor by
24718        // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
24719        // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
24720        // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
24721        // override the operator pins through a future
24722        // `:placement :default-port` slot that lands out-of-range, a
24723        // per-edition Servico-port migration that lifted the floor
24724        // above the previous default without coordinating the pair —
24725        // would silently invalidate the serde-default emission at
24726        // every author-side `(:entrada (:host … :para …))` slot
24727        // without an explicit `:port`: the default port would fall
24728        // below the accept-set floor, the `AplicacaoSpec::validate`
24729        // gate would reject every default-carrying Aplicacao as
24730        // `EntradaPortZero`, and the substrate's typed
24731        // `(defcaixa … :kind Aplicacao)` surface would fail validate
24732        // on every Aplicacao whose author omitted `:entrada :port`
24733        // for the substrate's chosen default — a class of authoring-
24734        // surface footguns the compile-time pin structurally closes.
24735        // Peer with the
24736        // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
24737        // (27f9b34) cross-const invariant pin discipline on the peer
24738        // canonical-Helm-per-values-block child-chart-enablement-toggle
24739        // axis pair.
24740        const {
24741            assert!(
24742                SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
24743                "the substrate's canonical default port DEFAULT_SERVICO_PORT \
24744                 must satisfy its own accept-set floor SERVICO_PORT_MIN — \
24745                 every default-carrying `(:entrada (:host … :para …))` slot \
24746                 without an explicit `:port` inherits `DEFAULT_SERVICO_PORT` \
24747                 through the serde default hook and must pass the \
24748                 `AplicacaoSpec::validate` floor gate by construction",
24749            );
24750        }
24751    }
24752
24753    #[test]
24754    fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
24755        // The gate-site pin — asserts the `AplicacaoSpec::validate`
24756        // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
24757        // `EntradaPortZero` diagnostic on the below-floor input
24758        // `port: 0` (the only below-floor value the `u16` field can
24759        // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
24760        // is the singleton `{0}`). A future refactor that drifts the
24761        // gate off the lifted const (silently re-introducing an
24762        // inline `if e.port == 0` byte-check) surfaces here — the
24763        // pin cannot distinguish `< 1` from `== 0` on the current
24764        // floor, but it *does* pin that the diagnostic fires on `0`
24765        // through whichever gate is wired, so any future accept-set
24766        // floor migration (a hypothetical unprivileged-only
24767        // migration lifting `SERVICO_PORT_MIN` to `1024`) must
24768        // update this test alongside the const declaration —
24769        // structurally guaranteeing the gate + accept-set + pin
24770        // trio move together. Peer with the
24771        // [`rejects_zero_entrada_port`] behavioral pin on the same
24772        // per-`:entrada :port` axis — that pin asserts the pre-lift
24773        // behavioral contract (`port: 0` → `EntradaPortZero`); this
24774        // pin adds the structural link to the lifted floor const.
24775        assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
24776        let mut s = three_member_spec();
24777        s.entrada.as_mut().unwrap().port = 0;
24778        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
24779    }
24780
24781    // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
24782
24783    #[test]
24784    fn membro_serde_keys_match_lifted_membro_key_consts() {
24785        // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
24786        // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
24787        // name the exact camelCase JSON keys the
24788        // `#[serde(rename_all = "camelCase")]` attribute on
24789        // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
24790        // that each canonical byte-sequence appears verbatim in the
24791        // JSON — a future accidental `rename_all = "snake_case"` /
24792        // `"kebab-case"` / verbatim-field-name flip at the derive
24793        // attribute (any of which would silently break every downstream
24794        // JSON consumer that reaches for one of the two consts via
24795        // `Value::get(...)`) surfaces here as a build-time test failure
24796        // at `aplicacao.rs`, not as an apply-time
24797        // `.get(<stale-canonical-const>)` returning `None` far from the
24798        // derive-attr drift's commit. Peer with the sibling
24799        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
24800        // (40cc4e5) pin on the M2 supervision-tree top-level axis —
24801        // same discipline the SupervisorSpec top-level lift established,
24802        // extended here to the M3 [`Membro`] per-`:membros` axis.
24803        let m = Membro {
24804            caixa: "catalog".into(),
24805            versao: "^0.1".into(),
24806        };
24807        let json = serde_json::to_string(&m).unwrap();
24808        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
24809            let quoted = format!("\"{key}\"");
24810            assert!(
24811                json.contains(&quoted),
24812                "serialized Membro must carry the lifted MEMBRO_KEY_* \
24813                 byte-sequence {quoted} verbatim in the JSON emission \
24814                 (got: {json})",
24815            );
24816        }
24817    }
24818
24819    #[test]
24820    fn membro_key_consts_are_pairwise_distinct() {
24821        // Cross-axis drift-detection pin: a future collapse of the two
24822        // canonical [`Membro`] per-entry byte-strings onto the same
24823        // value (e.g. an accidental copy-paste flip of
24824        // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
24825        // silently reroute every downstream probe on one axis onto the
24826        // sibling axis's overlay entry and pass every propagation-probe
24827        // test that expected only the stale axis's value. Peer of the
24828        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
24829        // (40cc4e5).
24830        let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
24831        for (i, a) in all.iter().enumerate() {
24832            for b in all.iter().skip(i + 1) {
24833                assert_ne!(
24834                    a, b,
24835                    "MEMBRO_KEY_* consts must be pairwise-distinct \
24836                     canonical byte-sequences — got `{a}` == `{b}`",
24837                );
24838            }
24839        }
24840    }
24841
24842    // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
24843    //    URL-path fallback resolver every HTTPRoute-aware renderer
24844    //    reaching for a per-rule path-list resolution routes through.
24845    //    The four pin tests below fix the four-way accept-set the
24846    //    resolver must always honor: (:paths-non-empty-verbatim,
24847    //    :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
24848    //    :paths-preserves-order-across-multiple-entries) — drift on any
24849    //    arm surfaces at caixa-core build time rather than at cluster-
24850    //    apply time. Peer discipline with `MeshPolicy::is_empty` on the
24851    //    sibling `:politicas` typed-primitive dispatch axis.
24852
24853    fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
24854        Entrada {
24855            host: "example.com".into(),
24856            para: "cart".into(),
24857            paths: paths.into_iter().map(String::from).collect(),
24858            port: DEFAULT_SERVICO_PORT,
24859        }
24860    }
24861
24862    #[test]
24863    fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
24864        // The typed `:entrada :paths` slot carries an author-declared
24865        // list — the resolver returns each entry verbatim, no
24866        // catch-all substitution. The canonical "author declared
24867        // paths, honor them verbatim" arm of the path-list dispatch.
24868        let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
24869        assert_eq!(
24870            e.resolved_paths(),
24871            vec!["/api/cart", "/api/products"],
24872            "resolved_paths must return each `:entrada :paths` entry \
24873             verbatim when the typed slot is non-empty (got {:?})",
24874            e.resolved_paths(),
24875        );
24876    }
24877
24878    #[test]
24879    fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
24880        // Empty `:entrada :paths` slot — the resolver substitutes the
24881        // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
24882        // catch-all fallback verbatim. Pins the empty-arm of the
24883        // resolver's four-way accept-set against a future silent
24884        // detour that returned an empty Vec (which would emit an
24885        // HTTPRoute with zero rules — silently dropping every
24886        // external `:entrada` flow at admission time), routed to a
24887        // different fallback shape, or dropped the catch-all
24888        // altogether.
24889        let e = entrada_with_paths(vec![]);
24890        assert_eq!(
24891            e.resolved_paths(),
24892            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
24893            "resolved_paths on empty `:entrada :paths` must fall back \
24894             to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
24895             all — got {:?}",
24896            e.resolved_paths(),
24897        );
24898    }
24899
24900    #[test]
24901    fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
24902        // Single-entry `:entrada :paths` — the resolver returns the
24903        // single declared path verbatim, NOT the catch-all fallback
24904        // (author declared a path, honor it — the empty-arm and the
24905        // len-1 arm are semantically distinct axes of the resolver's
24906        // accept-set). Pins that the resolver treats "author declared
24907        // one path" as authored input, not as the empty case.
24908        let e = entrada_with_paths(vec!["/api/only"]);
24909        assert_eq!(
24910            e.resolved_paths(),
24911            vec!["/api/only"],
24912            "resolved_paths on single-entry `:entrada :paths` must \
24913             return the declared path verbatim, NOT the catch-all \
24914             fallback (got {:?})",
24915            e.resolved_paths(),
24916        );
24917    }
24918
24919    #[test]
24920    fn resolved_paths_preserves_author_declared_order() {
24921        // The `:entrada :paths` list is author-ordered — the resolver
24922        // preserves the author's declaration order verbatim, since
24923        // per-rule dispatch order at the K8s Gateway API HTTPRoute
24924        // consumer is significant (first-match-wins under the
24925        // path-prefix matcher). Pins against a future silent
24926        // re-sort / dedup / normalize detour that reordered author
24927        // input.
24928        let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
24929        assert_eq!(
24930            e.resolved_paths(),
24931            vec!["/z/last", "/a/first", "/m/mid"],
24932            "resolved_paths must preserve author-declared `:entrada \
24933             :paths` order verbatim — got {:?}",
24934            e.resolved_paths(),
24935        );
24936    }
24937
24938    // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
24939    //    slot `&[String]` slice accessor every per-`:entrada` consumer
24940    //    that must see the author's declaration verbatim (not the
24941    //    fallback-applied projection the sibling `resolved_paths`
24942    //    returns) routes through. The three pin tests below fix the
24943    //    accept-set the accessor must honor: (:non-empty-byte-equal,
24944    //    :empty-projects-empty-slice, :preserves-author-declared-order)
24945    //    — drift on any arm surfaces at caixa-core build time rather
24946    //    than at cluster-apply time. Peer discipline with the sibling
24947    //    [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
24948    //    peer M3 mesh-slot `Vec<String>`-carry axis.
24949
24950    #[test]
24951    fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
24952        // Byte-equal pin: [`Entrada::paths`] must project the raw
24953        // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
24954        // slice borrowed from the typed slot's own [`Vec<String>`]
24955        // storage — no re-ordering, no dedup, no per-entry normalization,
24956        // no fallback substitution (the fallback-applying projection is
24957        // the sibling [`Entrada::resolved_paths`] resolver). Pins against
24958        // a future silent detour that re-normalized the list, dropped
24959        // duplicates the [`AplicacaoSpec::validate`]
24960        // `EntradaPathDuplicate` refusal already rejects at build time,
24961        // or (most severe) accidentally routed through the fallback-
24962        // applying sibling and returned the substrate catch-all when
24963        // the author declared an empty list — collapsing the raw-slot
24964        // and fallback-applied axes into one and breaking the
24965        // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
24966        //
24967        // Peer of the sibling
24968        // [`Placement::clusters`]-shape byte-equal pin
24969        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
24970        // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
24971        let fixtures: Vec<Vec<String>> = vec![
24972            Vec::new(),
24973            vec!["/api/cart".into()],
24974            vec!["/api/cart".into(), "/api/products".into()],
24975            vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
24976        ];
24977        for paths in fixtures {
24978            let e = Entrada {
24979                host: "example.com".into(),
24980                para: "cart".into(),
24981                paths: paths.clone(),
24982                port: DEFAULT_SERVICO_PORT,
24983            };
24984            assert_eq!(
24985                e.paths(),
24986                paths.as_slice(),
24987                "Entrada::paths must return :entrada :paths verbatim \
24988                 (got {:?}, expected {:?})",
24989                e.paths(),
24990                paths.as_slice(),
24991            );
24992            assert_eq!(
24993                e.paths(),
24994                e.paths.as_slice(),
24995                "Entrada::paths accessor and .paths.as_slice() field \
24996                 access must byte-equal — the accessor is the substrate-\
24997                 primitive typed dispatch every downstream per-`:entrada` \
24998                 raw-slot path-list consumer must route through",
24999            );
25000            assert_eq!(
25001                e.paths().len(),
25002                e.paths.len(),
25003                "Entrada::paths().len() must byte-equal self.paths.len() \
25004                 — a length drift would silently split the paired \
25005                 pre-flight cascade-head `.is_empty()` probe input in \
25006                 the sibling [`Entrada::resolved_paths`] resolver from \
25007                 the per-entry validate loop's traversal input in \
25008                 [`AplicacaoSpec::validate`]",
25009            );
25010        }
25011    }
25012
25013    #[test]
25014    fn resolved_paths_reads_through_lifted_paths_accessor() {
25015        // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
25016        // pre-flight `.paths().is_empty()` cascade-head probe (which
25017        // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
25018        // catch-all fallback arm when the accessor projects the empty
25019        // slice) and the per-entry `.paths().iter().map(String::as_str)`
25020        // projection (which must reach every entry in the same order
25021        // the accessor projects, so the sibling
25022        // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
25023        // per-entry projection stay in lockstep by construction) must
25024        // both key off the lifted accessor. Pins the two-site coherence
25025        // by exercising each production consumer end-to-end: (1) the
25026        // catch-all-fallback arm under the empty slice, (2) the
25027        // author-declared-verbatim arm under a two-entry cohort whose
25028        // per-entry projection must byte-equal the input's per-entry
25029        // author-declared paths in the author's declared order.
25030        //
25031        // Peer of the sibling M3
25032        // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
25033        // `validate_placement_reads_through_lifted_clusters_accessor`
25034        // on the sibling `Placement::clusters` reader-site convergence.
25035        let empty = entrada_with_paths(vec![]);
25036        assert_eq!(
25037            empty.resolved_paths(),
25038            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
25039            "resolved_paths on empty :entrada :paths must trip the \
25040             lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
25041             catch-all fallback — routing through the lifted paths() \
25042             accessor must not silently drop the fallback arm",
25043        );
25044
25045        let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
25046        assert_eq!(
25047            declared.resolved_paths(),
25048            vec!["/api/cart", "/api/products"],
25049            "resolved_paths on non-empty :entrada :paths must return each \
25050             entry verbatim in the author's declared order — routing \
25051             through the lifted paths() accessor must not silently \
25052             reorder or drop entries",
25053        );
25054        // Byte-equal pin against the raw-slot accessor to keep the
25055        // fallback-applying resolver's per-entry projection input in
25056        // lockstep with the raw-slot accessor's projection.
25057        let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
25058        assert_eq!(
25059            declared.resolved_paths(),
25060            raw_projected,
25061            "resolved_paths non-empty projection must byte-equal the \
25062             lifted paths() accessor's per-entry String::as_str projection \
25063             — the two projections share the same input slice by \
25064             construction, so any drift here would surface a silent \
25065             re-ordering / dedup / normalization detour in the resolver",
25066        );
25067    }
25068
25069    #[test]
25070    fn validate_reads_through_lifted_entrada_paths_accessor() {
25071        // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
25072        // per-entry value-shape gate's `for p in e.paths()` traversal
25073        // (which must reach every entry in the same order the accessor
25074        // projects, so both the per-entry `EntradaPathEmpty` /
25075        // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
25076        // the duplicate-detection HashSet insert that trips
25077        // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
25078        // projection) must route through the lifted accessor. Pins the
25079        // coherence by exercising each production consumer end-to-end:
25080        // (1) the `EntradaPathEmpty` refusal fires on the second entry
25081        // of a two-entry cohort whose head is valid but tail is empty
25082        // (which requires the loop to reach the second entry through
25083        // the accessor), and (2) the `EntradaPathDuplicate` refusal
25084        // fires on the second entry of a two-entry cohort that shares
25085        // a path (which requires the loop to reach both entries — a
25086        // first-entry-only projection would silently pass since the
25087        // dedup HashSet has room for the first insert).
25088        //
25089        // Peer of the sibling
25090        // `validate_placement_reads_through_lifted_clusters_accessor`
25091        // on the sibling `Placement::clusters` reader-site convergence.
25092        let base = crate::AplicacaoSpec {
25093            membros: vec![crate::Membro {
25094                caixa: "cart".into(),
25095                versao: "^0.1".into(),
25096            }],
25097            contratos: Vec::new(),
25098            politicas: crate::MeshPolicy::default(),
25099            placement: crate::Placement {
25100                estrategia: crate::PlacementStrategy::SingleNode,
25101                clusters: vec!["rio".into()],
25102                shard_key: None,
25103                affinity: None,
25104            },
25105            entrada: Some(Entrada {
25106                host: "example.com".into(),
25107                para: "cart".into(),
25108                paths: vec!["/api/cart".into(), String::new()],
25109                port: DEFAULT_SERVICO_PORT,
25110            }),
25111        };
25112        assert_eq!(
25113            base.validate(),
25114            Err(crate::AplicacaoError::EntradaPathEmpty),
25115            "validate must trip EntradaPathEmpty on the second entry of \
25116             a two-entry cohort — routing through the lifted paths() \
25117             accessor must not silently short-circuit the loop at the \
25118             valid head entry",
25119        );
25120
25121        let mut dup = base;
25122        dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
25123        assert_eq!(
25124            dup.validate(),
25125            Err(crate::AplicacaoError::EntradaPathDuplicate {
25126                path: "/api/cart".into(),
25127            }),
25128            "validate must trip EntradaPathDuplicate on the second entry \
25129             of a two-entry cohort that shares a path — routing through \
25130             the lifted paths() accessor must not silently short-circuit \
25131             the dedup HashSet insert at the first entry",
25132        );
25133    }
25134
25135    // ── Entrada::hostname / Entrada::hostnames — the substrate-
25136    //    canonical per-`:entrada` DNS-hostname resolver pair every
25137    //    Gateway-API-aware renderer reaching for a per-listener
25138    //    singular `hostname:` filter (Gateway) or a per-route plural
25139    //    `spec.hostnames[]` filter list (HTTPRoute) routes through.
25140    //    The three pin tests below fix the two-way accept-set the pair
25141    //    must always honor: (:singular-byte-equal-to-host,
25142    //    :plural-is-singleton-of-singular, :plural-len-is-one) — drift
25143    //    on any arm surfaces at caixa-core build time rather than at
25144    //    cluster-apply time when the API server refuses the HTTPRoute
25145    //    for non-intersecting hostname filters. Peer discipline with
25146    //    the sibling `resolved_paths` accept-set pin block above on the
25147    //    per-`:entrada` path-list resolver axis.
25148
25149    fn entrada_with_host(host: &str) -> Entrada {
25150        Entrada {
25151            host: host.into(),
25152            para: "cart".into(),
25153            paths: Vec::new(),
25154            port: DEFAULT_SERVICO_PORT,
25155        }
25156    }
25157
25158    #[test]
25159    fn hostname_returns_entrada_host_byte_equal() {
25160        // The canonical singular-axis pin: [`Entrada::hostname`] must
25161        // return the `:entrada :host` field byte-for-byte, borrowed
25162        // from the typed slot's own [`String`] storage. Pins against a
25163        // future silent detour that re-normalized the host (an
25164        // accidental `.to_lowercase()` — validate_entrada_host already
25165        // enforces lowercase, so any re-normalization is redundant + a
25166        // drift surface between the validator and the accessor), a
25167        // trailing-`.` fully-qualified DNS shape substitution, or a
25168        // Punycode round-trip that lowered a Unicode host through IDNA.
25169        let e = entrada_with_host("checkout.quero.cloud");
25170        assert_eq!(
25171            e.hostname(),
25172            "checkout.quero.cloud",
25173            "Entrada::hostname must return :entrada :host verbatim \
25174             (got {:?})",
25175            e.hostname(),
25176        );
25177        assert_eq!(
25178            e.hostname(),
25179            e.host.as_str(),
25180            "Entrada::hostname must byte-equal the .host field access",
25181        );
25182    }
25183
25184    #[test]
25185    fn hostnames_returns_singleton_of_hostname_accessor() {
25186        // The pair-invariant pin: [`Entrada::hostnames`] must always
25187        // return exactly `vec![hostname()]` — the singleton list whose
25188        // sole entry is the substrate's canonical per-`:entrada`
25189        // singular hostname. Pins the two-consumer coherence axis: the
25190        // Gateway listener's singular `hostname:` filter and the
25191        // HTTPRoute's plural `spec.hostnames[]` filter list must
25192        // agree, else the Gateway API v1.x conformance layer rejects
25193        // the HTTPRoute at attach time with
25194        // `Accepted:False/NoMatchingParent` (the parent Gateway's
25195        // listener hostname doesn't intersect the route's hostname
25196        // filter list) — a divergence whose apply-time symptom is far
25197        // from any single-site commit and never surfaces in the
25198        // emitted YAML. Pinning the pair-invariant here makes any
25199        // future accidental split (an accidental `.to_string() + "."`
25200        // trailing-`.` on the plural side that didn't land on the
25201        // singular side, an accidental prefix stripping on one axis,
25202        // an accidental wildcard prepend the SNI fan-out overlay
25203        // authors on the plural side without a paired singular
25204        // migration) trip at caixa-core build time.
25205        let e = entrada_with_host("checkout.quero.cloud");
25206        assert_eq!(
25207            e.hostnames(),
25208            vec![e.hostname()],
25209            "Entrada::hostnames must return `vec![hostname()]` under \
25210             the pair-invariant — got {:?} vs. singleton {:?}",
25211            e.hostnames(),
25212            vec![e.hostname()],
25213        );
25214    }
25215
25216    #[test]
25217    fn hostnames_is_singleton_under_single_host_author_surface() {
25218        // The singleton-shape pin: under today's single-hostname-per-
25219        // `:entrada` author surface (the `:host` slot is a single
25220        // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
25221        // must always return a list of length exactly one. Pins
25222        // against a future silent detour that returned an empty list
25223        // (which would emit an HTTPRoute with `spec.hostnames: []` —
25224        // matching every incoming Host header regardless of the
25225        // Aplicacao's declared ingress apex, silently over-matching
25226        // every foreign VirtualHost the parent Gateway also fronts) or
25227        // a duplicated entry (which the Gateway API v1.x parser
25228        // accepts as a `[]-length-2 list of equal hostnames]` but
25229        // whose semantics differ from the intended singleton). The
25230        // author-surface extension point ("a future `:entrada
25231        // :alt-hosts` list overlay" the docstring names) is the sole
25232        // future axis that flips this pin — that migration will re-
25233        // author this test to pin the new plural cardinality.
25234        let e = entrada_with_host("checkout.quero.cloud");
25235        assert_eq!(
25236            e.hostnames().len(),
25237            1,
25238            "Entrada::hostnames must be a singleton under today's \
25239             single-hostname-per-`:entrada` author surface — got \
25240             length {}: {:?}",
25241            e.hostnames().len(),
25242            e.hostnames(),
25243        );
25244    }
25245
25246    // ── Entrada::destination — the substrate-canonical per-`:entrada`
25247    //    destination-Servico scalar accessor every Gateway-API
25248    //    HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
25249    //    discriminator arg (HTTPRoute name composer) or a per-rule
25250    //    `backendRefs[0].name` axis routes through. The two pin tests
25251    //    below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
25252    //    either arm surfaces at caixa-core build time rather than at
25253    //    cluster-apply time when an HTTPRoute's `metadata.name` and
25254    //    `backendRefs[]` silently disagree on which destination Servico
25255    //    the ingress fronts. Peer discipline with the sibling
25256    //    `resolved_paths` + `hostname` + `hostnames` accept-set pin
25257    //    blocks above on the per-`:entrada` path-list / DNS-hostname
25258    //    resolver axes.
25259
25260    #[test]
25261    fn destination_returns_entrada_para_byte_equal() {
25262        // The canonical destination-scalar pin: [`Entrada::destination`]
25263        // must return the `:entrada :para` field byte-for-byte, borrowed
25264        // from the typed slot's own [`String`] storage. Pins against a
25265        // future silent detour that re-normalized the destination (an
25266        // accidental `.to_lowercase()` — the destination Servico is
25267        // already validated as a DNS-1123 label upstream, so any
25268        // re-normalization is redundant + a drift surface between the
25269        // validator and the accessor), a namespace-prefix rewrite (an
25270        // accidental `format!("{namespace}/{para}")` per-CR fully-
25271        // qualified rewrite that didn't land on the peer axis), or a
25272        // per-cluster suffix stamp the operator authors on one
25273        // consumer without the other.
25274        for para in ["cart", "checkout", "catalog", "orders-v2"] {
25275            let e = Entrada {
25276                host: "checkout.quero.cloud".into(),
25277                para: para.into(),
25278                paths: Vec::new(),
25279                port: DEFAULT_SERVICO_PORT,
25280            };
25281            assert_eq!(
25282                e.destination(),
25283                para,
25284                "Entrada::destination must return :entrada :para verbatim \
25285                 (got {:?}, expected {para:?})",
25286                e.destination(),
25287            );
25288            assert_eq!(
25289                e.destination(),
25290                e.para.as_str(),
25291                "Entrada::destination must byte-equal the .para field access",
25292            );
25293        }
25294    }
25295
25296    #[test]
25297    fn destination_borrows_from_entrada_para_storage() {
25298        // The borrow-not-copy pin: [`Entrada::destination`] must
25299        // return a `&str` slice that borrows from the typed slot's
25300        // own [`String`] storage — same-address invariant with
25301        // `entrada.para.as_str()`. Pins against a future silent detour
25302        // that allocated a fresh `String` (`self.para.clone()` in the
25303        // body would type-check but silently drop the borrow, and
25304        // every downstream consumer that assumed the returned slice
25305        // outlives `&self` would break on a stale-reference use-after-
25306        // free). Peer with the sibling `hostname_returns_entrada_
25307        // host_byte_equal` on the singular-DNS-hostname axis.
25308        let e = entrada_with_host("checkout.quero.cloud");
25309        let dest = e.destination();
25310        let para_slice = e.para.as_str();
25311        assert_eq!(
25312            dest.as_ptr(),
25313            para_slice.as_ptr(),
25314            "Entrada::destination must borrow from the .para String's \
25315             backing storage — a fresh allocation here means the \
25316             accessor no longer names the substrate-primitive typed \
25317             dispatch and every downstream consumer would silently \
25318             carry a detached copy",
25319        );
25320        assert_eq!(
25321            dest.len(),
25322            para_slice.len(),
25323            "Entrada::destination and .para.as_str() must byte-equal in \
25324             length as well as in address",
25325        );
25326    }
25327
25328    #[test]
25329    fn port_returns_entrada_port_verbatim_across_permutations() {
25330        // The canonical L4-port-scalar pin: [`Entrada::port`] must
25331        // return the `:entrada :port` field verbatim as a `u16` across
25332        // every author-declared value in the validated accept-set
25333        // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
25334        // silent detour that clamped the port (an accidental
25335        // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
25336        // land on the peer [`AplicacaoSpec::port_for_destination`]
25337        // resolver), rewrote it through a per-cluster port-remap table
25338        // the operator authors on one consumer without the other, or
25339        // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
25340        // serde-default value (which would silently collapse the
25341        // distinction between "author explicitly declared `:port 8080`"
25342        // and "author omitted the slot and inherited the default" the
25343        // future per-cluster override slot depends on). Peer with the
25344        // sibling `destination_returns_entrada_para_byte_equal` +
25345        // `hostname_returns_entrada_host_byte_equal` pins on the
25346        // per-`:entrada` `&str` scalar axes.
25347        for port in [
25348            SERVICO_PORT_MIN,
25349            DEFAULT_SERVICO_PORT,
25350            8443u16,
25351            9090u16,
25352            u16::MAX,
25353        ] {
25354            let e = Entrada {
25355                host: "checkout.quero.cloud".into(),
25356                para: "cart".into(),
25357                paths: Vec::new(),
25358                port,
25359            };
25360            assert_eq!(
25361                e.port(),
25362                port,
25363                "Entrada::port must return :entrada :port verbatim \
25364                 (got {}, expected {port})",
25365                e.port(),
25366            );
25367            assert_eq!(
25368                e.port(),
25369                e.port,
25370                "Entrada::port accessor and .port field access must \
25371                 byte-equal — the accessor is the substrate-primitive \
25372                 typed dispatch every downstream L4-port consumer must \
25373                 route through",
25374            );
25375        }
25376    }
25377
25378    #[test]
25379    fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
25380        // Two-consumer coherence pin: the
25381        // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
25382        // (which reads through [`Entrada::port`] to compare against
25383        // [`SERVICO_PORT_MIN`]) and the
25384        // [`AplicacaoSpec::port_for_destination`] resolver (which reads
25385        // through [`Entrada::port`] to emit the per-destination
25386        // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
25387        // lifted accessor, so any future rebrand on the typed slot's
25388        // reader shape lands at exactly one place. Pins the two-site
25389        // coherence by exercising a below-floor port through validate
25390        // (which must reject) and a validated in-accept-set port through
25391        // port_for_destination (which must emit the same value the
25392        // accessor returns).
25393        let mut spec = three_member_spec();
25394        if let Some(e) = spec.entrada.as_mut() {
25395            e.port = 0;
25396        }
25397        assert_eq!(
25398            spec.validate().unwrap_err(),
25399            AplicacaoError::EntradaPortZero,
25400            "validate must reject `:entrada :port 0` through the lifted \
25401             Entrada::port accessor — port zero lies below \
25402             SERVICO_PORT_MIN and the validator routes through port() \
25403             to name the floor",
25404        );
25405
25406        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
25407            let mut spec = three_member_spec();
25408            if let Some(e) = spec.entrada.as_mut() {
25409                e.port = port;
25410            }
25411            spec.validate().expect(
25412                "entrada with in-accept-set :port must validate — the \
25413                 structural-floor gate reads through Entrada::port",
25414            );
25415            let entrada_ref = spec.entrada().expect(":entrada present");
25416            assert_eq!(
25417                spec.port_for_destination(entrada_ref.destination()),
25418                entrada_ref.port(),
25419                "port_for_destination(entrada.destination()) must equal \
25420                 entrada.port() — the two consumers of the per-:entrada \
25421                 L4-port axis (validator, per-destination resolver) both \
25422                 route through Entrada::port",
25423            );
25424        }
25425    }
25426
25427    #[test]
25428    fn wit_contract_source_returns_de_byte_equal_across_permutations() {
25429        // The canonical caller-Servico-scalar pin: [`WitContract::source`]
25430        // must return the `:contratos :de` field byte-for-byte, borrowed
25431        // from the typed slot's own [`String`] storage. Peer of the
25432        // sibling `destination_returns_entrada_para_byte_equal` pin on
25433        // the per-`:entrada` axis — same "the substrate-primitive
25434        // accessor must byte-equal the raw field access verbatim across
25435        // every author-declared value" discipline extended to the
25436        // per-`:contratos` caller arm. Pins against a future silent
25437        // detour that re-normalized the caller (an accidental
25438        // `.to_lowercase()` — every `:contratos :de` is validated as a
25439        // DNS-1123 label upstream via `validate_contrato_caixa`, so any
25440        // re-normalization is redundant + a drift surface between the
25441        // validator and the accessor), a namespace-prefix rewrite (an
25442        // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
25443        // rewrite that didn't land on the peer axis), or a per-cluster
25444        // suffix stamp the operator authors on one consumer without the
25445        // other.
25446        for de in ["cart", "checkout", "catalog", "orders-v2"] {
25447            let c = WitContract {
25448                de: de.into(),
25449                para: "downstream".into(),
25450                wit: "wasi:http/proxy".into(),
25451                endpoint: Some("/lookup".into()),
25452                subject: None,
25453                slot: None,
25454            };
25455            assert_eq!(
25456                c.source(),
25457                de,
25458                "WitContract::source must return :contratos :de verbatim \
25459                 (got {:?}, expected {de:?})",
25460                c.source(),
25461            );
25462            assert_eq!(
25463                c.source(),
25464                c.de.as_str(),
25465                "WitContract::source must byte-equal the .de field access",
25466            );
25467        }
25468    }
25469
25470    #[test]
25471    fn wit_contract_source_borrows_from_de_storage() {
25472        // The borrow-not-copy pin: [`WitContract::source`] must return a
25473        // `&str` slice that borrows from the typed slot's own [`String`]
25474        // storage — same-address invariant with `c.de.as_str()`. Pins
25475        // against a future silent detour that allocated a fresh `String`
25476        // (`self.de.clone()` in the body would type-check but silently
25477        // drop the borrow, and every downstream consumer that assumed
25478        // the returned slice outlives `&self` would break on a stale-
25479        // reference use-after-free). Peer of the sibling
25480        // `destination_borrows_from_entrada_para_storage` on the
25481        // per-`:entrada` axis.
25482        let c = WitContract {
25483            de: "cart".into(),
25484            para: "catalog".into(),
25485            wit: "wasi:http/proxy".into(),
25486            endpoint: Some("/lookup".into()),
25487            subject: None,
25488            slot: None,
25489        };
25490        let src = c.source();
25491        let de_slice = c.de.as_str();
25492        assert_eq!(
25493            src.as_ptr(),
25494            de_slice.as_ptr(),
25495            "WitContract::source must borrow from the .de String's \
25496             backing storage — a fresh allocation here means the \
25497             accessor no longer names the substrate-primitive typed \
25498             dispatch and every downstream consumer would silently \
25499             carry a detached copy",
25500        );
25501        assert_eq!(
25502            src.len(),
25503            de_slice.len(),
25504            "WitContract::source and .de.as_str() must byte-equal in \
25505             length as well as in address",
25506        );
25507    }
25508
25509    #[test]
25510    fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
25511        // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
25512        // must return the `:contratos :para` field byte-for-byte,
25513        // borrowed from the typed slot's own [`String`] storage. Peer of
25514        // the sibling `destination_returns_entrada_para_byte_equal` on
25515        // the per-`:entrada` axis — both accessors name "the destination-
25516        // Servico byte-string" concept on their respective mesh-slot
25517        // atoms (per-ingress apex vs. per-typed-edge callee) and both
25518        // must project the underlying `.para` field verbatim so every
25519        // downstream renderer that composes them with peer accessors
25520        // (e.g. `spec.port_for_destination(c.destination())` at the CNP
25521        // per-edge L4 port emit site) reads the same byte-string the
25522        // author declared.
25523        for para in ["catalog", "payment", "orders", "inventory-v3"] {
25524            let c = WitContract {
25525                de: "cart".into(),
25526                para: para.into(),
25527                wit: "wasi:http/proxy".into(),
25528                endpoint: Some("/lookup".into()),
25529                subject: None,
25530                slot: None,
25531            };
25532            assert_eq!(
25533                c.destination(),
25534                para,
25535                "WitContract::destination must return :contratos :para \
25536                 verbatim (got {:?}, expected {para:?})",
25537                c.destination(),
25538            );
25539            assert_eq!(
25540                c.destination(),
25541                c.para.as_str(),
25542                "WitContract::destination must byte-equal the .para \
25543                 field access",
25544            );
25545        }
25546    }
25547
25548    #[test]
25549    fn wit_contract_destination_borrows_from_para_storage() {
25550        // The borrow-not-copy pin: [`WitContract::destination`] must
25551        // return a `&str` slice that borrows from the typed slot's own
25552        // [`String`] storage — same-address invariant with
25553        // `c.para.as_str()`. Peer of the sibling
25554        // `destination_borrows_from_entrada_para_storage` on the
25555        // per-`:entrada` axis.
25556        let c = WitContract {
25557            de: "cart".into(),
25558            para: "catalog".into(),
25559            wit: "wasi:http/proxy".into(),
25560            endpoint: Some("/lookup".into()),
25561            subject: None,
25562            slot: None,
25563        };
25564        let dest = c.destination();
25565        let para_slice = c.para.as_str();
25566        assert_eq!(
25567            dest.as_ptr(),
25568            para_slice.as_ptr(),
25569            "WitContract::destination must borrow from the .para \
25570             String's backing storage — a fresh allocation here means \
25571             the accessor no longer names the substrate-primitive typed \
25572             dispatch and every downstream consumer would silently \
25573             carry a detached copy",
25574        );
25575        assert_eq!(
25576            dest.len(),
25577            para_slice.len(),
25578            "WitContract::destination and .para.as_str() must byte-equal \
25579             in length as well as in address",
25580        );
25581    }
25582
25583    #[test]
25584    fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
25585        // The canonical per-`:contratos` WIT-world-reference scalar pin:
25586        // [`WitContract::world_ref`] must return the `:contratos :wit`
25587        // field byte-for-byte, borrowed from the typed slot's own
25588        // [`String`] storage. Sibling of the peer per-`:contratos`
25589        // [`WitContract::source`] / [`WitContract::destination`]
25590        // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
25591        // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
25592        // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
25593        // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
25594        // "the substrate-primitive accessor must byte-equal the raw
25595        // field access verbatim across every author-declared value"
25596        // discipline extended to the per-`:contratos` WIT-world arm.
25597        // Pins against a future silent detour that re-canonicalized the
25598        // WIT world reference (an accidental `.to_lowercase()` pass that
25599        // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
25600        // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
25601        // gate is already lowercase-prefixed so any re-normalization is
25602        // redundant + a drift surface between the validator and the
25603        // accessor), an M4-promotion-shape rewrite that formatted a
25604        // typed WIT-world enum through [`Display`] and silently drifted
25605        // the printer output from the source `caixa.lisp`, or a per-
25606        // cluster WIT-alias rewrite that didn't land on the peer field-
25607        // access sites. Five values sweep the shape-dispatch accept-set
25608        // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
25609        // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
25610        // `wasi:keyvalue/`).
25611        for (wit, endpoint, subject, slot) in [
25612            ("wasi:http/proxy", Some("/lookup"), None, None),
25613            ("http:proxy", Some("/health"), None, None),
25614            ("nats:pub-sub", None, Some("orders.paid"), None),
25615            ("kafka:events", None, Some("checkout-events"), None),
25616            ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
25617        ] {
25618            let c = WitContract {
25619                de: "cart".into(),
25620                para: "downstream".into(),
25621                wit: wit.into(),
25622                endpoint: endpoint.map(str::to_string),
25623                subject: subject.map(str::to_string),
25624                slot: slot.map(str::to_string),
25625            };
25626            assert_eq!(
25627                c.world_ref(),
25628                wit,
25629                "WitContract::world_ref must return :contratos :wit \
25630                 verbatim (got {:?}, expected {wit:?})",
25631                c.world_ref(),
25632            );
25633            assert_eq!(
25634                c.world_ref(),
25635                c.wit.as_str(),
25636                "WitContract::world_ref must byte-equal the .wit field \
25637                 access",
25638            );
25639        }
25640    }
25641
25642    #[test]
25643    fn wit_contract_world_ref_borrows_from_wit_storage() {
25644        // The borrow-not-copy pin: [`WitContract::world_ref`] must
25645        // return a `&str` slice that borrows from the typed slot's own
25646        // [`String`] storage — same-address invariant with
25647        // `c.wit.as_str()`. Pins against a future silent detour that
25648        // allocated a fresh `String` (`self.wit.clone()` in the body
25649        // would type-check but silently drop the borrow, and every
25650        // downstream consumer that assumed the returned slice outlives
25651        // `&self` would break on a stale-reference use-after-free — the
25652        // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
25653        // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
25654        // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
25655        // / [`is_pubsub`][WitContract::is_pubsub] /
25656        // [`is_store`][WitContract::is_store] methods route through —
25657        // each borrow from the WitContract's own storage and each would
25658        // silently misbehave if this accessor produced a detached copy).
25659        // Peer of the sibling per-`:contratos` [`WitContract::source`] /
25660        // [`WitContract::destination`] and per-`:entrada`
25661        // [`Entrada::destination`] / [`Entrada::hostname`] and
25662        // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
25663        // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
25664        let c = WitContract {
25665            de: "cart".into(),
25666            para: "catalog".into(),
25667            wit: "wasi:http/proxy".into(),
25668            endpoint: Some("/lookup".into()),
25669            subject: None,
25670            slot: None,
25671        };
25672        let world = c.world_ref();
25673        let wit_slice = c.wit.as_str();
25674        assert_eq!(
25675            world.as_ptr(),
25676            wit_slice.as_ptr(),
25677            "WitContract::world_ref must borrow from the .wit String's \
25678             backing storage — a fresh allocation here means the \
25679             accessor no longer names the substrate-primitive typed \
25680             dispatch and every downstream consumer would silently carry \
25681             a detached copy",
25682        );
25683        assert_eq!(
25684            world.len(),
25685            wit_slice.len(),
25686            "WitContract::world_ref and .wit.as_str() must byte-equal in \
25687             length as well as in address",
25688        );
25689    }
25690
25691    #[test]
25692    fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
25693        // Sibling-triple invariant pin composing all three per-`:contratos`
25694        // substrate-primitive typed dispatches — [`WitContract::source`]
25695        // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
25696        // [`WitContract::world_ref`] — at the joint
25697        // `(source(), destination(), world_ref())` call shape every
25698        // renderer that fans on per-edge caller-callee-shape identity
25699        // keys off. The invariant, evaluated per-contract:
25700        //
25701        //   (c.source(), c.destination(), c.world_ref())
25702        //   == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
25703        //
25704        // Closes the last unlifted per-`:contratos` scalar axis — every
25705        // downstream consumer that reads the triple now routes through
25706        // exactly three typed dispatches on the substrate primitive,
25707        // not two typed + one open-coded field access. A future refactor
25708        // that silently split any one accessor's projection (an
25709        // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
25710        // canonicalization that didn't reach the peer `source`/
25711        // `destination` arms, an accidental `source()` per-cluster
25712        // caller-alias rewrite that didn't land on the `world_ref` peer)
25713        // surfaces at caixa-core build time. Peer of the sibling per-
25714        // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
25715        // per-`:entrada` `(hostname(), destination())` (6db982c /
25716        // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
25717        // axes, extended to the per-`:contratos` triple.
25718        for (de, para, wit, endpoint, subject, slot) in [
25719            (
25720                "cart",
25721                "catalog",
25722                "wasi:http/proxy",
25723                Some("/lookup"),
25724                None,
25725                None,
25726            ),
25727            (
25728                "checkout",
25729                "orders",
25730                "nats:pub-sub",
25731                None,
25732                Some("orders.paid"),
25733                None,
25734            ),
25735            (
25736                "cart",
25737                "kv",
25738                "wasi:keyvalue/store",
25739                None,
25740                None,
25741                Some("carts/{cart_id}"),
25742            ),
25743            (
25744                "orders-v2",
25745                "inventory-v3",
25746                "http:proxy",
25747                Some("/reserve"),
25748                None,
25749                None,
25750            ),
25751        ] {
25752            let c = WitContract {
25753                de: de.into(),
25754                para: para.into(),
25755                wit: wit.into(),
25756                endpoint: endpoint.map(str::to_string),
25757                subject: subject.map(str::to_string),
25758                slot: slot.map(str::to_string),
25759            };
25760            assert_eq!(
25761                (c.source(), c.destination(), c.world_ref()),
25762                (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
25763                "(WitContract::source, ::destination, ::world_ref) must \
25764                 project (.de, .para, .wit) verbatim across every author-\
25765                 declared triple (got ({:?}, {:?}, {:?}), expected \
25766                 ({de:?}, {para:?}, {wit:?}))",
25767                c.source(),
25768                c.destination(),
25769                c.world_ref(),
25770            );
25771        }
25772    }
25773
25774    #[test]
25775    fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
25776        // The canonical per-`:contratos` owned-form caller-callee-pair
25777        // pin: [`WitContract::edge_pair`] must return the
25778        // `(source(), destination())` tuple in owned form byte-for-byte,
25779        // projected through the lifted [`WitContract::source`] /
25780        // [`WitContract::destination`] scalar accessors. Pins the
25781        // composite-projection invariant on the per-`:contratos`
25782        // mesh-slot atom — every author-declared `(de, para)` pair must
25783        // round-trip verbatim through the substrate primitive's typed
25784        // dispatch, so the nine [`AplicacaoError`] diagnostic-
25785        // construction sites the accessor now feeds
25786        // ([`AplicacaoError::EmptyWit`],
25787        // [`AplicacaoError::ContratoEndpointEmpty`],
25788        // [`AplicacaoError::ContratoEndpointNotAbsolute`],
25789        // [`AplicacaoError::ContratoEndpointInvalid`],
25790        // [`AplicacaoError::ContratoSubjectEmpty`],
25791        // [`AplicacaoError::ContratoSubjectInvalid`],
25792        // [`AplicacaoError::ContratoSlotEmpty`],
25793        // [`AplicacaoError::ContratoSlotInvalid`],
25794        // [`AplicacaoError::ContratoDuplicate`]) all read the same
25795        // `(de, para)` label pair every author sees at the source
25796        // `caixa.lisp`. Pins against a future silent detour that swapped
25797        // the `.0` / `.1` arms (an accidental `(destination(),
25798        // source())` re-order in the body would silently invert every
25799        // downstream diagnostic's `de:` / `para:` label pair, silently
25800        // reversing the direction of every operator-facing typed error
25801        // arrow), a fresh-allocation shape drift (an accidental
25802        // `.to_string()` on one arm but not the other would leave the
25803        // owned/borrowed pair mismatched vs. the sibling `source()` /
25804        // `destination()` returns), or an M4 per-cluster caller/callee-
25805        // alias rewrite that landed on `source()` without reaching
25806        // `destination()` (or vice versa). Peer of the sibling per-
25807        // `:contratos` `(source, destination, world_ref)` triple
25808        // pin above on the mesh-slot-atom scalar-value axes, extended
25809        // to the owned-form pair-projection axis.
25810        for (de, para, wit, endpoint, subject, slot) in [
25811            (
25812                "cart",
25813                "catalog",
25814                "wasi:http/proxy",
25815                Some("/lookup"),
25816                None,
25817                None,
25818            ),
25819            (
25820                "checkout",
25821                "orders",
25822                "nats:pub-sub",
25823                None,
25824                Some("orders.paid"),
25825                None,
25826            ),
25827            (
25828                "cart",
25829                "kv",
25830                "wasi:keyvalue/store",
25831                None,
25832                None,
25833                Some("carts/{cart_id}"),
25834            ),
25835            (
25836                "orders-v2",
25837                "inventory-v3",
25838                "http:proxy",
25839                Some("/reserve"),
25840                None,
25841                None,
25842            ),
25843        ] {
25844            let c = WitContract {
25845                de: de.into(),
25846                para: para.into(),
25847                wit: wit.into(),
25848                endpoint: endpoint.map(str::to_string),
25849                subject: subject.map(str::to_string),
25850                slot: slot.map(str::to_string),
25851            };
25852            assert_eq!(
25853                c.edge_pair(),
25854                (de.to_string(), para.to_string()),
25855                "WitContract::edge_pair must return (:contratos :de, \
25856                 :contratos :para) as an owned tuple verbatim (got {:?}, \
25857                 expected ({de:?}, {para:?}))",
25858                c.edge_pair(),
25859            );
25860        }
25861    }
25862
25863    #[test]
25864    fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
25865        // The composition pin: [`WitContract::edge_pair`] must return
25866        // exactly `(source().to_string(), destination().to_string())` —
25867        // the owned form of the sibling accessor pair — so any future
25868        // refactor that silently re-authored the caller-arm / callee-arm
25869        // projection to bypass the lifted scalar accessors (an accidental
25870        // `(self.de.clone(), self.para.clone())` regression back to the
25871        // raw field-access shape, an M4-typed-caller-enum `Display`
25872        // re-canonicalization on `source()` that didn't reach
25873        // `edge_pair()`, a per-cluster alias rewrite the operator lands
25874        // on `destination()` without reaching this composite projection)
25875        // trips at caixa-core build time. Pins the "typed dispatch
25876        // composes with typed dispatch, not with raw field access"
25877        // discipline every downstream diagnostic-construction site now
25878        // routes through — a `de:` / `para:` label pair whose
25879        // projection silently drifted off the substrate primitive's
25880        // scalar accessors would silently split the diagnostic's self-
25881        // locating signal from the source `caixa.lisp` author's view.
25882        // Peer of the sibling per-`:politicas` `is_empty` /
25883        // `validate_politicas` accessor-routing-pin family on the M3
25884        // mesh-slot family (18575, 18739, 18918, 19140, 19371).
25885        let c = WitContract {
25886            de: "cart".into(),
25887            para: "catalog".into(),
25888            wit: "wasi:http/proxy".into(),
25889            endpoint: Some("/lookup".into()),
25890            subject: None,
25891            slot: None,
25892        };
25893        assert_eq!(
25894            c.edge_pair(),
25895            (c.source().to_string(), c.destination().to_string()),
25896            "WitContract::edge_pair must compose exactly \
25897             (source().to_string(), destination().to_string()) — a \
25898             bypass of either sibling accessor here would silently \
25899             decouple the composite-projection axis from the \
25900             substrate-primitive scalar accessors every downstream \
25901             consumer routes through",
25902        );
25903    }
25904
25905    #[test]
25906    fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
25907     {
25908        // The canonical per-`:contratos` owned-form
25909        // caller-callee-world-ref-triple pin:
25910        // [`WitContract::edge_triple`] must return the
25911        // `(source(), destination(), world_ref())` tuple in owned form
25912        // byte-for-byte, projected through the lifted
25913        // [`WitContract::source`] / [`WitContract::destination`] /
25914        // [`WitContract::world_ref`] scalar accessors. Pins the
25915        // composite-projection invariant on the per-`:contratos`
25916        // mesh-slot atom — every author-declared `(de, para, wit)`
25917        // triple must round-trip verbatim through the substrate
25918        // primitive's typed dispatch, so the nine
25919        // [`AplicacaoError`] diagnostic-construction sites the
25920        // accessor now feeds (the [`WitTarget`]-dispatch's eight
25921        // wrong-target / missing-target / invalid-wit / capability-
25922        // with-payload arms in [`WitContract::target`], plus the
25923        // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
25924        // diagnostic constructor in [`AplicacaoSpec::validate`]) all
25925        // read the same `(de, para, wit)` triple every author sees at
25926        // the source `caixa.lisp`. Pins against a future silent
25927        // detour that swapped any two arms (an accidental `(destination(),
25928        // source(), world_ref())` re-order in the body would silently
25929        // invert every downstream diagnostic's `de:` / `para:` label
25930        // pair, silently reversing the direction of every operator-
25931        // facing typed error arrow), a fresh-allocation shape drift
25932        // (an accidental `.to_string()` skipped on one arm would leave
25933        // the owned/borrowed triple mismatched vs. the sibling
25934        // `source()` / `destination()` / `world_ref()` returns), or an
25935        // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
25936        // canonicalization pass that landed on one accessor without
25937        // reaching the peers. Peer of the sibling per-`:contratos`
25938        // caller-callee-pair
25939        // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
25940        // pin on the mesh-slot-atom composite-projection axis,
25941        // extended to the triple-projection axis.
25942        for (de, para, wit, endpoint, subject, slot) in [
25943            (
25944                "cart",
25945                "catalog",
25946                "wasi:http/proxy",
25947                Some("/lookup"),
25948                None,
25949                None,
25950            ),
25951            (
25952                "checkout",
25953                "orders",
25954                "nats:pub-sub",
25955                None,
25956                Some("orders.paid"),
25957                None,
25958            ),
25959            (
25960                "cart",
25961                "kv",
25962                "wasi:keyvalue/store",
25963                None,
25964                None,
25965                Some("carts/{cart_id}"),
25966            ),
25967            (
25968                "orders-v2",
25969                "inventory-v3",
25970                "http:proxy",
25971                Some("/reserve"),
25972                None,
25973                None,
25974            ),
25975        ] {
25976            let c = WitContract {
25977                de: de.into(),
25978                para: para.into(),
25979                wit: wit.into(),
25980                endpoint: endpoint.map(str::to_string),
25981                subject: subject.map(str::to_string),
25982                slot: slot.map(str::to_string),
25983            };
25984            assert_eq!(
25985                c.edge_triple(),
25986                (de.to_string(), para.to_string(), wit.to_string()),
25987                "WitContract::edge_triple must return (:contratos :de, \
25988                 :contratos :para, :contratos :wit) as an owned triple \
25989                 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
25990                c.edge_triple(),
25991            );
25992        }
25993    }
25994
25995    #[test]
25996    fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
25997        // The composition pin: [`WitContract::edge_triple`] must return
25998        // exactly `(source().to_string(), destination().to_string(),
25999        // world_ref().to_string())` — the owned form of the sibling
26000        // scalar-accessor triple — so any future refactor that silently
26001        // re-authored one arm's projection to bypass the lifted scalar
26002        // accessors (an accidental `(self.de.clone(), self.para.clone(),
26003        // self.wit.clone())` regression back to the raw field-access
26004        // shape the internal `edge` closure and the ContratoDuplicate
26005        // diagnostic both carried before this lift landed, an
26006        // M4-typed-caller-enum `Display` re-canonicalization on
26007        // `source()` that didn't reach `edge_triple()`, a per-cluster
26008        // alias rewrite the operator lands on `destination()` /
26009        // `world_ref()` without reaching this composite projection)
26010        // trips at caixa-core build time. Pins the "typed dispatch
26011        // composes with typed dispatch, not with raw field access"
26012        // discipline every downstream diagnostic-construction site now
26013        // routes through — a `de:` / `para:` / `wit:` triple whose
26014        // projection silently drifted off the substrate primitive's
26015        // scalar accessors would silently split the diagnostic's self-
26016        // locating signal from the source `caixa.lisp` author's view.
26017        // Peer of the sibling per-`:contratos` edge_pair composition-
26018        // pin above on the mesh-slot-atom composite-projection axis.
26019        let c = WitContract {
26020            de: "cart".into(),
26021            para: "catalog".into(),
26022            wit: "wasi:http/proxy".into(),
26023            endpoint: Some("/lookup".into()),
26024            subject: None,
26025            slot: None,
26026        };
26027        assert_eq!(
26028            c.edge_triple(),
26029            (
26030                c.source().to_string(),
26031                c.destination().to_string(),
26032                c.world_ref().to_string(),
26033            ),
26034            "WitContract::edge_triple must compose exactly \
26035             (source().to_string(), destination().to_string(), \
26036             world_ref().to_string()) — a bypass of any sibling accessor \
26037             here would silently decouple the composite-projection axis \
26038             from the substrate-primitive scalar accessors every \
26039             downstream consumer routes through",
26040        );
26041    }
26042
26043    #[test]
26044    fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
26045        // The canonical semantics-pin: [`WitContract::edge_triple`] must
26046        // project the full `(de, para, wit)` identity of a `:contratos`
26047        // edge — the sub-triple every triple-carrying
26048        // [`AplicacaoError::Contrato*`] diagnostic weaves into its
26049        // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
26050        // missing-target, capability-with-payload, invalid-wit, and the
26051        // duplicate-gate). Rejects a drift in shape (an accidental
26052        // silent detour that returned a `(de, para)` pair or added an
26053        // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
26054        // would trip here because the return type would no longer
26055        // pattern-match the eight `let (de, para, wit) = edge();`
26056        // destructures the [`WitContract::target`] dispatch feeds off
26057        // + the paired duplicate-gate `let (de, para, wit) =
26058        // c.edge_triple();` destructure in
26059        // [`AplicacaoSpec::validate`]). Peer of the sibling per-
26060        // `:contratos` caller-callee-pair pin above extended to the
26061        // triple projection surface: closes the "one composite
26062        // accessor per typed diagnostic-construction sub-tuple"
26063        // discipline on the per-`:contratos` mesh-slot-atom axis.
26064        let c = WitContract {
26065            de: "checkout".into(),
26066            para: "orders".into(),
26067            wit: "nats:pub-sub".into(),
26068            endpoint: None,
26069            subject: Some("orders.paid".into()),
26070            slot: None,
26071        };
26072        let (de, para, wit) = c.edge_triple();
26073        assert_eq!(de, "checkout");
26074        assert_eq!(para, "orders");
26075        assert_eq!(wit, "nats:pub-sub");
26076    }
26077
26078    #[test]
26079    fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
26080     {
26081        // The composition pin: [`WitContract::identity`] must return
26082        // exactly `(source(), destination(), world_ref(), endpoint(),
26083        // subject(), slot())` — the borrowed form of the six-scalar-
26084        // accessor identity axis. Any future refactor that silently
26085        // re-authored one arm's projection to bypass a scalar accessor
26086        // (a `self.de.as_str()` regression back to raw field access on
26087        // any of the three required arms, a `self.endpoint.as_deref()`
26088        // regression on any of the three optional arms, an M4 per-
26089        // cluster caller/callee-alias rewrite the operator lands on
26090        // `source()` / `destination()` without reaching this composite
26091        // projection) trips at caixa-core build time. Sweeps four
26092        // permutations of the WIT-shape × payload lattice — HTTP with
26093        // endpoint, pub-sub with subject, store with slot, payload-less
26094        // capability — so every payload arm is exercised. Peer of the
26095        // sibling per-`:contratos`
26096        // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
26097        // composition pin on the mesh-slot-atom composite-projection
26098        // axis; extends the discipline from the (de, para, wit) prefix
26099        // onto the full-identity axis carrying the three payload arms.
26100        for (de, para, wit, endpoint, subject, slot) in [
26101            (
26102                "cart",
26103                "catalog",
26104                "wasi:http/proxy",
26105                Some("/lookup"),
26106                None,
26107                None,
26108            ),
26109            (
26110                "checkout",
26111                "orders",
26112                "nats:pub-sub",
26113                None,
26114                Some("orders.paid"),
26115                None,
26116            ),
26117            (
26118                "cart",
26119                "kv",
26120                "wasi:keyvalue/store",
26121                None,
26122                None,
26123                Some("carts/{cart_id}"),
26124            ),
26125            ("audit", "sink", "wasi:logging", None, None, None),
26126        ] {
26127            let c = WitContract {
26128                de: de.into(),
26129                para: para.into(),
26130                wit: wit.into(),
26131                endpoint: endpoint.map(str::to_owned),
26132                subject: subject.map(str::to_owned),
26133                slot: slot.map(str::to_owned),
26134            };
26135            assert_eq!(
26136                c.identity(),
26137                (
26138                    c.source(),
26139                    c.destination(),
26140                    c.world_ref(),
26141                    c.endpoint(),
26142                    c.subject(),
26143                    c.slot(),
26144                ),
26145                "WitContract::identity must compose exactly \
26146                 (source(), destination(), world_ref(), endpoint(), \
26147                 subject(), slot()) — a bypass of any sibling accessor \
26148                 here would silently decouple the identity-projection \
26149                 axis from the substrate-primitive scalar accessors \
26150                 every dedup-key consumer routes through",
26151            );
26152        }
26153    }
26154
26155    #[test]
26156    fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
26157        // The canonical semantics-pin: [`WitContract::identity`] must
26158        // project the six-axis (de, para, wit, endpoint, subject, slot)
26159        // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
26160        // gate keys off — two `WitContract`s that agree on all six axes
26161        // are the same typed edge declared twice, the graph-edge
26162        // analogue of duplicate `:membros` / `:placement :clusters` /
26163        // `:entrada :paths` entries. Rejects a shape drift (an
26164        // accidental silent detour that returned a prefix tuple or
26165        // added an extra field) by pattern-matching the six-arm shape.
26166        // Peer of the sibling per-`:contratos`
26167        // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
26168        // pin extended from the (de, para, wit) prefix onto the full
26169        // six-axis identity that the dedup key rides.
26170        let c = WitContract {
26171            de: "cart".into(),
26172            para: "catalog".into(),
26173            wit: "wasi:http/proxy".into(),
26174            endpoint: Some("/products/:id".into()),
26175            subject: None,
26176            slot: None,
26177        };
26178        let (de, para, wit, endpoint, subject, slot) = c.identity();
26179        assert_eq!(de, "cart");
26180        assert_eq!(para, "catalog");
26181        assert_eq!(wit, "wasi:http/proxy");
26182        assert_eq!(endpoint, Some("/products/:id"));
26183        assert_eq!(subject, None);
26184        assert_eq!(slot, None);
26185
26186        // Two byte-identical contracts must produce equal identities —
26187        // the dedup key's foundational invariant.
26188        let c2 = c.clone();
26189        assert_eq!(c.identity(), c2.identity());
26190
26191        // Any change on any of the six axes must break the identity —
26192        // sweeps by mutating one axis at a time.
26193        let mut mutated = c.clone();
26194        mutated.de = "search".into();
26195        assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
26196        let mut mutated = c.clone();
26197        mutated.para = "warehouse".into();
26198        assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
26199        let mut mutated = c.clone();
26200        mutated.wit = "http:legacy".into();
26201        assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
26202        let mut mutated = c.clone();
26203        mutated.endpoint = Some("/search".into());
26204        assert_ne!(
26205            c.identity(),
26206            mutated.identity(),
26207            "endpoint axis must partition"
26208        );
26209        let mut mutated = c.clone();
26210        mutated.subject = Some("orders.paid".into());
26211        assert_ne!(
26212            c.identity(),
26213            mutated.identity(),
26214            "subject axis must partition"
26215        );
26216        let mut mutated = c;
26217        mutated.slot = Some("carts/{id}".into());
26218        assert_ne!(mutated.identity().5, None, "slot axis must partition");
26219    }
26220
26221    #[test]
26222    fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
26223        // The canonical per-`:contratos` structural-self-edge pin:
26224        // [`WitContract::is_self_loop`] must return `true` when the
26225        // `:de` and `:para` fields agree byte-for-byte, across every
26226        // WIT-shape variant the per-edge shape family carries. Pins
26227        // the shape-agnostic identity-space partition the
26228        // [`AplicacaoSpec::validate`] self-edge gate at
26229        // caixa-core/src/aplicacao.rs:5559 fires against — all four
26230        // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
26231        // under the same one predicate. Four permutations sweep the
26232        // accept-set: HTTP with endpoint, pub-sub with subject, KV
26233        // store with slot, and payload-less capability.
26234        for (nome, wit, endpoint, subject, slot) in [
26235            ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
26236            ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
26237            (
26238                "kv",
26239                "wasi:keyvalue/store",
26240                None,
26241                None,
26242                Some("carts/{cart_id}"),
26243            ),
26244            ("audit", "wasi:logging", None, None, None),
26245        ] {
26246            let c = WitContract {
26247                de: nome.into(),
26248                para: nome.into(),
26249                wit: wit.into(),
26250                endpoint: endpoint.map(str::to_string),
26251                subject: subject.map(str::to_string),
26252                slot: slot.map(str::to_string),
26253            };
26254            assert!(
26255                c.is_self_loop(),
26256                "WitContract::is_self_loop must return true when \
26257                 :contratos :de == :contratos :para (got false on \
26258                 {nome:?} under {wit:?})",
26259            );
26260        }
26261    }
26262
26263    #[test]
26264    fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
26265        // The complement pin: [`WitContract::is_self_loop`] must return
26266        // `false` on every well-shaped inter-Servico contract (the
26267        // author-intended `:contratos` shape MESH-COMPOSITION §III.1
26268        // names — "Servico A calls Servico B" between two distinct
26269        // graph nodes). Pins against a future silent detour that
26270        // inverted the predicate (an accidental `!= ` swap for `==`
26271        // would silently reject every legitimate inter-Servico edge
26272        // and admit every self-edge — the exact inversion of the
26273        // author-intended shape). Four permutations sweep the same
26274        // WIT-shape accept-set the sibling positive-arm test carries.
26275        for (de, para, wit, endpoint, subject, slot) in [
26276            (
26277                "cart",
26278                "catalog",
26279                "wasi:http/proxy",
26280                Some("/lookup"),
26281                None,
26282                None,
26283            ),
26284            (
26285                "checkout",
26286                "orders",
26287                "nats:pub-sub",
26288                None,
26289                Some("orders.paid"),
26290                None,
26291            ),
26292            (
26293                "cart",
26294                "kv",
26295                "wasi:keyvalue/store",
26296                None,
26297                None,
26298                Some("carts/{cart_id}"),
26299            ),
26300            ("audit", "sink", "wasi:logging", None, None, None),
26301        ] {
26302            let c = WitContract {
26303                de: de.into(),
26304                para: para.into(),
26305                wit: wit.into(),
26306                endpoint: endpoint.map(str::to_string),
26307                subject: subject.map(str::to_string),
26308                slot: slot.map(str::to_string),
26309            };
26310            assert!(
26311                !c.is_self_loop(),
26312                "WitContract::is_self_loop must return false when \
26313                 :contratos :de differs from :contratos :para (got true \
26314                 on {de:?} → {para:?} under {wit:?})",
26315            );
26316        }
26317    }
26318
26319    #[test]
26320    fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
26321        // The composition pin: [`WitContract::is_self_loop`] must
26322        // resolve to exactly `self.source() == self.destination()` —
26323        // the equality probe of the sibling scalar-accessor pair — so
26324        // any future refactor that silently re-authored the predicate
26325        // to bypass the lifted scalar accessors (an accidental
26326        // `self.de == self.para` regression back to the raw field-
26327        // access shape, an M4-typed-caller-enum identity-comparison
26328        // rule that landed on `source()` without reaching
26329        // `destination()`, a per-cluster alias rewrite the operator
26330        // pins on `destination()` without reaching this predicate)
26331        // trips at caixa-core build time. Pins the "typed dispatch
26332        // composes with typed dispatch, not with raw field access"
26333        // discipline the sibling [`WitContract::edge_pair`] /
26334        // [`WitContract::edge_triple`] composite-projection accessors
26335        // already carry, extended onto the per-edge endpoint-equality
26336        // predicate axis. Positive and complement arms both fire.
26337        let self_edge = WitContract {
26338            de: "cart".into(),
26339            para: "cart".into(),
26340            wit: "wasi:http/proxy".into(),
26341            endpoint: Some("/lookup".into()),
26342            subject: None,
26343            slot: None,
26344        };
26345        assert_eq!(
26346            self_edge.is_self_loop(),
26347            self_edge.source() == self_edge.destination(),
26348            "WitContract::is_self_loop must compose exactly \
26349             `source() == destination()` — a bypass of either sibling \
26350             accessor here would silently decouple the endpoint-\
26351             equality predicate from the substrate-primitive scalar \
26352             accessors every downstream consumer routes through",
26353        );
26354        let inter_edge = WitContract {
26355            de: "cart".into(),
26356            para: "catalog".into(),
26357            wit: "wasi:http/proxy".into(),
26358            endpoint: Some("/lookup".into()),
26359            subject: None,
26360            slot: None,
26361        };
26362        assert_eq!(
26363            inter_edge.is_self_loop(),
26364            inter_edge.source() == inter_edge.destination(),
26365            "WitContract::is_self_loop must compose exactly \
26366             `source() == destination()` on the complement arm too",
26367        );
26368    }
26369
26370    #[test]
26371    fn wit_contract_target_wit_shape_gate_routes_through_world_ref_accessor() {
26372        // The composition pin: [`WitContract::target`]'s invalid-wit
26373        // value-shape gate must feed the reason string through the
26374        // lifted [`WitContract::world_ref`] scalar accessor — the same
26375        // typed dispatch on the substrate primitive every peer
26376        // per-`:contratos` payload-carrier extraction in the same
26377        // method body already routes through
26378        // ([`WitContract::endpoint`] on the HTTP-arm target extraction,
26379        // [`WitContract::subject`] on the pub-sub-arm target extraction,
26380        // [`WitContract::slot`] on the store-arm target extraction) and
26381        // every peer composite-projection accessor
26382        // ([`WitContract::edge_pair`], [`WitContract::edge_triple`],
26383        // [`WitContract::identity`]) already composes from. Any future
26384        // refactor that silently re-authored the gate to bypass the
26385        // lifted accessor (an accidental `&self.wit` regression back to
26386        // the raw field-access shape, an M4-typed-`WitWorld` `Display`
26387        // re-canonicalization on `world_ref()` that didn't reach this
26388        // gate, a per-CR lowercasing canonicalization pass the M4
26389        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
26390        // per-tenant that lands on `world_ref()` without reaching this
26391        // gate) would silently split the invalid-wit diagnostic reason
26392        // from the substrate-primitive projection every downstream
26393        // consumer routes through. Same "typed dispatch composes with
26394        // typed dispatch, not with raw field access" discipline the
26395        // sibling
26396        // [`wit_contract_is_self_loop_routes_through_source_destination_accessors`]
26397        // pin already carries on the endpoint-equality predicate axis,
26398        // extended onto the invalid-wit value-shape gate axis inside
26399        // the same [`WitContract::target`] body. Closes the last
26400        // unlifted raw-field-access site inside `impl WitContract`.
26401        //
26402        // The fixture carries `:wit "WASI:HTTP/proxy"` — the canonical
26403        // uppercase-typo footgun the pre-c4213a4 shape silently demoted
26404        // to a capability-only edge; the value-shape gate rejects it
26405        // through [`crate::render::is_wit_world_ref`] on the substrate
26406        // primitive's ASCII-lowercase-only accept-set, with a
26407        // parser-shaped reason string the test asserts round-trips
26408        // byte-for-byte between the direct-dispatch call (through the
26409        // predicate on the accessor's projection) and the
26410        // [`WitContract::target`] gate's produced reason field.
26411        let c = WitContract {
26412            de: "cart".into(),
26413            para: "catalog".into(),
26414            wit: "WASI:HTTP/proxy".into(),
26415            endpoint: Some("/lookup".into()),
26416            subject: None,
26417            slot: None,
26418        };
26419        let err = c.target().unwrap_err();
26420        let AplicacaoError::ContratoWitInvalid {
26421            ref de,
26422            ref para,
26423            ref wit,
26424            ref reason,
26425        } = err
26426        else {
26427            panic!("expected ContratoWitInvalid, got {err:?}");
26428        };
26429        assert_eq!(de, "cart");
26430        assert_eq!(para, "catalog");
26431        assert_eq!(wit, "WASI:HTTP/proxy");
26432        let expected_reason = crate::render::is_wit_world_ref(c.world_ref()).unwrap_err();
26433        assert_eq!(
26434            *reason, expected_reason,
26435            "WitContract::target's invalid-wit value-shape gate reason \
26436             must compose exactly is_wit_world_ref(self.world_ref()) — \
26437             a bypass here (e.g. a raw `&self.wit` field-access \
26438             regression, or a divergent predicate on a different \
26439             projection) would silently decouple the invalid-wit \
26440             diagnostic's reason field from the substrate-primitive \
26441             scalar accessor every peer per-`:contratos` extraction in \
26442             the same method body already routes through",
26443        );
26444    }
26445
26446    #[test]
26447    fn wit_contract_is_self_loop_predicate_is_const_fn() {
26448        // Fail-before-pass-after pin on the [`WitContract::is_self_loop`]
26449        // caller-callee identity-space predicate's `const`-eval-surface
26450        // posture. The wrapper below dispatches through
26451        // [`WitContract::is_self_loop`] and is well-formed only when the
26452        // callee is itself `pub const fn` — any future accidental
26453        // downgrade to non-`const` fails the wrapper at caixa-core build
26454        // time with E0015 (`cannot call non-const method`), strictly
26455        // stronger than a runtime `assert!` and strictly stronger than a
26456        // module-scope `const _: () = assert!(…)` pin (the type's
26457        // `String` / `Option<String>` carriers rule out `const`-context
26458        // value construction; the `const fn` wrapper is the load-bearing
26459        // shape that side-steps the destructor-in-const restriction on
26460        // the value axis while still pinning the `const`-fn posture on
26461        // the callee — mirror of the sibling
26462        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
26463        // (279823b) and
26464        // [`wit_contract_identity_projection_accessor_is_const_fn`]
26465        // (1ab648c) pins' discipline verbatim on the peer scalar-
26466        // accessor and composite-projection surfaces). Closes the last
26467        // unlifted per-`:contratos` shape/identity predicate on the
26468        // const-eval surface — the peer WIT-shape-partition family
26469        // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
26470        // [`WitContract::is_store`] / [`WitContract::is_capability`]
26471        // already carried the `pub const fn` posture on the peer
26472        // WIT-world-ref classifier axis (d46420c / 84c2325 / 279823b);
26473        // this pin extends the same posture onto the caller-callee
26474        // identity-space partition. Sweeps every WIT-shape arm on both
26475        // the equal-endpoints (self-edge) and distinct-endpoints
26476        // (inter-edge) arms of the identity-space partition, plus one
26477        // same-length distinct-byte pair to pin the mid-loop `!=` arm
26478        // past the leading length-mismatch shortcut.
26479        const fn is_self_loop_via_const_fn(c: &WitContract) -> bool {
26480            c.is_self_loop()
26481        }
26482        let mk = |de: &str, para: &str, wit: &str| WitContract {
26483            de: de.into(),
26484            para: para.into(),
26485            wit: wit.into(),
26486            endpoint: None,
26487            subject: None,
26488            slot: None,
26489        };
26490        for (nome, wit) in [
26491            ("cart", "wasi:http/proxy"),
26492            ("checkout", "nats:pub-sub"),
26493            ("kv", "wasi:keyvalue/store"),
26494            ("audit", "wasi:logging"),
26495        ] {
26496            let self_edge = mk(nome, nome, wit);
26497            assert!(
26498                is_self_loop_via_const_fn(&self_edge),
26499                "self-edge {nome:?} under {wit:?}"
26500            );
26501            assert_eq!(
26502                is_self_loop_via_const_fn(&self_edge),
26503                self_edge.is_self_loop()
26504            );
26505        }
26506        for (de, para, wit) in [
26507            ("cart", "catalog", "wasi:http/proxy"),
26508            ("checkout", "orders", "nats:pub-sub"),
26509            ("cart", "kv", "wasi:keyvalue/store"),
26510            ("audit", "sink", "wasi:logging"),
26511        ] {
26512            let inter_edge = mk(de, para, wit);
26513            assert!(
26514                !is_self_loop_via_const_fn(&inter_edge),
26515                "inter-edge {de:?}→{para:?} under {wit:?}",
26516            );
26517            assert_eq!(
26518                is_self_loop_via_const_fn(&inter_edge),
26519                inter_edge.is_self_loop()
26520            );
26521        }
26522        // Same-length distinct-byte pair — pins the mid-loop `!=` arm
26523        // past the leading `a.len() != b.len()` shortcut so the const-fn
26524        // wrapper exercises every arm of the byte-slice equality loop.
26525        let same_len_pair = mk("cart", "kart", "wasi:http/proxy");
26526        assert!(
26527            !is_self_loop_via_const_fn(&same_len_pair),
26528            "same-length distinct-byte"
26529        );
26530        assert_eq!(
26531            is_self_loop_via_const_fn(&same_len_pair),
26532            same_len_pair.is_self_loop()
26533        );
26534    }
26535
26536    #[test]
26537    fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
26538        // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
26539        // pin: [`WitContract::endpoint`] must return the `:contratos
26540        // :endpoint` field byte-for-byte, borrowed from the typed slot's
26541        // own `Option<String>` storage. Peer of the sibling
26542        // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
26543        // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
26544        // mesh-slot `Option<String>` optional-scalar axes — same "the
26545        // substrate-primitive accessor must byte-equal the raw field
26546        // access verbatim across every author-declared value" discipline
26547        // extended to the per-`:contratos` HTTP-payload-carrier arm.
26548        // Pins against a future silent detour that re-canonicalized the
26549        // endpoint (an accidental percent-encoding pass that didn't
26550        // reach the peer field-access site at the dedup key, a per-CR
26551        // fully-qualified prefix rewrite the operator authors on one
26552        // consumer without the other, or an M4 typed-path-template
26553        // `Display` re-canonicalization that silently drifted the
26554        // printer output from the source `caixa.lisp`). Four values
26555        // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
26556        // gate upstream admits (short root-path, dashed, param-shaped,
26557        // deep-hierarchy).
26558        for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
26559            let c = WitContract {
26560                de: "cart".into(),
26561                para: "catalog".into(),
26562                wit: "wasi:http/proxy".into(),
26563                endpoint: Some(endpoint.into()),
26564                subject: None,
26565                slot: None,
26566            };
26567            assert_eq!(
26568                c.endpoint(),
26569                Some(endpoint),
26570                "WitContract::endpoint must return :contratos :endpoint \
26571                 verbatim (got {:?}, expected Some({endpoint:?}))",
26572                c.endpoint(),
26573            );
26574            assert_eq!(
26575                c.endpoint(),
26576                c.endpoint.as_deref(),
26577                "WitContract::endpoint must byte-equal the .endpoint \
26578                 field's `.as_deref()` projection",
26579            );
26580        }
26581    }
26582
26583    #[test]
26584    fn wit_contract_endpoint_none_when_field_is_none() {
26585        // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
26586        // payload-carrier accessor pin: when the typed slot is absent —
26587        // the canonical shape under a non-HTTP `:wit` world per the
26588        // [`WitContract::target`]-enforced shape ↔ target partition
26589        // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
26590        // carries `:slot`, [`WitTarget::Capability`] carries none) —
26591        // [`WitContract::endpoint`] must return `None`. Pins against a
26592        // future silent detour that projected the absent slot to a
26593        // `Some("")` empty-string default (the canonical `Option<String>`
26594        // → `String` collapse footgun the sibling M2
26595        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
26596        // emptiness predicates already guard on the peer M2 typed-slot
26597        // surfaces), a `Some("None")` stringified-None round-trip, or a
26598        // `Some` arm whose contents were derived from a sibling slot (an
26599        // accidental fallback to the `:subject` / `:slot` payload that
26600        // read the pub-sub / store payload into the endpoint axis).
26601        // Three contracts sweep the accept-set every non-HTTP `:wit`
26602        // world lands on — pub-sub NATS, key/value, and payload-less
26603        // capability.
26604        for (wit, subject, slot) in [
26605            ("nats:pub-sub", Some("orders.paid"), None),
26606            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
26607            ("wasi:cli/environment", None, None),
26608        ] {
26609            let c = WitContract {
26610                de: "cart".into(),
26611                para: "downstream".into(),
26612                wit: wit.into(),
26613                endpoint: None,
26614                subject: subject.map(str::to_string),
26615                slot: slot.map(str::to_string),
26616            };
26617            assert!(
26618                c.endpoint().is_none(),
26619                "WitContract::endpoint must return None when the typed \
26620                 slot is absent under :wit {wit:?} (got {:?})",
26621                c.endpoint(),
26622            );
26623            assert_eq!(
26624                c.endpoint(),
26625                c.endpoint.as_deref(),
26626                "WitContract::endpoint must byte-equal the .endpoint \
26627                 field's `.as_deref()` projection in the absent arm",
26628            );
26629        }
26630    }
26631
26632    #[test]
26633    fn wit_contract_endpoint_borrows_from_endpoint_storage() {
26634        // The borrow-not-copy pin: [`WitContract::endpoint`] must return
26635        // an `Option<&str>` whose `Some` arm borrows from the typed
26636        // slot's own [`String`] storage — same-address invariant with
26637        // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
26638        // detour that allocated a fresh `String`
26639        // (`self.endpoint.clone().map(...)` in the body would type-check
26640        // but silently drop the borrow, and every downstream consumer
26641        // that assumed the returned slice outlives `&self` would break
26642        // on a stale-reference use-after-free — the [`WitContract::target`]
26643        // Http-arm payload extraction rebinds the returned `Option<&str>`
26644        // through `.ok_or_else(...)` and threads the `&str` payload into
26645        // [`WitTarget::Http { endpoint: &'a str }`], the
26646        // [`AplicacaoSpec::validate`] duplicate-`:contratos`
26647        // [`ContratoIdentity`] dedup key threads the returned
26648        // `Option<&str>` into the six-tuple's HTTP arm — each borrow
26649        // from the WitContract's own storage and each would silently
26650        // misbehave if this accessor produced a detached copy). Peer of
26651        // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
26652        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
26653        // shaped optional-scalar axes — first extension of the
26654        // `Option<&str>` borrow-not-copy discipline onto the
26655        // per-`:contratos` HTTP-shaped payload-carrier axis.
26656        let c = WitContract {
26657            de: "cart".into(),
26658            para: "catalog".into(),
26659            wit: "wasi:http/proxy".into(),
26660            endpoint: Some("/lookup".into()),
26661            subject: None,
26662            slot: None,
26663        };
26664        let ep = c.endpoint().expect("Some arm");
26665        let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
26666        assert_eq!(
26667            ep.as_ptr(),
26668            storage_slice.as_ptr(),
26669            "WitContract::endpoint must borrow from the .endpoint \
26670             String's backing storage — a fresh allocation here means \
26671             the accessor no longer names the substrate-primitive typed \
26672             dispatch and every downstream consumer would silently \
26673             carry a detached copy",
26674        );
26675        assert_eq!(
26676            ep.len(),
26677            storage_slice.len(),
26678            "WitContract::endpoint and .endpoint.as_deref() must byte-\
26679             equal in length as well as in address",
26680        );
26681    }
26682
26683    #[test]
26684    fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
26685        // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
26686        // pin: [`WitContract::subject`] must return the `:contratos
26687        // :subject` field byte-for-byte, borrowed from the typed slot's
26688        // own `Option<String>` storage. Peer of the sibling per-`:contratos`
26689        // [`WitContract::endpoint`] (7020470) accessor pin on the M3
26690        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
26691        // optional-scalar axis — same "the substrate-primitive accessor
26692        // must byte-equal the raw field access verbatim across every
26693        // author-declared value" discipline extended to the pub-sub arm.
26694        // Pins against a future silent detour that re-canonicalized the
26695        // subject (an accidental `.to_lowercase()` normalization that
26696        // didn't reach the peer field-access site at the dedup key, a
26697        // per-CR fully-qualified prefix rewrite the operator authors on
26698        // one consumer without the other, or an M4 typed-subject-template
26699        // `Display` re-canonicalization that silently drifted the printer
26700        // output from the source `caixa.lisp`). Four values sweep the
26701        // NATS accept-set every pub-sub author-declared subject lands on
26702        // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
26703        for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
26704            let c = WitContract {
26705                de: "cart".into(),
26706                para: "notifier".into(),
26707                wit: "nats:pub-sub".into(),
26708                endpoint: None,
26709                subject: Some(subject.into()),
26710                slot: None,
26711            };
26712            assert_eq!(
26713                c.subject(),
26714                Some(subject),
26715                "WitContract::subject must return :contratos :subject \
26716                 verbatim (got {:?}, expected Some({subject:?}))",
26717                c.subject(),
26718            );
26719            assert_eq!(
26720                c.subject(),
26721                c.subject.as_deref(),
26722                "WitContract::subject must byte-equal the .subject \
26723                 field's `.as_deref()` projection",
26724            );
26725        }
26726    }
26727
26728    #[test]
26729    fn wit_contract_subject_none_when_field_is_none() {
26730        // The absent-`:subject` arm of the per-`:contratos` pub-sub-
26731        // shaped payload-carrier accessor pin: when the typed slot is
26732        // absent — the canonical shape under a non-pub-sub `:wit` world
26733        // per the [`WitContract::target`]-enforced shape ↔ target
26734        // partition ([`WitTarget::Http`] carries `:endpoint`,
26735        // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
26736        // carries none) — [`WitContract::subject`] must return `None`.
26737        // Pins against a future silent detour that projected the absent
26738        // slot to a `Some("")` empty-string default (the canonical
26739        // `Option<String>` → `String` collapse footgun the sibling M2
26740        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
26741        // emptiness predicates already guard on the peer M2 typed-slot
26742        // surfaces), a `Some("None")` stringified-None round-trip, or a
26743        // `Some` arm whose contents were derived from a sibling slot (an
26744        // accidental fallback to the `:endpoint` / `:slot` payload that
26745        // read the HTTP / store payload into the subject axis). Three
26746        // contracts sweep the accept-set every non-pub-sub `:wit` world
26747        // lands on — HTTP proxy, key/value store, and payload-less
26748        // capability.
26749        for (wit, endpoint, slot) in [
26750            ("wasi:http/proxy", Some("/lookup"), None),
26751            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
26752            ("wasi:cli/environment", None, None),
26753        ] {
26754            let c = WitContract {
26755                de: "cart".into(),
26756                para: "downstream".into(),
26757                wit: wit.into(),
26758                endpoint: endpoint.map(str::to_string),
26759                subject: None,
26760                slot: slot.map(str::to_string),
26761            };
26762            assert!(
26763                c.subject().is_none(),
26764                "WitContract::subject must return None when the typed \
26765                 slot is absent under :wit {wit:?} (got {:?})",
26766                c.subject(),
26767            );
26768            assert_eq!(
26769                c.subject(),
26770                c.subject.as_deref(),
26771                "WitContract::subject must byte-equal the .subject \
26772                 field's `.as_deref()` projection in the absent arm",
26773            );
26774        }
26775    }
26776
26777    #[test]
26778    fn wit_contract_subject_borrows_from_subject_storage() {
26779        // The borrow-not-copy pin: [`WitContract::subject`] must return
26780        // an `Option<&str>` whose `Some` arm borrows from the typed
26781        // slot's own [`String`] storage — same-address invariant with
26782        // `c.subject.as_deref().unwrap()`. Pins against a future silent
26783        // detour that allocated a fresh `String`
26784        // (`self.subject.clone().map(...)` in the body would type-check
26785        // but silently drop the borrow, and every downstream consumer
26786        // that assumed the returned slice outlives `&self` would break
26787        // on a stale-reference use-after-free — the [`WitContract::target`]
26788        // PubSub-arm payload extraction rebinds the returned
26789        // `Option<&str>` through `.ok_or_else(...)` and threads the
26790        // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
26791        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
26792        // [`ContratoIdentity`] dedup key threads the returned
26793        // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
26794        // from the WitContract's own storage and each would silently
26795        // misbehave if this accessor produced a detached copy). Peer of
26796        // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
26797        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
26798        // shaped optional-scalar axis — second extension of the
26799        // `Option<&str>` borrow-not-copy discipline onto the
26800        // per-`:contratos` payload-carrier family, this time on the
26801        // pub-sub arm.
26802        let c = WitContract {
26803            de: "cart".into(),
26804            para: "notifier".into(),
26805            wit: "nats:pub-sub".into(),
26806            endpoint: None,
26807            subject: Some("orders.paid".into()),
26808            slot: None,
26809        };
26810        let sub = c.subject().expect("Some arm");
26811        let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
26812        assert_eq!(
26813            sub.as_ptr(),
26814            storage_slice.as_ptr(),
26815            "WitContract::subject must borrow from the .subject \
26816             String's backing storage — a fresh allocation here means \
26817             the accessor no longer names the substrate-primitive typed \
26818             dispatch and every downstream consumer would silently \
26819             carry a detached copy",
26820        );
26821        assert_eq!(
26822            sub.len(),
26823            storage_slice.len(),
26824            "WitContract::subject and .subject.as_deref() must byte-\
26825             equal in length as well as in address",
26826        );
26827    }
26828
26829    #[test]
26830    fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
26831        // The canonical per-`:contratos` key/value-store-shaped
26832        // `:slot`-scalar pin: [`WitContract::slot`] must return the
26833        // `:contratos :slot` field byte-for-byte, borrowed from the
26834        // typed slot's own `Option<String>` storage. Peer of the
26835        // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
26836        // [`WitContract::subject`] (90de675) accessor pins on the M3
26837        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
26838        // optional-scalar axis — same "the substrate-primitive
26839        // accessor must byte-equal the raw field access verbatim
26840        // across every author-declared value" discipline extended to
26841        // the store arm. Pins against a future silent detour that
26842        // re-canonicalized the slot template (an accidental
26843        // `.to_lowercase()` bucket-prefix normalization that didn't
26844        // reach the peer field-access site at the dedup key, a per-CR
26845        // fully-qualified prefix rewrite the operator authors on one
26846        // consumer without the other, or an M4 typed-key-template
26847        // `Display` re-canonicalization that silently drifted the
26848        // printer output from the source `caixa.lisp`). Four values
26849        // sweep the wasi:keyvalue accept-set every store-shaped
26850        // author-declared slot lands on (flat bucket, single-param
26851        // template, multi-param template, nested-hierarchy template).
26852        for slot in [
26853            "sessions",
26854            "carts/{cart_id}",
26855            "orders/{tenant}/{order_id}",
26856            "cache/tenant-a/orders/{id}",
26857        ] {
26858            let c = WitContract {
26859                de: "cart".into(),
26860                para: "kv".into(),
26861                wit: "wasi:keyvalue/store".into(),
26862                endpoint: None,
26863                subject: None,
26864                slot: Some(slot.into()),
26865            };
26866            assert_eq!(
26867                c.slot(),
26868                Some(slot),
26869                "WitContract::slot must return :contratos :slot \
26870                 verbatim (got {:?}, expected Some({slot:?}))",
26871                c.slot(),
26872            );
26873            assert_eq!(
26874                c.slot(),
26875                c.slot.as_deref(),
26876                "WitContract::slot must byte-equal the .slot field's \
26877                 `.as_deref()` projection",
26878            );
26879        }
26880    }
26881
26882    #[test]
26883    fn wit_contract_slot_none_when_field_is_none() {
26884        // The absent-`:slot` arm of the per-`:contratos` store-shaped
26885        // payload-carrier accessor pin: when the typed slot is absent —
26886        // the canonical shape under a non-store `:wit` world per the
26887        // [`WitContract::target`]-enforced shape ↔ target partition
26888        // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
26889        // carries `:subject`, [`WitTarget::Capability`] carries none) —
26890        // [`WitContract::slot`] must return `None`. Pins against a
26891        // future silent detour that projected the absent slot to a
26892        // `Some("")` empty-string default (the canonical
26893        // `Option<String>` → `String` collapse footgun the sibling M2
26894        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
26895        // emptiness predicates already guard on the peer M2 typed-slot
26896        // surfaces), a `Some("None")` stringified-None round-trip, or
26897        // a `Some` arm whose contents were derived from a sibling
26898        // slot (an accidental fallback to the `:endpoint` / `:subject`
26899        // payload that read the HTTP / pub-sub payload into the store
26900        // axis). Three contracts sweep the accept-set every non-store
26901        // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
26902        // payload-less capability.
26903        for (wit, endpoint, subject) in [
26904            ("wasi:http/proxy", Some("/lookup"), None),
26905            ("nats:pub-sub", None, Some("orders.paid")),
26906            ("wasi:cli/environment", None, None),
26907        ] {
26908            let c = WitContract {
26909                de: "cart".into(),
26910                para: "downstream".into(),
26911                wit: wit.into(),
26912                endpoint: endpoint.map(str::to_string),
26913                subject: subject.map(str::to_string),
26914                slot: None,
26915            };
26916            assert!(
26917                c.slot().is_none(),
26918                "WitContract::slot must return None when the typed \
26919                 slot is absent under :wit {wit:?} (got {:?})",
26920                c.slot(),
26921            );
26922            assert_eq!(
26923                c.slot(),
26924                c.slot.as_deref(),
26925                "WitContract::slot must byte-equal the .slot field's \
26926                 `.as_deref()` projection in the absent arm",
26927            );
26928        }
26929    }
26930
26931    #[test]
26932    fn wit_contract_slot_borrows_from_slot_storage() {
26933        // The borrow-not-copy pin: [`WitContract::slot`] must return
26934        // an `Option<&str>` whose `Some` arm borrows from the typed
26935        // slot's own [`String`] storage — same-address invariant with
26936        // `c.slot.as_deref().unwrap()`. Pins against a future silent
26937        // detour that allocated a fresh `String`
26938        // (`self.slot.clone().map(...)` in the body would type-check
26939        // but silently drop the borrow, and every downstream consumer
26940        // that assumed the returned slice outlives `&self` would
26941        // break on a stale-reference use-after-free — the
26942        // [`WitContract::target`] Store-arm payload extraction rebinds
26943        // the returned `Option<&str>` through `.ok_or_else(...)` and
26944        // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
26945        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
26946        // [`ContratoIdentity`] dedup key threads the returned
26947        // `Option<&str>` into the six-tuple's store arm — each borrow
26948        // from the WitContract's own storage and each would silently
26949        // misbehave if this accessor produced a detached copy). Peer
26950        // of the sibling per-`:contratos` [`WitContract::endpoint`]
26951        // (7020470) / [`WitContract::subject`] (90de675)
26952        // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
26953        // shaped optional-scalar axis — third and final extension of
26954        // the `Option<&str>` borrow-not-copy discipline onto the
26955        // per-`:contratos` payload-carrier family, this time on the
26956        // store arm.
26957        let c = WitContract {
26958            de: "cart".into(),
26959            para: "kv".into(),
26960            wit: "wasi:keyvalue/store".into(),
26961            endpoint: None,
26962            subject: None,
26963            slot: Some("carts/{cart_id}".into()),
26964        };
26965        let slot = c.slot().expect("Some arm");
26966        let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
26967        assert_eq!(
26968            slot.as_ptr(),
26969            storage_slice.as_ptr(),
26970            "WitContract::slot must borrow from the .slot String's \
26971             backing storage — a fresh allocation here means the \
26972             accessor no longer names the substrate-primitive typed \
26973             dispatch and every downstream consumer would silently \
26974             carry a detached copy",
26975        );
26976        assert_eq!(
26977            slot.len(),
26978            storage_slice.len(),
26979            "WitContract::slot and .slot.as_deref() must byte-equal \
26980             in length as well as in address",
26981        );
26982    }
26983
26984    #[test]
26985    fn membro_nome_returns_caixa_byte_equal_across_permutations() {
26986        // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
26987        // [`Membro::nome`] must return the `:membros :caixa` field
26988        // byte-for-byte, borrowed from the typed slot's own [`String`]
26989        // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
26990        // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
26991        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
26992        // slot-atom scalar-value axes — same "the substrate-primitive
26993        // accessor must byte-equal the raw field access verbatim across
26994        // every author-declared value" discipline extended to the
26995        // per-`:membros` member-identity arm. Pins against a future
26996        // silent detour that re-normalized the member identity (an
26997        // accidental `.to_lowercase()` — every `:membros :caixa` is
26998        // validated as a DNS-1123 label upstream via
26999        // [`validate_membro_caixa`], so any re-normalization is
27000        // redundant + a drift surface between the validator and the
27001        // accessor), a namespace-prefix rewrite (an accidental
27002        // `format!("{namespace}/{caixa}")` per-CR fully-qualified
27003        // rewrite that didn't land on the peer axes), or a per-cluster
27004        // alias stamp the operator authors on one consumer without the
27005        // other. Four values sweep the accept-set the DNS-1123 gate
27006        // upstream admits (short single-word / dashed / v-suffixed
27007        // member names).
27008        for name in ["cart", "checkout", "catalog", "orders-v2"] {
27009            let m = Membro {
27010                caixa: name.into(),
27011                versao: "^0.1".into(),
27012            };
27013            assert_eq!(
27014                m.nome(),
27015                name,
27016                "Membro::nome must return :membros :caixa verbatim \
27017                 (got {:?}, expected {name:?})",
27018                m.nome(),
27019            );
27020            assert_eq!(
27021                m.nome(),
27022                m.caixa.as_str(),
27023                "Membro::nome must byte-equal the .caixa field access",
27024            );
27025        }
27026    }
27027
27028    #[test]
27029    fn membro_nome_borrows_from_caixa_storage() {
27030        // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
27031        // slice that borrows from the typed slot's own [`String`]
27032        // storage — same-address invariant with `m.caixa.as_str()`. Pins
27033        // against a future silent detour that allocated a fresh `String`
27034        // (`self.caixa.clone()` in the body would type-check but
27035        // silently drop the borrow, and every downstream consumer that
27036        // assumed the returned slice outlives `&self` would break on a
27037        // stale-reference use-after-free — the `HashSet<&str>` collector
27038        // at [`AplicacaoSpec::validate`]'s `names` seed, the
27039        // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
27040        // [`AplicacaoSpec::detect_sync_cycles`], the
27041        // [`crate::render::insert_first_seen`] dedup key at
27042        // [`AplicacaoSpec::validate_membros`] — each borrow from the
27043        // Membro's own storage and each would silently misbehave if
27044        // this accessor produced a detached copy). Peer of the sibling
27045        // per-`:contratos` [`WitContract::source`] /
27046        // [`WitContract::destination`] and per-`:entrada`
27047        // [`Entrada::destination`] borrow-invariant pins on the mesh-
27048        // slot-atom scalar-value axes.
27049        let m = Membro {
27050            caixa: "checkout".into(),
27051            versao: "^0.1".into(),
27052        };
27053        let name = m.nome();
27054        let caixa_slice = m.caixa.as_str();
27055        assert_eq!(
27056            name.as_ptr(),
27057            caixa_slice.as_ptr(),
27058            "Membro::nome must borrow from the .caixa String's backing \
27059             storage — a fresh allocation here means the accessor no \
27060             longer names the substrate-primitive typed dispatch and \
27061             every downstream consumer would silently carry a detached \
27062             copy",
27063        );
27064        assert_eq!(
27065            name.len(),
27066            caixa_slice.len(),
27067            "Membro::nome and .caixa.as_str() must byte-equal in length \
27068             as well as in address",
27069        );
27070    }
27071
27072    #[test]
27073    fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
27074        // The canonical per-`:membros` member-`:versao`-scalar pin:
27075        // [`Membro::versao_requirement`] must return the
27076        // `:membros :versao` field byte-for-byte, borrowed from the typed
27077        // slot's own [`String`] storage. Sibling of the peer
27078        // `membro_nome_returns_caixa_byte_equal_across_permutations`
27079        // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
27080        // — same "the substrate-primitive accessor must byte-equal the
27081        // raw field access verbatim across every author-declared value"
27082        // discipline extended to the per-`:membros` member-`:versao`
27083        // requirement-string arm. Pins against a future silent detour
27084        // that re-canonicalized the requirement (an accidental
27085        // `.to_string()` via [`parse_requirement`] → [`Display`] round-
27086        // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
27087        // drifted the printer output away from the source `caixa.lisp`,
27088        // an accidental whitespace trim on `"^ 0.1"` that no consumer
27089        // ever produced from the field-access side, an accidental
27090        // per-cluster lacre-projected concrete-version rewrite that
27091        // didn't land on the peer field-access sites). Five values sweep
27092        // the accept-set the shared
27093        // [`crate::render::require_valid_versao_requirement`] gate
27094        // admits (caret / tilde / exact / wildcard / bare-major).
27095        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
27096            let m = Membro {
27097                caixa: "cart".into(),
27098                versao: req.into(),
27099            };
27100            assert_eq!(
27101                m.versao_requirement(),
27102                req,
27103                "Membro::versao_requirement must return :membros :versao \
27104                 verbatim (got {:?}, expected {req:?})",
27105                m.versao_requirement(),
27106            );
27107            assert_eq!(
27108                m.versao_requirement(),
27109                m.versao.as_str(),
27110                "Membro::versao_requirement must byte-equal the .versao \
27111                 field access",
27112            );
27113        }
27114    }
27115
27116    #[test]
27117    fn membro_versao_requirement_borrows_from_versao_storage() {
27118        // The borrow-not-copy pin: [`Membro::versao_requirement`] must
27119        // return a `&str` slice that borrows from the typed slot's own
27120        // [`String`] storage — same-address invariant with
27121        // `m.versao.as_str()`. Pins against a future silent detour that
27122        // allocated a fresh `String` (`self.versao.clone()` in the body
27123        // would type-check but silently drop the borrow, and every
27124        // downstream consumer that assumed the returned slice outlives
27125        // `&self` would break on a stale-reference use-after-free). Peer
27126        // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
27127        // per-`:contratos` [`WitContract::source`] /
27128        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
27129        // [`Entrada::destination`] (6db982c) borrow-invariant pins on
27130        // the mesh-slot-atom scalar-value axes.
27131        let m = Membro {
27132            caixa: "checkout".into(),
27133            versao: "^0.1".into(),
27134        };
27135        let req = m.versao_requirement();
27136        let versao_slice = m.versao.as_str();
27137        assert_eq!(
27138            req.as_ptr(),
27139            versao_slice.as_ptr(),
27140            "Membro::versao_requirement must borrow from the .versao \
27141             String's backing storage — a fresh allocation here means \
27142             the accessor no longer names the substrate-primitive typed \
27143             dispatch and every downstream consumer would silently carry \
27144             a detached copy",
27145        );
27146        assert_eq!(
27147            req.len(),
27148            versao_slice.len(),
27149            "Membro::versao_requirement and .versao.as_str() must byte-\
27150             equal in length as well as in address",
27151        );
27152    }
27153
27154    #[test]
27155    fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
27156        // Sibling-pair invariant pin composing both per-`:membros`
27157        // substrate-primitive typed dispatches — [`Membro::nome`]
27158        // (4a32abf) and [`Membro::versao_requirement`] — at the joint
27159        // `(nome(), versao_requirement())` call shape every renderer
27160        // that fans on per-member identity + version pin keys off. The
27161        // invariant, evaluated per-member:
27162        //
27163        //   (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
27164        //
27165        // Closes the last unlifted per-`:membros` scalar axis — every
27166        // downstream consumer that reads the pair now routes through
27167        // exactly two typed dispatches on the substrate primitive, not
27168        // one typed + one open-coded field access. A future refactor
27169        // that silently split either accessor's projection (an
27170        // accidental `nome()` namespace-prefix rewrite that didn't
27171        // reach the peer, an accidental `versao_requirement()` lacre-
27172        // projected concrete-version rewrite that didn't land on the
27173        // `nome()` peer) surfaces at caixa-core build time. Peer of the
27174        // sibling per-`:entrada` `(hostname(), destination())` and
27175        // per-`:contratos` `(source(), destination())` pair invariants
27176        // on the mesh-slot-atom scalar-value axes.
27177        for (caixa, versao) in [
27178            ("cart", "^0.1"),
27179            ("checkout", "~0.1.2"),
27180            ("catalog", "0.1.0"),
27181            ("orders-v2", "*"),
27182        ] {
27183            let m = Membro {
27184                caixa: caixa.into(),
27185                versao: versao.into(),
27186            };
27187            assert_eq!(
27188                (m.nome(), m.versao_requirement()),
27189                (m.caixa.as_str(), m.versao.as_str()),
27190                "(Membro::nome, Membro::versao_requirement) must project \
27191                 (.caixa, .versao) verbatim across every author-declared \
27192                 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
27193                m.nome(),
27194                m.versao_requirement(),
27195            );
27196        }
27197    }
27198
27199    #[test]
27200    fn validate_membros_empty_gate_routes_through_nome_accessor() {
27201        // Composition pin: [`AplicacaoSpec::validate_membros`]'s
27202        // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
27203        // not the raw `.caixa` field access. Structurally: setting
27204        // ONLY the `.caixa` field to `""` on an otherwise-well-formed
27205        // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
27206        // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
27207        // (i.e. the empty string) — so the emptiness predicate the
27208        // refusal arm reaches under is the accessor-projected value,
27209        // not a peer field that would silently drift under a future
27210        // accessor-side rewrite.
27211        //
27212        // Pins against a future silent detour that (a) re-derived the
27213        // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
27214        // instead of `self.nome().is_empty()`, silently disagreeing with
27215        // every peer consumer (the `validate_membro_caixa(m.nome())`
27216        // per-slot helper — which now owns the emptiness arm outright —
27217        // the dedup-key `insert_first_seen(&mut seen, m.nome(), …)`
27218        // below, and the emit-side per-`programs[]` entry-`name:` at
27219        // caixa-mesh/src/lib.rs:133), (b) accessor-side introduced a
27220        // per-tenant alias arm the caller was unaware of, silently
27221        // rewriting an author-declared `:caixa "checkout"` to `""` —
27222        // the raw-field-access gate would fail-open while the
27223        // accessor-routed peer consumers would fail-closed, splitting
27224        // the diagnostic from the actual failure surface.
27225        //
27226        // Peer of the sibling
27227        // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
27228        // (c0110f1) composition pin — same "the shape-gate predicate
27229        // must route through the substrate-primitive typed dispatch"
27230        // discipline extended onto the per-`:membros` empty-`:caixa`
27231        // refusal-arm axis. Closes the last unlifted `.caixa` production-
27232        // code read site on `Membro` — after this converge every
27233        // caixa-core `.caixa` field access outside the accessor's own
27234        // body is either a test-side field-setter (in-module tests
27235        // constructing invalid-shape inputs) or a doc-comment reference.
27236        let mut s = three_member_spec();
27237        s.membros[1].caixa = String::new();
27238        assert!(
27239            s.membros[1].nome().is_empty(),
27240            "Membro::nome must byte-equal the .caixa field access — an \
27241             accessor-side detour that no longer projects the raw field \
27242             would silently split this drift-detection test from the \
27243             validate() refusal arm",
27244        );
27245        assert_eq!(
27246            s.membros[1].nome(),
27247            s.membros[1].caixa.as_str(),
27248            "Membro::nome and .caixa.as_str() must byte-equal on an \
27249             empty-`:caixa` entry — the emptiness gate keys off the \
27250             accessor by construction",
27251        );
27252        assert_eq!(
27253            s.validate().unwrap_err(),
27254            AplicacaoError::MembroCaixaEmpty,
27255            "validate_membros' emptiness gate must fire MembroCaixaEmpty \
27256             on an entry whose accessor-projected `nome()` is empty",
27257        );
27258    }
27259
27260    #[test]
27261    fn validate_membros_empty_arm_is_owned_by_validate_membro_caixa_alone() {
27262        // Convergence pin, paired with the deletion of the redundant
27263        // outer `if m.nome().is_empty() { return Err(MembroCaixaEmpty); }`
27264        // guard formerly inline in [`AplicacaoSpec::validate_membros`]:
27265        // after the collapse, the `MembroCaixaEmpty` refusal on every
27266        // empty-`:caixa` per-member input is owned solely by the shared
27267        // [`validate_membro_caixa`] helper — the same per-slot substrate
27268        // primitive routing empty + shape arms uniformly onto
27269        // [`crate::render::require_valid_dns_1123_label`] that every
27270        // peer M3 mesh-slot per-slot gate ([`validate_placement_cluster`]
27271        // on `:placement :clusters`, [`validate_entrada_para`] on
27272        // `:entrada :para`, [`validate_contrato_caixa`] on `:contratos
27273        // :de`/`:para`) already funnels its own empty arm through.
27274        //
27275        // Two arms pin the collapse:
27276        //
27277        //   (1) The per-slot helper called with the empty string returns
27278        //       byte-equal to the previous inline arm's diagnostic — so
27279        //       a future rebrand of [`validate_membro_caixa`] that
27280        //       (accidentally) stopped returning [`MembroCaixaEmpty`] on
27281        //       empty input (an inadvertent switch to
27282        //       [`AplicacaoError::MembroCaixaInvalid`] via the parse-side
27283        //       `on_invalid` arm, an accidental re-routing to a shared
27284        //       `MembroError::Empty` under a future error-hierarchy
27285        //       flattening) would silently split the drift from the
27286        //       [`validate_membros`] caller and surface the wrong
27287        //       diagnostic on the author-facing empty-`:caixa` footgun.
27288        //
27289        //   (2) The whole-spec equivalence: an empty-`:caixa` entry
27290        //       anywhere in the `:membros` fan-out still trips
27291        //       [`MembroCaixaEmpty`] end-to-end via [`validate`], with
27292        //       no outer inline guard needed. Same shape as the
27293        //       whole-spec arm on [`validate_placement_cluster`] /
27294        //       [`validate_entrada_para`] / [`validate_contrato_caixa`]:
27295        //       one substrate primitive per axis, folding empty + shape.
27296        //
27297        // Same PRIME DIRECTIVE convergence the peer per-slot gate lifts
27298        // (906a5c6 validate_contratos, 20cd523 validate_entrada, f03a154
27299        // MeshPolicy::validate) already extend across the M3 mesh-slot
27300        // family — closes the last per-slot gate on the family carrying
27301        // an inline empty guard duplicating its own helper.
27302        assert_eq!(
27303            validate_membro_caixa(""),
27304            Err(AplicacaoError::MembroCaixaEmpty),
27305            "validate_membro_caixa must own the empty arm outright — a \
27306             regression here would silently split MembroCaixaEmpty from \
27307             validate_membros' end-to-end refusal shape after the outer \
27308             inline `if m.nome().is_empty()` guard collapse",
27309        );
27310        let mut s = three_member_spec();
27311        s.membros[0].caixa = String::new();
27312        assert_eq!(
27313            s.validate().unwrap_err(),
27314            AplicacaoError::MembroCaixaEmpty,
27315            "an empty-`:caixa` :membros head entry must trip \
27316             MembroCaixaEmpty end-to-end via validate() with the outer \
27317             inline guard removed — the per-slot helper alone is now \
27318             load-bearing",
27319        );
27320        let mut s = three_member_spec();
27321        s.membros[2].caixa = String::new();
27322        assert_eq!(
27323            s.validate().unwrap_err(),
27324            AplicacaoError::MembroCaixaEmpty,
27325            "an empty-`:caixa` :membros tail entry must trip \
27326             MembroCaixaEmpty end-to-end via validate() with the outer \
27327             inline guard removed — the per-slot helper alone reaches \
27328             every fan-out position",
27329        );
27330    }
27331
27332    #[test]
27333    fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
27334        // The canonical per-`:placement` Akka-cluster-sharding
27335        // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
27336        // the `:placement :shard-key` field byte-for-byte, borrowed
27337        // from the typed slot's own `Option<String>` storage. Peer of
27338        // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
27339        // per-`:contratos` [`WitContract::source`] /
27340        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
27341        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
27342        // slot-atom scalar-value axes — same "the substrate-primitive
27343        // accessor must byte-equal the raw field access verbatim across
27344        // every author-declared value" discipline extended to the
27345        // per-`:placement` Akka-cluster-sharding key extractor arm.
27346        // Pins against a future silent detour that re-normalized the
27347        // key (an accidental `.to_lowercase()` — every non-empty
27348        // `:shard-key` is validated as a printable-ASCII single-token
27349        // reference upstream via [`validate_placement_shard_key`], so
27350        // any re-normalization is redundant + a drift surface between
27351        // the validator and the accessor), a per-cluster alias rewrite
27352        // the operator authors on one consumer without the other, or an
27353        // accidental variable-prefix strip (`$tenantId` → `tenantId`)
27354        // that didn't land on the peer field-access sites. Four values
27355        // sweep the accept-set the shape gate admits — bare identifier,
27356        // `$`-prefixed variable, dotted path, `${}`-quoted variable —
27357        // the four canonical Akka-style entity-id extractor shapes the
27358        // future M4 cluster-sharding reconciler hashes.
27359        for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
27360            let p = Placement {
27361                estrategia: PlacementStrategy::Sharded,
27362                clusters: vec!["rio".into()],
27363                affinity: None,
27364                shard_key: Some(key.into()),
27365            };
27366            assert_eq!(
27367                p.shard_key(),
27368                Some(key),
27369                "Placement::shard_key must return :placement :shard-key \
27370                 verbatim (got {:?}, expected Some({key:?}))",
27371                p.shard_key(),
27372            );
27373            assert_eq!(
27374                p.shard_key(),
27375                p.shard_key.as_deref(),
27376                "Placement::shard_key must byte-equal the .shard_key \
27377                 field's `.as_deref()` projection",
27378            );
27379        }
27380    }
27381
27382    #[test]
27383    fn placement_shard_key_none_when_field_is_none() {
27384        // The absent-`:shard-key` arm of the per-`:placement`
27385        // Akka-cluster-sharding accessor pin: when the typed slot is
27386        // absent — the canonical shape under `:estrategia Replicated` /
27387        // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
27388        // enforced `shard_key.is_some() == matches!(estrategia,
27389        // Sharded)` partition — [`Placement::shard_key`] must return
27390        // `None`. Pins against a future silent detour that projected
27391        // the absent slot to a `Some("")` empty-string default (the
27392        // canonical `Option<String>` → `String` collapse footgun the
27393        // sibling M2 [`crate::LimitsSpec::is_empty`] /
27394        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
27395        // already guard on the peer M2 typed-slot surfaces), a
27396        // `Some("None")` stringified-None round-trip, or a `Some` arm
27397        // whose contents were derived from a sibling slot (an
27398        // accidental fallback to `estrategia.as_str()` that read the
27399        // strategy discriminator into the key axis). Two placements
27400        // sweep the accept-set every `validate`-passing non-`Sharded`
27401        // shape lands on — `Replicated` (Erlang/OTP distributed-app
27402        // takeover) and `SingleNode` (single-node hosting).
27403        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
27404            let p = Placement {
27405                estrategia,
27406                clusters: vec!["rio".into()],
27407                affinity: None,
27408                shard_key: None,
27409            };
27410            assert!(
27411                p.shard_key().is_none(),
27412                "Placement::shard_key must return None when the typed \
27413                 slot is absent under :estrategia {estrategia:?} (got {:?})",
27414                p.shard_key(),
27415            );
27416            assert_eq!(
27417                p.shard_key(),
27418                p.shard_key.as_deref(),
27419                "Placement::shard_key must byte-equal the .shard_key \
27420                 field's `.as_deref()` projection in the absent arm",
27421            );
27422        }
27423    }
27424
27425    #[test]
27426    fn placement_shard_key_borrows_from_shard_key_storage() {
27427        // The borrow-not-copy pin: [`Placement::shard_key`] must return
27428        // an `Option<&str>` whose `Some` arm borrows from the typed
27429        // slot's own [`String`] storage — same-address invariant with
27430        // `p.shard_key.as_deref().unwrap()`. Pins against a future
27431        // silent detour that allocated a fresh `String`
27432        // (`self.shard_key.clone().map(...)` in the body would type-
27433        // check but silently drop the borrow, and every downstream
27434        // consumer that assumed the returned slice outlives `&self`
27435        // would break on a stale-reference use-after-free — the
27436        // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
27437        // gate's `Some(k)`-bound match arm reads `k: &str` under the
27438        // accessor's return type and would silently misbehave if this
27439        // accessor produced a detached copy). Peer of the sibling
27440        // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
27441        // [`WitContract::source`] / [`WitContract::destination`]
27442        // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
27443        // (6db982c) borrow-invariant pins on the mesh-slot-atom
27444        // scalar-value axes — first extension of the discipline onto
27445        // an `Option<String>`-shaped optional-scalar axis.
27446        let p = Placement {
27447            estrategia: PlacementStrategy::Sharded,
27448            clusters: vec!["rio".into()],
27449            affinity: None,
27450            shard_key: Some("tenantId".into()),
27451        };
27452        let key = p.shard_key().expect("Some arm");
27453        let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
27454        assert_eq!(
27455            key.as_ptr(),
27456            storage_slice.as_ptr(),
27457            "Placement::shard_key must borrow from the .shard_key \
27458             String's backing storage — a fresh allocation here means \
27459             the accessor no longer names the substrate-primitive typed \
27460             dispatch and every downstream consumer would silently \
27461             carry a detached copy",
27462        );
27463        assert_eq!(
27464            key.len(),
27465            storage_slice.len(),
27466            "Placement::shard_key and .shard_key.as_deref() must byte-\
27467             equal in length as well as in address",
27468        );
27469    }
27470
27471    #[test]
27472    fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
27473        // The canonical per-`:placement` M3-Adaptive-compression-hint
27474        // scalar pin: [`Placement::affinity`] must return the
27475        // `:placement :affinity` field byte-for-byte, borrowed from the
27476        // typed slot's own `Option<String>` storage. Peer of the sibling
27477        // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
27478        // pin on the sibling `Option<&str>` optional-scalar axis — same
27479        // "the substrate-primitive accessor must byte-equal the raw
27480        // field access verbatim across every author-declared value"
27481        // discipline extended to the peer per-`:placement` M3-Adaptive-
27482        // compression-hint arm. Pins against a future silent detour
27483        // that re-normalized the hint (an accidental `.to_lowercase()`
27484        // — every `:affinity` is already validated as a DNS-1123 label
27485        // upstream via [`validate_placement_affinity`], so any re-
27486        // normalization is redundant + a drift surface between the
27487        // validator and the accessor), a per-cluster alias rewrite the
27488        // operator authors on one consumer without the other, or an
27489        // accidental hint-family collapse (`low-latency` → `latency`
27490        // that dropped the qualifier prefix). Four values sweep the
27491        // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
27492        // canonical adaptive-compression-weight biases the future M4
27493        // placement engine reads.
27494        for hint in [
27495            "data-locality",
27496            "low-latency",
27497            "high-throughput",
27498            "cost-optimized",
27499        ] {
27500            let p = Placement {
27501                estrategia: PlacementStrategy::Replicated,
27502                clusters: vec!["rio".into()],
27503                affinity: Some(hint.into()),
27504                shard_key: None,
27505            };
27506            assert_eq!(
27507                p.affinity(),
27508                Some(hint),
27509                "Placement::affinity must return :placement :affinity \
27510                 verbatim (got {:?}, expected Some({hint:?}))",
27511                p.affinity(),
27512            );
27513            assert_eq!(
27514                p.affinity(),
27515                p.affinity.as_deref(),
27516                "Placement::affinity must byte-equal the .affinity \
27517                 field's `.as_deref()` projection",
27518            );
27519        }
27520    }
27521
27522    #[test]
27523    fn placement_affinity_none_when_field_is_none() {
27524        // The absent-`:affinity` arm of the per-`:placement`
27525        // M3-Adaptive-compression-hint accessor pin: when the typed
27526        // slot is absent — the canonical shape of an Aplicacao that
27527        // leaves the compression weighting up to the placement engine's
27528        // cluster-default arm — [`Placement::affinity`] must return
27529        // `None`. Pins against a future silent detour that projected
27530        // the absent slot to a `Some("")` empty-string default (the
27531        // canonical `Option<String>` → `String` collapse footgun the
27532        // sibling M2 [`crate::LimitsSpec::is_empty`] /
27533        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
27534        // already guard on the peer M2 typed-slot surfaces), a
27535        // `Some("None")` stringified-None round-trip, a `Some` arm
27536        // whose contents were derived from a sibling slot (an
27537        // accidental fallback to `estrategia.as_str()` that read the
27538        // strategy discriminator into the hint axis), or a
27539        // `Some("default")` implicit-default that would silently biases
27540        // the routing without the author having written one. Three
27541        // placements sweep the accept-set every `validate`-passing
27542        // `:affinity None` shape lands on — one per PlacementStrategy
27543        // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
27544        // with a shard-key), since `:affinity` is orthogonal to
27545        // `:estrategia` in the typed grammar.
27546        for (estrategia, shard_key) in [
27547            (PlacementStrategy::SingleNode, None),
27548            (PlacementStrategy::Replicated, None),
27549            (PlacementStrategy::Sharded, Some("tenantId".to_string())),
27550        ] {
27551            let p = Placement {
27552                estrategia,
27553                clusters: vec!["rio".into()],
27554                affinity: None,
27555                shard_key,
27556            };
27557            assert!(
27558                p.affinity().is_none(),
27559                "Placement::affinity must return None when the typed \
27560                 slot is absent under :estrategia {estrategia:?} (got {:?})",
27561                p.affinity(),
27562            );
27563            assert_eq!(
27564                p.affinity(),
27565                p.affinity.as_deref(),
27566                "Placement::affinity must byte-equal the .affinity \
27567                 field's `.as_deref()` projection in the absent arm",
27568            );
27569        }
27570    }
27571
27572    #[test]
27573    fn placement_affinity_borrows_from_affinity_storage() {
27574        // The borrow-not-copy pin: [`Placement::affinity`] must return
27575        // an `Option<&str>` whose `Some` arm borrows from the typed
27576        // slot's own [`String`] storage — same-address invariant with
27577        // `p.affinity.as_deref().unwrap()`. Pins against a future
27578        // silent detour that allocated a fresh `String`
27579        // (`self.affinity.clone().map(...)` in the body would type-
27580        // check but silently drop the borrow, and every downstream
27581        // consumer that assumed the returned slice outlives `&self`
27582        // would break on a stale-reference use-after-free — the
27583        // [`AplicacaoSpec::validate_placement`] per-hint value-shape
27584        // gate reads the accessor's `&str` return through the
27585        // [`validate_placement_affinity`] `&str` parameter and would
27586        // silently misbehave if this accessor produced a detached
27587        // copy). Peer of the sibling per-`:placement`
27588        // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
27589        // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
27590        // extends the discipline onto the sibling per-`:placement`
27591        // M3-Adaptive-compression-hint arm.
27592        let p = Placement {
27593            estrategia: PlacementStrategy::Replicated,
27594            clusters: vec!["rio".into()],
27595            affinity: Some("data-locality".into()),
27596            shard_key: None,
27597        };
27598        let hint = p.affinity().expect("Some arm");
27599        let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
27600        assert_eq!(
27601            hint.as_ptr(),
27602            storage_slice.as_ptr(),
27603            "Placement::affinity must borrow from the .affinity \
27604             String's backing storage — a fresh allocation here means \
27605             the accessor no longer names the substrate-primitive typed \
27606             dispatch and every downstream consumer would silently \
27607             carry a detached copy",
27608        );
27609        assert_eq!(
27610            hint.len(),
27611            storage_slice.len(),
27612            "Placement::affinity and .affinity.as_deref() must byte-\
27613             equal in length as well as in address",
27614        );
27615    }
27616
27617    #[test]
27618    fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
27619        // The canonical per-`:placement` distribution-strategy-scalar
27620        // pin: [`Placement::estrategia`] must return the `:placement
27621        // :estrategia` field verbatim as a [`PlacementStrategy`],
27622        // `Copy`-projected from the typed slot's own `PlacementStrategy`
27623        // storage across every variant in the closed accept-set
27624        // (`SingleNode` — Erlang/OTP distributed-app takeover;
27625        // `Replicated` — active-active across every named cluster;
27626        // `Sharded` — Akka-style hash-keyed entity distribution). Pins
27627        // against a future silent detour that re-derived the strategy
27628        // from a peer axis (an accidental fallback to
27629        // `if shard_key.is_some() { Sharded } else { Replicated }`
27630        // collapse that read the shard-key axis into the strategy
27631        // discriminator), a variant remap the operator authors on one
27632        // consumer without the other, or a stale-derive detour that
27633        // substituted [`PlacementStrategy::default`] when the field
27634        // held any explicit variant (which would silently collapse the
27635        // distinction between "author explicitly declared `:estrategia
27636        // Replicated`" and "author omitted the slot and inherited the
27637        // default" the future per-cluster override slot depends on).
27638        // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
27639        // pin on the `Copy`-return `u16` scalar axis — same "the
27640        // substrate-primitive accessor must byte-equal the raw field
27641        // access verbatim across every author-declared value" discipline
27642        // extended onto the per-`:placement` distribution-strategy
27643        // `Copy`-composite-enum scalar axis.
27644        for estrategia in [
27645            PlacementStrategy::SingleNode,
27646            PlacementStrategy::Replicated,
27647            PlacementStrategy::Sharded,
27648        ] {
27649            // Route the paired `:shard-key` fixture-builder through the
27650            // typed cross-slot invariant predicate
27651            // [`PlacementStrategy::requires_shard_key`] rather than the
27652            // [`gen_platform::IsVariant`]-derived [`PlacementStrategy::is_sharded`]
27653            // arm-identity predicate — same discipline the sibling
27654            // `placement_strategy_variants_round_trip` fixture builder now
27655            // reads through.
27656            let shard_key = estrategia
27657                .requires_shard_key()
27658                .then(|| "tenantId".to_string());
27659            let p = Placement {
27660                estrategia,
27661                clusters: vec!["rio".into()],
27662                affinity: None,
27663                shard_key,
27664            };
27665            assert_eq!(
27666                p.estrategia(),
27667                estrategia,
27668                "Placement::estrategia must return :placement :estrategia \
27669                 verbatim (got {:?}, expected {estrategia:?})",
27670                p.estrategia(),
27671            );
27672            assert_eq!(
27673                p.estrategia(),
27674                p.estrategia,
27675                "Placement::estrategia accessor and .estrategia field \
27676                 access must byte-equal — the accessor is the substrate-\
27677                 primitive typed dispatch every downstream distribution-\
27678                 strategy consumer must route through",
27679            );
27680        }
27681    }
27682
27683    #[test]
27684    fn validate_placement_reads_through_lifted_estrategia_accessor() {
27685        // Three-consumer coherence pin: the
27686        // [`AplicacaoSpec::validate_placement`]
27687        // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
27688        // `estrategia:` field (which reads through
27689        // [`Placement::estrategia`] to name the strategy the empty
27690        // `:clusters` list was declared against), the same method's
27691        // `Sharded ↔ non-Sharded` `match` partition dispatch (which
27692        // reads through [`Placement::estrategia`] to fan across the
27693        // shape-gate cascades), and the non-`Sharded`-arm
27694        // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
27695        // `estrategia:` field (which reads through
27696        // [`Placement::estrategia`] to name the strategy the declared-
27697        // but-inert `:shard-key` was authored under) must all key off
27698        // the lifted accessor, so any future rebrand on the typed
27699        // slot's reader shape lands at exactly one place. Pins the
27700        // three-site coherence by exercising each error surface end-
27701        // to-end and asserting the surfaced `estrategia:` field byte-
27702        // equals the accessor's return. Peer of the sibling per-
27703        // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
27704        // pin on the M3 mesh-slot `Copy`-return scalar axis.
27705
27706        // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
27707        // whose `estrategia:` field must byte-equal the accessor's return
27708        // for every variant in the closed accept-set.
27709        for estrategia in [
27710            PlacementStrategy::SingleNode,
27711            PlacementStrategy::Replicated,
27712            PlacementStrategy::Sharded,
27713        ] {
27714            let mut spec = three_member_spec();
27715            spec.placement.estrategia = estrategia;
27716            spec.placement.clusters = Vec::new();
27717            // Route the paired `:shard-key` spec-mutator through the typed
27718            // cross-slot invariant predicate
27719            // [`PlacementStrategy::requires_shard_key`] rather than the
27720            // [`gen_platform::IsVariant`]-derived
27721            // [`PlacementStrategy::is_sharded`] arm-identity predicate —
27722            // same discipline the sibling
27723            // `placement_strategy_variants_round_trip` and
27724            // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
27725            // fixture builders now read through.
27726            spec.placement.shard_key = estrategia
27727                .requires_shard_key()
27728                .then(|| "tenantId".to_string());
27729            let err = spec.validate().unwrap_err();
27730            match err {
27731                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
27732                    assert_eq!(
27733                        e,
27734                        spec.placement.estrategia(),
27735                        "PlacementWithoutClusters.estrategia must byte-equal \
27736                         Placement::estrategia() — the error carrier reads \
27737                         through the lifted accessor",
27738                    );
27739                }
27740                other => panic!(
27741                    "expected PlacementWithoutClusters, got {other:?} for \
27742                     estrategia={estrategia:?}"
27743                ),
27744            }
27745        }
27746
27747        // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
27748        // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
27749        // must byte-equal the accessor's return for both non-`Sharded`
27750        // strategies.
27751        for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
27752            let mut spec = three_member_spec();
27753            spec.placement.estrategia = estrategia;
27754            spec.placement.shard_key = Some("tenantId".into());
27755            let err = spec.validate().unwrap_err();
27756            match err {
27757                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
27758                    assert_eq!(
27759                        e,
27760                        spec.placement.estrategia(),
27761                        "ShardKeyOnNonSharded.estrategia must byte-equal \
27762                         Placement::estrategia() — the non-Sharded-arm \
27763                         refusal reads through the lifted accessor",
27764                    );
27765                }
27766                other => panic!(
27767                    "expected ShardKeyOnNonSharded, got {other:?} for \
27768                     estrategia={estrategia:?}"
27769                ),
27770            }
27771        }
27772    }
27773
27774    // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
27775    //
27776    // The [`Placement::clusters`] accessor lift is the second slice-return
27777    // (`&[T]`) accessor on any typed slot — sibling to the seed M2
27778    // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
27779    // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
27780    // below cover (1) the accessor's byte-equal projection against the raw
27781    // field access across the empty / singleton / cohort fixtures the
27782    // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
27783    // and the per-cluster validate loop fan between, and (2) the two-
27784    // consumer coherence of the paired pre-flight refusal probe and the
27785    // per-cluster validate loop routing through the accessor on both arms.
27786
27787    #[test]
27788    fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
27789        // The canonical per-`:placement` cluster-pool-scalar-shape pin:
27790        // [`Placement::clusters`] must return the `:placement :clusters`
27791        // typed `Vec<String>` verbatim as a `&[String]` slice-view over
27792        // the same backing buffer the raw `self.clusters.as_slice()`
27793        // field access borrows from, byte-equal across every
27794        // representative fixture in the accept-set — the empty slice
27795        // (the pre-validation sentinel every
27796        // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
27797        // the singleton slice (the minimal `SingleNode`-shape cohort),
27798        // and multi-entry cohorts (the peer `Replicated` / `Sharded`
27799        // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
27800        //
27801        // Pins against a future silent detour that returned
27802        // `&Vec<String>` (which would type-check but leak the storage-
27803        // side `Vec`'s grow/push/reserve surface no consumer of the
27804        // typed view reaches for), a fresh-allocated `Vec<String>` copy
27805        // (which would type-check via a coercion but silently break
27806        // every downstream caller that relied on the slice sharing the
27807        // backing buffer's identity), or an out-of-order or length-
27808        // drifted projection (which would silently split the paired
27809        // pre-flight `.is_empty()` refusal probe's input from the per-
27810        // cluster validate loop's traversal input).
27811        //
27812        // Peer of the sibling M2
27813        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
27814        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
27815        // `:supervisor` static-child-list axis, extended onto the M3
27816        // per-`:placement` distribution-target-list `Vec`-carry axis.
27817        let fixtures: Vec<Vec<String>> = vec![
27818            Vec::new(),
27819            vec!["rio".into()],
27820            vec!["rio".into(), "mar".into()],
27821            vec!["rio".into(), "mar".into(), "plo".into()],
27822        ];
27823        for clusters in fixtures {
27824            let p = Placement {
27825                clusters: clusters.clone(),
27826                ..Placement::default()
27827            };
27828            assert_eq!(
27829                p.clusters(),
27830                clusters.as_slice(),
27831                "Placement::clusters must return :placement :clusters \
27832                 verbatim (got {:?}, expected {:?})",
27833                p.clusters(),
27834                clusters.as_slice(),
27835            );
27836            assert_eq!(
27837                p.clusters(),
27838                p.clusters.as_slice(),
27839                "Placement::clusters accessor and .clusters.as_slice() \
27840                 field access must byte-equal — the accessor is the \
27841                 substrate-primitive typed dispatch every downstream \
27842                 cluster-pool consumer must route through",
27843            );
27844            assert_eq!(
27845                p.clusters().len(),
27846                p.clusters.len(),
27847                "Placement::clusters().len() must byte-equal \
27848                 self.clusters.len() — a length-drift would silently \
27849                 split the paired pre-flight `.is_empty()` refusal \
27850                 probe input from the per-cluster validate loop's \
27851                 traversal input",
27852            );
27853        }
27854    }
27855
27856    #[test]
27857    fn validate_placement_reads_through_lifted_clusters_accessor() {
27858        // Two-consumer coherence pin: the
27859        // [`AplicacaoSpec::validate_placement`] pre-flight
27860        // `self.placement.clusters().is_empty()` refusal probe (which
27861        // must trip [`AplicacaoError::PlacementWithoutClusters`] when
27862        // the accessor projects the empty slice) and the per-cluster
27863        // validate loop's `for c in self.placement.clusters()`
27864        // traversal (which must reach every entry in the same order
27865        // the accessor projects, so both the per-entry value-shape
27866        // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
27867        // and the duplicate-detection HashSet insert that trips
27868        // [`AplicacaoError::PlacementClusterDuplicate`] key off the
27869        // accessor's projection) must both key off the lifted
27870        // accessor, so any future rebrand on the typed slot's reader
27871        // shape lands at exactly one place. Pins the two-site
27872        // coherence by exercising each production consumer end-to-end:
27873        // (1) the `PlacementWithoutClusters` refusal under the empty
27874        // slice, (2) the `PlacementClusterInvalid` refusal fires on
27875        // the second entry of a two-cluster cohort whose head is
27876        // valid but tail is not (which requires the loop to reach the
27877        // second entry through the accessor), and (3) the
27878        // `PlacementClusterDuplicate` refusal fires on the second
27879        // entry of a two-cluster cohort that shares a name (which
27880        // requires the loop to reach both entries — a first-entry-only
27881        // projection would silently pass since the dedup HashSet has
27882        // room for the first insert).
27883        //
27884        // Peer of the sibling M2
27885        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
27886        // (bc92bce) coherence pin on the per-`:supervisor` static-
27887        // child-list axis, extended onto the M3 per-`:placement`
27888        // distribution-target-list `Vec`-carry axis.
27889
27890        // (1) Pre-flight `.is_empty()` probe: the empty slice must
27891        // trip `PlacementWithoutClusters`.
27892        let mut spec = three_member_spec();
27893        spec.placement.clusters = Vec::new();
27894        match spec.validate().unwrap_err() {
27895            AplicacaoError::PlacementWithoutClusters { .. } => {}
27896            other => panic!("expected PlacementWithoutClusters, got {other:?}"),
27897        }
27898        assert!(
27899            spec.placement.clusters().is_empty(),
27900            "the pre-flight refusal input must be the empty slice per \
27901             the accessor's projection",
27902        );
27903
27904        // (2) Per-cluster validate loop: a two-cluster cohort with an
27905        // invalid tail entry must trip `PlacementClusterInvalid` on
27906        // the tail — the loop must reach the second entry through
27907        // the accessor.
27908        let mut spec = three_member_spec();
27909        spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
27910        match spec.validate().unwrap_err() {
27911            AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
27912                assert_eq!(
27913                    cluster, "BAD_CLUSTER",
27914                    "PlacementClusterInvalid.cluster must carry the \
27915                     tail entry the loop reached through the accessor",
27916                );
27917            }
27918            other => panic!("expected PlacementClusterInvalid, got {other:?}"),
27919        }
27920        assert_eq!(
27921            spec.placement.clusters().len(),
27922            2,
27923            "the per-cluster validate loop's traversal input must be \
27924             a two-element slice per the accessor's projection",
27925        );
27926
27927        // (3) Per-cluster validate loop: a two-cluster cohort that
27928        // shares a name must trip `PlacementClusterDuplicate` on the
27929        // second entry — the loop must reach both entries through the
27930        // accessor for the dedup HashSet's second insert to collide.
27931        let mut spec = three_member_spec();
27932        spec.placement.clusters = vec!["rio".into(), "rio".into()];
27933        match spec.validate().unwrap_err() {
27934            AplicacaoError::PlacementClusterDuplicate { cluster } => {
27935                assert_eq!(
27936                    cluster, "rio",
27937                    "PlacementClusterDuplicate.cluster must carry the \
27938                     shared cluster name verbatim",
27939                );
27940            }
27941            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
27942        }
27943        assert_eq!(
27944            spec.placement.clusters().len(),
27945            2,
27946            "the per-cluster validate loop's traversal input must be \
27947             a two-element slice per the accessor's projection",
27948        );
27949    }
27950
27951    #[test]
27952    fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
27953        // The canonical per-`:membros` member-list-slice-shape pin:
27954        // [`AplicacaoSpec::membros`] must return the `:membros` typed
27955        // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
27956        // same backing buffer the raw `self.membros.as_slice()` field
27957        // access borrows from, byte-equal across every representative
27958        // fixture in the accept-set — the empty slice (the pre-
27959        // validation sentinel every [`AplicacaoError::NoMembros`]
27960        // refusal keys off), the singleton slice (the minimal one-
27961        // Servico Aplicacao shape), and multi-entry cohorts (the peer
27962        // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
27963        // load-bearing identity of the application graph).
27964        //
27965        // Pins against a future silent detour that returned
27966        // `&Vec<Membro>` (which would type-check but leak the storage-
27967        // side `Vec`'s grow/push/reserve surface no consumer of the
27968        // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
27969        // (which would type-check via a coercion but silently break
27970        // every downstream caller that relied on the slice sharing the
27971        // backing buffer's identity), or an out-of-order or length-
27972        // drifted projection (which would silently split the paired
27973        // `HashSet<&str>` name-set seed's collect input from the
27974        // pre-flight `.is_empty()` refusal probe's input from the per-
27975        // member validate loop's traversal input from the
27976        // programs.yaml emitter's per-entry fan-out loop's input from
27977        // the `feira app graph` per-member print traversal's input).
27978        //
27979        // Peer of the sibling M2
27980        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
27981        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
27982        // `:supervisor` static-child-list axis and the sibling M3
27983        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
27984        // (a6e18d7) `&[String]` byte-equal pin on the per-
27985        // `:placement` distribution-target-list axis — extends the
27986        // slice-return-accessor byte-equal-projection discipline onto
27987        // the outermost M3 mesh-slot type's per-Aplicacao member-list
27988        // `Vec`-carry axis.
27989        let fixtures: Vec<Vec<Membro>> = vec![
27990            Vec::new(),
27991            vec![membro("catalog", "^0.1")],
27992            vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
27993            vec![
27994                membro("catalog", "^0.1"),
27995                membro("cart", "^0.1"),
27996                membro("payment", "^0.2"),
27997            ],
27998        ];
27999        for membros in fixtures {
28000            let s = AplicacaoSpec {
28001                membros: membros.clone(),
28002                contratos: Vec::new(),
28003                politicas: MeshPolicy::default(),
28004                placement: Placement::default(),
28005                entrada: None,
28006            };
28007            assert_eq!(
28008                s.membros(),
28009                membros.as_slice(),
28010                "AplicacaoSpec::membros must return :membros verbatim \
28011                 (got {:?}, expected {:?})",
28012                s.membros(),
28013                membros.as_slice(),
28014            );
28015            assert_eq!(
28016                s.membros(),
28017                s.membros.as_slice(),
28018                "AplicacaoSpec::membros accessor and .membros.as_slice() \
28019                 field access must byte-equal — the accessor is the \
28020                 substrate-primitive typed dispatch every downstream \
28021                 member-list consumer must route through",
28022            );
28023            assert_eq!(
28024                s.membros().len(),
28025                s.membros.len(),
28026                "AplicacaoSpec::membros().len() must byte-equal \
28027                 self.membros.len() — a length-drift would silently \
28028                 split the paired `HashSet<&str>` name-set seed's \
28029                 collect input from the pre-flight `.is_empty()` \
28030                 refusal probe input from the per-member validate \
28031                 loop's traversal input",
28032            );
28033        }
28034    }
28035
28036    #[test]
28037    fn validate_reads_through_lifted_membros_accessor() {
28038        // Three-consumer coherence pin: the
28039        // [`AplicacaoSpec::validate_membros`] pre-flight
28040        // `self.membros().is_empty()` refusal probe (which must trip
28041        // [`AplicacaoError::NoMembros`] when the accessor projects the
28042        // empty slice), the same method's per-member validate loop's
28043        // `for m in self.membros()` traversal (which must reach every
28044        // entry in the same order the accessor projects, so both the
28045        // per-entry empty-`:caixa` gate that trips
28046        // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
28047        // detection `insert_first_seen` that trips
28048        // [`AplicacaoError::MembroDuplicate`] key off the accessor's
28049        // projection), and the peer [`AplicacaoSpec::validate`]'s
28050        // `HashSet<&str>` name-set seed's
28051        // `self.membros().iter().map(Membro::nome).collect()` collect
28052        // input (which every `:contratos` `:de` / `:para` membership
28053        // lookup rejects an unknown name against) must all three key
28054        // off the lifted accessor, so any future rebrand on the typed
28055        // slot's reader shape lands at exactly one place. Pins the
28056        // three-site coherence by exercising each production consumer
28057        // end-to-end: (1) the `NoMembros` refusal under the empty
28058        // slice, (2) the `MembroCaixaEmpty` refusal fires on the
28059        // second entry of a two-member cohort whose head is valid but
28060        // tail has an empty `:caixa` (which requires the loop to
28061        // reach the second entry through the accessor), and (3) the
28062        // `MembroDuplicate` refusal fires on the second entry of a
28063        // two-member cohort that shares a `:caixa` name (which
28064        // requires the loop to reach both entries through the
28065        // accessor for the dedup HashSet's second insert to collide).
28066        //
28067        // Peer of the sibling M2
28068        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
28069        // (bc92bce) coherence pin on the per-`:supervisor` static-
28070        // child-list axis and the sibling M3
28071        // `validate_placement_reads_through_lifted_clusters_accessor`
28072        // (a6e18d7) coherence pin on the per-`:placement` distribution-
28073        // target-list axis — extends the slice-return-accessor
28074        // multi-consumer coherence discipline onto the outermost M3
28075        // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
28076
28077        // (1) Pre-flight `.is_empty()` probe: the empty slice must
28078        // trip `NoMembros`.
28079        let mut spec = three_member_spec();
28080        spec.membros = Vec::new();
28081        assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
28082        assert!(
28083            spec.membros().is_empty(),
28084            "the pre-flight refusal input must be the empty slice per \
28085             the accessor's projection",
28086        );
28087
28088        // (2) Per-member validate loop: a two-member cohort with an
28089        // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
28090        // the tail — the loop must reach the second entry through
28091        // the accessor.
28092        let mut spec = three_member_spec();
28093        spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
28094        assert_eq!(
28095            spec.validate().unwrap_err(),
28096            AplicacaoError::MembroCaixaEmpty,
28097        );
28098        assert_eq!(
28099            spec.membros().len(),
28100            2,
28101            "the per-member validate loop's traversal input must be \
28102             a two-element slice per the accessor's projection",
28103        );
28104
28105        // (3) Per-member validate loop: a two-member cohort that
28106        // shares a `:caixa` name must trip `MembroDuplicate` on the
28107        // second entry — the loop must reach both entries through the
28108        // accessor for the dedup HashSet's second insert to collide.
28109        let mut spec = three_member_spec();
28110        spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
28111        match spec.validate().unwrap_err() {
28112            AplicacaoError::MembroDuplicate { caixa } => {
28113                assert_eq!(
28114                    caixa, "catalog",
28115                    "MembroDuplicate.caixa must carry the shared \
28116                     member name verbatim",
28117                );
28118            }
28119            other => panic!("expected MembroDuplicate, got {other:?}"),
28120        }
28121        assert_eq!(
28122            spec.membros().len(),
28123            2,
28124            "the per-member validate loop's traversal input must be \
28125             a two-element slice per the accessor's projection",
28126        );
28127    }
28128
28129    #[test]
28130    fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
28131        // The canonical per-`:contratos` contract-list-slice-shape pin:
28132        // [`AplicacaoSpec::contratos`] must return the `:contratos`
28133        // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
28134        // slice-view over the same backing buffer the raw
28135        // `self.contratos.as_slice()` field access borrows from, byte-
28136        // equal across every representative fixture in the accept-set —
28137        // the empty slice (the pre-validation "internal-only mesh" shape
28138        // an Aplicacao whose members exchange no typed edges renders
28139        // through), the singleton slice (the minimal one-edge Aplicacao
28140        // shape), and multi-entry cohorts (the peer multi-edge shapes
28141        // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
28142        // of the application graph).
28143        //
28144        // Pins against a future silent detour that returned
28145        // `&Vec<WitContract>` (which would type-check but leak the
28146        // storage-side `Vec`'s grow/push/reserve surface no consumer of
28147        // the typed view reaches for), a fresh-allocated
28148        // `Vec<WitContract>` copy (which would type-check via a coercion
28149        // but silently break every downstream caller that relied on the
28150        // slice sharing the backing buffer's identity), or an out-of-
28151        // order or length-drifted projection (which would silently split
28152        // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
28153        // seed's traversal input from the `detect_sync_cycles` per-edge
28154        // adjacency-list seed's traversal input from the
28155        // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
28156        // BTreeMap grouping loop's traversal input from the
28157        // `feira app graph` per-contract print traversal's input).
28158        //
28159        // Peer of the immediately-adjacent sibling M3
28160        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
28161        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
28162        // node-list axis, the sibling M3
28163        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
28164        // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
28165        // distribution-target-list axis, and the sibling M2
28166        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
28167        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
28168        // `:supervisor` static-child-list axis — extends the slice-
28169        // return-accessor byte-equal-projection discipline onto the
28170        // outermost M3 mesh-slot type's per-Aplicacao contract-list
28171        // `Vec`-carry axis, closing the last unlifted per-
28172        // `AplicacaoSpec` `Vec`-carry axis.
28173        let fixtures: Vec<Vec<WitContract>> = vec![
28174            Vec::new(),
28175            vec![contract_http("cart", "catalog", "/products/:id")],
28176            vec![
28177                contract_http("cart", "catalog", "/products/:id"),
28178                contract_http("cart", "payment", "/charge"),
28179            ],
28180            vec![
28181                contract_http("cart", "catalog", "/products/:id"),
28182                contract_http("cart", "payment", "/charge"),
28183                contract_http("payment", "catalog", "/audit"),
28184            ],
28185        ];
28186        for contratos in fixtures {
28187            let s = AplicacaoSpec {
28188                membros: vec![
28189                    membro("catalog", "^0.1"),
28190                    membro("cart", "^0.1"),
28191                    membro("payment", "^0.2"),
28192                ],
28193                contratos: contratos.clone(),
28194                politicas: MeshPolicy::default(),
28195                placement: Placement::default(),
28196                entrada: None,
28197            };
28198            assert_eq!(
28199                s.contratos(),
28200                contratos.as_slice(),
28201                "AplicacaoSpec::contratos must return :contratos verbatim \
28202                 (got {:?}, expected {:?})",
28203                s.contratos(),
28204                contratos.as_slice(),
28205            );
28206            assert_eq!(
28207                s.contratos(),
28208                s.contratos.as_slice(),
28209                "AplicacaoSpec::contratos accessor and \
28210                 .contratos.as_slice() field access must byte-equal — \
28211                 the accessor is the substrate-primitive typed dispatch \
28212                 every downstream contract-list consumer must route \
28213                 through",
28214            );
28215            assert_eq!(
28216                s.contratos().len(),
28217                s.contratos.len(),
28218                "AplicacaoSpec::contratos().len() must byte-equal \
28219                 self.contratos.len() — a length-drift would silently \
28220                 split the paired per-edge validate-loop's traversal \
28221                 input from the sync-cycle adjacency-list seed's \
28222                 traversal input from the cilium_network_policies \
28223                 per-`(:de, :para)` BTreeMap grouping loop's traversal \
28224                 input from the `feira app graph` per-contract print \
28225                 traversal's input",
28226            );
28227        }
28228    }
28229
28230    #[test]
28231    fn validate_reads_through_lifted_contratos_accessor() {
28232        // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
28233        // per-`:contratos` validate-loop's `for c in self.contratos()`
28234        // traversal (which must reach every entry in the same order the
28235        // accessor projects, so both the per-entry
28236        // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
28237        // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
28238        // dedup `HashSet` insert key off the accessor's projection),
28239        // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
28240        // `for c in self.contratos()` adjacency-list seed (which drives
28241        // the sync-subgraph deadlock-detection gate via
28242        // [`AplicacaoError::SyncCycle`]), and the peer
28243        // [`caixa_mesh::cilium_network_policies`]'s
28244        // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
28245        // grouping loop (which drives the per-CNP fan-out) must all
28246        // three key off the lifted accessor, so any future rebrand on
28247        // the typed slot's reader shape lands at exactly one place. Pins
28248        // the three-site coherence by exercising the two caixa-core
28249        // production consumers end-to-end: (1) the empty-`:contratos`
28250        // slice must validate without a per-edge diagnostic (the
28251        // per-edge loop is a no-op under the empty projection), (2) the
28252        // `ContratoMemberMissing` refusal fires on the second entry of a
28253        // two-edge cohort whose head references a valid member but tail
28254        // references a phantom name (which requires the loop to reach
28255        // the second entry through the accessor), and (3) the
28256        // `SyncCycle` refusal fires on a self-referential two-edge
28257        // cohort through the sync-cycle detector's peer projection
28258        // (which requires the detector to iterate the accessor's
28259        // projection to add the back-edge to its adjacency list).
28260        //
28261        // Peer of the sibling M3
28262        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
28263        // three-consumer coherence pin on the per-`:membros` node-list
28264        // axis and the sibling M3
28265        // `validate_placement_reads_through_lifted_clusters_accessor`
28266        // (a6e18d7) coherence pin on the per-`:placement` distribution-
28267        // target-list axis — extends the slice-return-accessor multi-
28268        // consumer coherence discipline onto the outermost M3 mesh-slot
28269        // type's per-Aplicacao contract-list `Vec`-carry axis.
28270
28271        // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
28272        // and no per-edge diagnostic surfaces. Validate succeeds on
28273        // the well-formed `:membros` head.
28274        let mut spec = three_member_spec();
28275        spec.contratos = Vec::new();
28276        assert!(
28277            spec.validate().is_ok(),
28278            "empty :contratos must validate — the per-edge loop is a \
28279             no-op under the accessor's empty projection",
28280        );
28281        assert!(
28282            spec.contratos().is_empty(),
28283            "the per-edge validate loop's traversal input must be the \
28284             empty slice per the accessor's projection",
28285        );
28286
28287        // (2) Per-edge validate loop: a two-edge cohort whose tail
28288        // references a phantom `:para` member must trip
28289        // `ContratoMemberMissing` on the tail — the loop must reach
28290        // the second entry through the accessor for the membership
28291        // lookup to fail on the phantom name.
28292        let mut spec = three_member_spec();
28293        spec.contratos = vec![
28294            contract_http("cart", "catalog", "/products/:id"),
28295            contract_http("cart", "phantom", "/x"),
28296        ];
28297        let err = spec.validate().unwrap_err();
28298        assert!(
28299            matches!(
28300                err,
28301                AplicacaoError::ContratoMemberMissing { ref caixa }
28302                    if caixa == "phantom"
28303            ),
28304            "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
28305        );
28306        assert_eq!(
28307            spec.contratos().len(),
28308            2,
28309            "the per-edge validate loop's traversal input must be \
28310             a two-element slice per the accessor's projection",
28311        );
28312
28313        // (3) Sync-cycle detector: a two-edge synchronous cohort
28314        // whose second edge closes the sync-subgraph back onto the
28315        // first must trip [`AplicacaoError::ContratoCycle`] — the
28316        // detector must iterate the accessor's projection to add
28317        // both edges to its adjacency list, so a length-drift on
28318        // the accessor's projection would silently disagree with
28319        // the sync-cycle detector on which edge closes the loop.
28320        // Peer projection to the `validate` per-edge loop above:
28321        // the sync-cycle detector routes through the same lifted
28322        // accessor, so a rebrand of the reader shape lands at one
28323        // place. Uses a two-edge cohort (cart → catalog → cart)
28324        // because the per-edge `ContratoSelfLoop` gate fires before
28325        // the sync-cycle detector on a single self-referential edge
28326        // (`cart → cart`) — the cycle-detector's input must be a
28327        // multi-edge cohort for its per-edge traversal input to be
28328        // observably wider than the per-edge validate loop's input.
28329        let mut spec = three_member_spec();
28330        spec.contratos = vec![
28331            contract_http("cart", "catalog", "/products/:id"),
28332            contract_http("catalog", "cart", "/callback"),
28333        ];
28334        let err = spec.validate().unwrap_err();
28335        assert!(
28336            matches!(err, AplicacaoError::ContratoCycle { .. }),
28337            "expected ContratoCycle from the sync-cycle detector on a \
28338             two-edge back-edge cohort, got {err:?}",
28339        );
28340        assert_eq!(
28341            spec.contratos().len(),
28342            2,
28343            "the sync-cycle detector's traversal input must be a \
28344             two-element slice per the accessor's projection",
28345        );
28346    }
28347
28348    #[test]
28349    fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
28350        // The canonical per-`:politicas` outer-composite-reference-shape
28351        // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
28352        // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
28353        // the same backing storage the raw `&self.politicas` field
28354        // access borrows from, byte-equal across every representative
28355        // fixture in the accept-set — the default `MeshPolicy` (the
28356        // author-empty "no policy on any axis" shape whose
28357        // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
28358        // shapes carrying one axis at a time
28359        // (`{mtls_required, timeout, retries, circuit_breaker,
28360        // rate_limit}` — the minimal five-axis fan-out over the
28361        // per-axis lifted accessor family every downstream mesh-artifact
28362        // emitter dispatches on), and the multi-axis composite (the
28363        // canonical `three_member_spec` fixture's `{timeout, retries,
28364        // mtls_required}` triple — the load-bearing shape every
28365        // Aplicacao-scoped fixture in this suite constructs).
28366        //
28367        // Pins against a future silent detour that returned a fresh-
28368        // cloned `MeshPolicy` copy (which would type-check via a `Clone`
28369        // impl but silently break every downstream caller that relied
28370        // on the reference sharing the composite's backing identity), a
28371        // reference to an operator-resolved overlay (the future
28372        // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
28373        // acknowledges — its resolution must land at exactly this
28374        // accessor body, not silently divert the raw slot away from a
28375        // second consumer), or an axis-shuffled projection (a future
28376        // detour that swapped `timeout` and `retries` through the
28377        // accessor would silently split the paired `validate_politicas`
28378        // per-axis bracket-dispatch's traversal input from the peer
28379        // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
28380        // emitter's fan-out input from the peer
28381        // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
28382        // overlay emitter's fan-out input).
28383        //
28384        // Peer of the sibling M3
28385        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
28386        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
28387        // node-list `Vec`-carry axis and the sibling M3
28388        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
28389        // (0dcc926) `&[WitContract]` byte-equal pin on the per-
28390        // `:contratos` edge-list `Vec`-carry axis — extends the outer-
28391        // accessor byte-equal-projection discipline onto the outermost
28392        // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
28393        // reference axis, the first `&Composite`-return accessor on the
28394        // outer [`AplicacaoSpec`] type.
28395        let fixtures: Vec<MeshPolicy> = vec![
28396            MeshPolicy::default(),
28397            MeshPolicy {
28398                mtls_required: Some(true),
28399                ..MeshPolicy::default()
28400            },
28401            MeshPolicy {
28402                mtls_required: Some(false),
28403                ..MeshPolicy::default()
28404            },
28405            MeshPolicy {
28406                timeout: Some(Duration::from_secs(30)),
28407                ..MeshPolicy::default()
28408            },
28409            MeshPolicy {
28410                retries: Some(3),
28411                ..MeshPolicy::default()
28412            },
28413            MeshPolicy {
28414                circuit_breaker: Some(CircuitBreaker {
28415                    max_failures: 5,
28416                    window: Duration::from_secs(30),
28417                }),
28418                ..MeshPolicy::default()
28419            },
28420            MeshPolicy {
28421                rate_limit: Some(RateLimit {
28422                    rate: 100,
28423                    window: Duration::from_secs(1),
28424                }),
28425                ..MeshPolicy::default()
28426            },
28427            MeshPolicy {
28428                timeout: Some(Duration::from_secs(30)),
28429                retries: Some(3),
28430                mtls_required: Some(true),
28431                ..MeshPolicy::default()
28432            },
28433        ];
28434        for politicas in fixtures {
28435            let s = AplicacaoSpec {
28436                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
28437                contratos: Vec::new(),
28438                politicas: politicas.clone(),
28439                placement: Placement::default(),
28440                entrada: None,
28441            };
28442            assert_eq!(
28443                *s.politicas(),
28444                politicas,
28445                "AplicacaoSpec::politicas must return :politicas verbatim \
28446                 (got {:?}, expected {:?})",
28447                s.politicas(),
28448                politicas,
28449            );
28450            assert!(
28451                std::ptr::eq(s.politicas(), &s.politicas),
28452                "AplicacaoSpec::politicas accessor and &self.politicas \
28453                 field access must borrow the same backing storage — \
28454                 the accessor is the substrate-primitive typed dispatch \
28455                 every downstream mesh-policy composite consumer must \
28456                 route through, and a reference-identity split would \
28457                 silently break every consumer that relied on the \
28458                 borrow sharing the composite's storage",
28459            );
28460            assert_eq!(
28461                s.politicas().is_empty(),
28462                s.politicas.is_empty(),
28463                "AplicacaoSpec::politicas().is_empty() must byte-equal \
28464                 self.politicas.is_empty() — an emptiness-drift would \
28465                 silently split the paired `validate_politicas` \
28466                 per-axis bracket-dispatch's seed from the peer \
28467                 caixa-mesh CNP mTLS-overlay emitter's key from the \
28468                 peer caixa-mesh HTTPRoute timeout+retry overlay \
28469                 emitter's key",
28470            );
28471        }
28472    }
28473
28474    #[test]
28475    fn validate_politicas_reads_through_lifted_politicas_accessor() {
28476        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
28477        // per-axis bracket-dispatch seed (`let p = self.politicas();`,
28478        // followed by the per-axis fan-out `p.timeout()` /
28479        // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
28480        // the lifted axis-level accessor family) must key off the
28481        // lifted outer accessor, so any future rebrand on the typed
28482        // slot's outer-composite reader shape lands at exactly one
28483        // place. Pins the multi-axis coherence by exercising each
28484        // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
28485        // a `Some(Duration::ZERO)` timeout under the outer accessor's
28486        // reference projection, (2) `PolicyRetriesZero` fires on a
28487        // `Some(0)` retries under the same projection, and (3) an
28488        // empty [`MeshPolicy::default`] passes `validate_politicas` —
28489        // the outer accessor's reference-projection reaches every
28490        // per-axis branch without silently short-circuiting any.
28491        //
28492        // Peer of the sibling M3
28493        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
28494        // three-consumer coherence pin on the per-`:membros` node-list
28495        // axis and the sibling M3
28496        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
28497        // three-consumer coherence pin on the per-`:contratos`
28498        // edge-list axis — extends the multi-consumer coherence
28499        // discipline onto the outermost M3 mesh-slot type's per-
28500        // Aplicacao mesh-policy composite-reference axis, the first
28501        // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
28502        // type.
28503
28504        // (1) `PolicyTimeoutZero` refusal under the outer accessor's
28505        // reference projection: a `Some(Duration::ZERO)` timeout must
28506        // trip the zero-floor gate. The bracket-dispatch's first arm
28507        // reads `p.timeout()` on the reference returned by the outer
28508        // accessor.
28509        let mut spec = three_member_spec();
28510        spec.politicas.timeout = Some(Duration::ZERO);
28511        spec.politicas.retries = None;
28512        spec.politicas.circuit_breaker = None;
28513        spec.politicas.rate_limit = None;
28514        assert_eq!(
28515            spec.validate().unwrap_err(),
28516            AplicacaoError::PolicyTimeoutZero,
28517        );
28518        assert!(
28519            std::ptr::eq(spec.politicas(), &spec.politicas),
28520            "the `validate_politicas` per-axis bracket-dispatch's \
28521             traversal input must be the same backing composite the \
28522             accessor's reference projection borrows from",
28523        );
28524
28525        // (2) `PolicyRetriesZero` refusal under the outer accessor's
28526        // reference projection: a `Some(0)` retries must trip the
28527        // zero-floor gate. The bracket-dispatch's second arm reads
28528        // `p.retries()` on the reference returned by the outer accessor.
28529        let mut spec = three_member_spec();
28530        spec.politicas.timeout = None;
28531        spec.politicas.retries = Some(0);
28532        spec.politicas.circuit_breaker = None;
28533        spec.politicas.rate_limit = None;
28534        assert_eq!(
28535            spec.validate().unwrap_err(),
28536            AplicacaoError::PolicyRetriesZero,
28537        );
28538
28539        // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
28540        // — every per-axis arm short-circuits on `None`, so the outer
28541        // accessor's reference projection reaches the fall-through
28542        // `Ok(())` without any per-axis refusal firing.
28543        let mut spec = three_member_spec();
28544        spec.politicas = MeshPolicy::default();
28545        assert!(
28546            spec.validate().is_ok(),
28547            "an empty `MeshPolicy` must pass `validate_politicas` — \
28548             every per-axis arm short-circuits on `None` under the \
28549             outer accessor's reference projection",
28550        );
28551        assert!(
28552            spec.politicas().is_empty(),
28553            "the outer accessor's reference projection must be the \
28554             empty composite per the `MeshPolicy::default()` fixture",
28555        );
28556    }
28557
28558    #[test]
28559    #[allow(clippy::too_many_lines)]
28560    fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
28561        // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
28562        // per-axis bracket-dispatch's `:timeout` and `:retries` arms
28563        // must both key off the lifted axis-level accessors
28564        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
28565        // the peer `:circuit-breaker` / `:rate-limit` arms already
28566        // routing through [`MeshPolicy::circuit_breaker`] /
28567        // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
28568        // per axis on the substrate primitive" shape at the fan-out
28569        // (four axes, four accessors, no raw-field-access site
28570        // anywhere on the bracket-dispatch). Pins the per-axis
28571        // coherence at the accept-set boundaries the bracket carves:
28572        //   1. accessor byte-equal to raw field on every representative
28573        //      accept-set value (`None`, sub-cap, at-cap, past-cap
28574        //      sentinel) — a future accessor drift that no longer
28575        //      shipped the raw slot verbatim would surface here,
28576        //   2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
28577        //      routed through the accessor's projection, proving the
28578        //      first arm reads through the accessor rather than a
28579        //      silent-detour peer-axis field access,
28580        //   3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
28581        //      through the accessor's projection, proving the second
28582        //      arm reads through the accessor,
28583        //   4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
28584        //      passes validate under the accessor projection (paired
28585        //      with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
28586        //      sibling axis), pinning the upper-boundary accept-arm
28587        //      also routes through the accessor.
28588        //
28589        // Peer of the sibling M3
28590        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
28591        // outer-composite-reference coherence pin (which asserts the
28592        // `let p = self.politicas()` seed); extends the discipline onto
28593        // the per-axis fan-out layer that consumes the seed's
28594        // reference. Same shape as
28595        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
28596        // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
28597        // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
28598        // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
28599
28600        // (1) Accessor byte-equal to raw field on the `:timeout` axis
28601        // across the accept-set boundaries the bracket dispatch's
28602        // three-arm gate carves out
28603        // ([`crate::render::require_positive_canonical_bounded_duration`]
28604        // — zero-floor + canonical-form + upper-cap).
28605        for timeout in [
28606            None,
28607            Some(Duration::ZERO),
28608            Some(Duration::from_millis(1)),
28609            Some(POLICY_TIMEOUT_MAX),
28610        ] {
28611            let p = MeshPolicy {
28612                timeout,
28613                ..MeshPolicy::default()
28614            };
28615            assert_eq!(
28616                p.timeout(),
28617                p.timeout,
28618                "MeshPolicy::timeout accessor must byte-equal the raw \
28619                 .timeout field across every accept-set boundary the \
28620                 validate_politicas :timeout arm carves out — a drift \
28621                 here would silently split the validate bracket's arm \
28622                 from the peer caixa-mesh HTTPRoute timeout-overlay \
28623                 emitter's read",
28624            );
28625        }
28626
28627        // (2) Accessor byte-equal to raw field on the `:retries` axis
28628        // across the accept-set boundaries the bracket dispatch's
28629        // two-arm gate carves out
28630        // ([`crate::render::require_positive_bounded_u32`] — zero-floor
28631        // + upper-cap).
28632        for retries in [
28633            None,
28634            Some(0u32),
28635            Some(1u32),
28636            Some(POLICY_RETRIES_MAX),
28637            Some(POLICY_RETRIES_MAX + 1),
28638            Some(u32::MAX),
28639        ] {
28640            let p = MeshPolicy {
28641                retries,
28642                ..MeshPolicy::default()
28643            };
28644            assert_eq!(
28645                p.retries(),
28646                p.retries,
28647                "MeshPolicy::retries accessor must byte-equal the raw \
28648                 .retries field across every accept-set boundary the \
28649                 validate_politicas :retries arm carves out — a drift \
28650                 here would silently split the validate bracket's arm \
28651                 from the peer caixa-mesh HTTPRoute retry-overlay \
28652                 emitter's read",
28653            );
28654        }
28655
28656        // (3) `PolicyTimeoutZero` fires on the accessor-projected
28657        // zero-floor boundary. A silent detour that no longer read
28658        // through `p.timeout()` (a peer-axis field read, an accidental
28659        // Option::and-then chain that collapsed the None arm to Some,
28660        // an accessor rebrand that clamped the return through the
28661        // upper cap) would fail to refuse here.
28662        let mut spec = three_member_spec();
28663        spec.politicas.timeout = Some(Duration::ZERO);
28664        spec.politicas.retries = None;
28665        spec.politicas.circuit_breaker = None;
28666        spec.politicas.rate_limit = None;
28667        assert_eq!(
28668            spec.politicas().timeout(),
28669            Some(Duration::ZERO),
28670            "the accessor projection must reflect the fixture's \
28671             `Some(Duration::ZERO)` :timeout verbatim",
28672        );
28673        assert_eq!(
28674            spec.validate().unwrap_err(),
28675            AplicacaoError::PolicyTimeoutZero,
28676            "the validate_politicas :timeout zero-floor arm must fire \
28677             through the lifted accessor's projection — a silent \
28678             detour to a peer-axis field would fail to refuse",
28679        );
28680
28681        // (4) `PolicyRetriesZero` fires on the accessor-projected
28682        // zero-floor boundary on the sibling `:retries` axis.
28683        let mut spec = three_member_spec();
28684        spec.politicas.timeout = None;
28685        spec.politicas.retries = Some(0);
28686        spec.politicas.circuit_breaker = None;
28687        spec.politicas.rate_limit = None;
28688        assert_eq!(
28689            spec.politicas().retries(),
28690            Some(0),
28691            "the accessor projection must reflect the fixture's \
28692             `Some(0)` :retries verbatim",
28693        );
28694        assert_eq!(
28695            spec.validate().unwrap_err(),
28696            AplicacaoError::PolicyRetriesZero,
28697            "the validate_politicas :retries zero-floor arm must fire \
28698             through the lifted accessor's projection — a silent \
28699             detour to a peer-axis field would fail to refuse",
28700        );
28701
28702        // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
28703        // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
28704        // must pass validate under the accessor projection — pins the
28705        // upper-boundary accept-arm also routes through the lifted
28706        // accessor (a drift that clamped or short-circuited at the
28707        // upper boundary would fail the whole-spec validate here).
28708        let mut spec = three_member_spec();
28709        spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
28710        spec.politicas.retries = Some(POLICY_RETRIES_MAX);
28711        spec.politicas.circuit_breaker = None;
28712        spec.politicas.rate_limit = None;
28713        assert_eq!(
28714            spec.politicas().timeout(),
28715            Some(POLICY_TIMEOUT_MAX),
28716            "the accessor projection must reflect the fixture's \
28717             at-cap :timeout verbatim",
28718        );
28719        assert_eq!(
28720            spec.politicas().retries(),
28721            Some(POLICY_RETRIES_MAX),
28722            "the accessor projection must reflect the fixture's \
28723             at-cap :retries verbatim",
28724        );
28725        assert!(
28726            spec.validate().is_ok(),
28727            "at-cap :timeout + :retries must pass validate under the \
28728             accessor projection — the upper-boundary accept-arm on \
28729             both axes routes through the lifted accessor",
28730        );
28731    }
28732
28733    #[test]
28734    fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
28735        // The canonical per-`:placement` outer-composite-reference-shape
28736        // pin: [`AplicacaoSpec::placement`] must return the `:placement`
28737        // typed `Placement` verbatim as a `&Placement` reference over the
28738        // same backing storage the raw `&self.placement` field access
28739        // borrows from, byte-equal across every representative fixture in
28740        // the accept-set — the default `Placement` (the substrate seed
28741        // shape whose [`PlacementStrategy::default`] evaluates to
28742        // `SingleNode` with an empty `:clusters` pool and both
28743        // optional-scalar axes `None`), and every canonical strategy /
28744        // cluster-pool / optional-scalar combination the
28745        // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
28746        // three [`PlacementStrategy`] variants — `SingleNode`,
28747        // `Replicated`, `Sharded` — cross-projected with a non-empty
28748        // `:clusters` pool and, on the `Sharded` arm, a non-empty
28749        // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
28750        // canonical `three_member_spec` `Replicated` fixture's
28751        // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
28752        //
28753        // Pins against a future silent detour that returned a fresh-
28754        // cloned `Placement` copy (which would type-check via a `Clone`
28755        // impl but silently break every downstream caller that relied on
28756        // the reference sharing the composite's backing identity), a
28757        // reference to an operator-resolved overlay (the future per-
28758        // cluster `:placement-overrides` slot MESH-COMPOSITION §V
28759        // acknowledges — its resolution must land at exactly this
28760        // accessor body, not silently divert the raw slot away from a
28761        // second consumer), or an axis-shuffled projection (a future
28762        // detour that swapped `clusters` and `affinity` through the
28763        // accessor would silently split the paired `validate_placement`
28764        // per-axis bracket-dispatch's traversal input from the peer
28765        // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
28766        // programs.yaml distribution-annotation emitter's fan-out input
28767        // from the peer `feira app graph` per-Aplicacao print line's
28768        // input).
28769        //
28770        // Peer of the sibling M3
28771        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
28772        // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
28773        // outer mesh-policy composite-reference axis, and of the sibling
28774        // slice-return `aplicacao_spec_membros_returns_membros_slice_
28775        // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
28776        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
28777        // across_permutations` (0dcc926) `&[WitContract]` pins — extends
28778        // the outer-accessor byte-equal-projection discipline onto the
28779        // outermost M3 mesh-slot type's per-Aplicacao distribution
28780        // composite-reference axis, the second `&Composite`-return
28781        // accessor on the outer [`AplicacaoSpec`] type.
28782        let fixtures: Vec<Placement> = vec![
28783            Placement::default(),
28784            Placement {
28785                estrategia: PlacementStrategy::SingleNode,
28786                clusters: vec!["rio".into()],
28787                affinity: None,
28788                shard_key: None,
28789            },
28790            Placement {
28791                estrategia: PlacementStrategy::Replicated,
28792                clusters: vec!["rio".into(), "mar".into()],
28793                affinity: None,
28794                shard_key: None,
28795            },
28796            Placement {
28797                estrategia: PlacementStrategy::Replicated,
28798                clusters: vec!["rio".into(), "mar".into()],
28799                affinity: Some("data-locality".into()),
28800                shard_key: None,
28801            },
28802            Placement {
28803                estrategia: PlacementStrategy::Sharded,
28804                clusters: vec!["rio".into(), "mar".into()],
28805                affinity: None,
28806                shard_key: Some("tenantId".into()),
28807            },
28808            Placement {
28809                estrategia: PlacementStrategy::Sharded,
28810                clusters: vec!["rio".into(), "mar".into(), "sol".into()],
28811                affinity: Some("low-latency".into()),
28812                shard_key: Some("metadata.tenantId".into()),
28813            },
28814        ];
28815        for placement in fixtures {
28816            let s = AplicacaoSpec {
28817                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
28818                contratos: Vec::new(),
28819                politicas: MeshPolicy::default(),
28820                placement: placement.clone(),
28821                entrada: None,
28822            };
28823            assert_eq!(
28824                *s.placement(),
28825                placement,
28826                "AplicacaoSpec::placement must return :placement verbatim \
28827                 (got {:?}, expected {:?})",
28828                s.placement(),
28829                placement,
28830            );
28831            assert!(
28832                std::ptr::eq(s.placement(), &s.placement),
28833                "AplicacaoSpec::placement accessor and &self.placement \
28834                 field access must borrow the same backing storage — the \
28835                 accessor is the substrate-primitive typed dispatch every \
28836                 downstream distribution-composite consumer must route \
28837                 through, and a reference-identity split would silently \
28838                 break every consumer that relied on the borrow sharing \
28839                 the composite's storage",
28840            );
28841            assert_eq!(
28842                s.placement().estrategia(),
28843                s.placement.estrategia,
28844                "AplicacaoSpec::placement().estrategia() must byte-equal \
28845                 self.placement.estrategia — a strategy-drift would \
28846                 silently split the paired `validate_placement` \
28847                 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
28848                 peer caixa-mesh programs.yaml `placement.estrategia` \
28849                 emitter's key from the peer `feira app graph` printer's \
28850                 strategy label",
28851            );
28852            assert_eq!(
28853                s.placement().clusters(),
28854                s.placement.clusters.as_slice(),
28855                "AplicacaoSpec::placement().clusters() must byte-equal \
28856                 self.placement.clusters — a cluster-pool drift would \
28857                 silently split the paired `validate_placement` \
28858                 pre-flight `.is_empty()` refusal probe's traversal from \
28859                 the peer caixa-mesh programs.yaml `placement.clusters` \
28860                 emitter's fan-out from the peer `feira app graph` \
28861                 printer's cluster list",
28862            );
28863        }
28864    }
28865
28866    #[test]
28867    fn validate_placement_reads_through_lifted_placement_accessor() {
28868        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
28869        // per-axis bracket-dispatch seed (`let p = self.placement();`,
28870        // followed by the per-axis fan-out `p.clusters()` /
28871        // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
28872        // lifted axis-level accessor family) must key off the lifted
28873        // outer accessor, so any future rebrand on the typed slot's
28874        // outer-composite reader shape lands at exactly one place. Pins
28875        // the multi-axis coherence by exercising each per-axis refusal
28876        // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
28877        // `:clusters` pool under the outer accessor's reference
28878        // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
28879        // strategy with a `None` `:shard-key` under the same projection,
28880        // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
28881        // with a `Some` `:shard-key` under the same projection, and
28882        // (4) the canonical `three_member_spec` `Replicated` fixture
28883        // passes `validate_placement` under the outer accessor's
28884        // reference projection — the accessor's reference-projection
28885        // reaches every per-axis branch (cluster-pool refusal, `Sharded`
28886        // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
28887        // without silently short-circuiting any.
28888        //
28889        // Peer of the sibling M3
28890        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
28891        // (534dc21) multi-axis coherence pin on the per-`:politicas`
28892        // outer mesh-policy composite-reference axis — extends the
28893        // multi-consumer coherence discipline onto the outermost M3
28894        // mesh-slot type's per-Aplicacao distribution composite-
28895        // reference axis, the second `&Composite`-return accessor on
28896        // the outer [`AplicacaoSpec`] type.
28897
28898        // (1) `PlacementWithoutClusters` refusal under the outer
28899        // accessor's reference projection: an empty `:clusters` pool
28900        // must trip the pre-flight refusal probe. The bracket-dispatch's
28901        // first arm reads `p.clusters()` on the reference returned by
28902        // the outer accessor.
28903        let mut spec = three_member_spec();
28904        spec.placement.clusters = Vec::new();
28905        assert_eq!(
28906            spec.validate().unwrap_err(),
28907            AplicacaoError::PlacementWithoutClusters {
28908                estrategia: PlacementStrategy::Replicated,
28909            },
28910        );
28911        assert!(
28912            std::ptr::eq(spec.placement(), &spec.placement),
28913            "the `validate_placement` per-axis bracket-dispatch's \
28914             traversal input must be the same backing composite the \
28915             accessor's reference projection borrows from",
28916        );
28917
28918        // (2) `ShardedWithoutKey` refusal under the outer accessor's
28919        // reference projection: a `Sharded` strategy with a `None`
28920        // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
28921        // The bracket-dispatch's third arm reads `p.estrategia()` for
28922        // the match scrutinee then `p.shard_key()` for the cascade
28923        // scrutinee, both on the reference returned by the outer
28924        // accessor.
28925        let mut spec = three_member_spec();
28926        spec.placement.estrategia = PlacementStrategy::Sharded;
28927        spec.placement.shard_key = None;
28928        assert_eq!(
28929            spec.validate().unwrap_err(),
28930            AplicacaoError::ShardedWithoutKey,
28931        );
28932
28933        // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
28934        // reference projection: a non-`Sharded` strategy with a `Some`
28935        // `:shard-key` must trip the declared-but-inert refusal. The
28936        // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
28937        // + `p.estrategia()` for the diagnostic on the reference
28938        // returned by the outer accessor.
28939        let mut spec = three_member_spec();
28940        spec.placement.estrategia = PlacementStrategy::Replicated;
28941        spec.placement.shard_key = Some("tenantId".into());
28942        assert_eq!(
28943            spec.validate().unwrap_err(),
28944            AplicacaoError::ShardKeyOnNonSharded {
28945                estrategia: PlacementStrategy::Replicated,
28946                shard_key: "tenantId".into(),
28947            },
28948        );
28949
28950        // (4) Canonical `three_member_spec` `Replicated` fixture passes
28951        // `validate_placement` — every per-axis arm reaches the fall-
28952        // through `Ok(())` without any per-axis refusal firing under the
28953        // outer accessor's reference projection.
28954        let spec = three_member_spec();
28955        assert!(
28956            spec.validate().is_ok(),
28957            "the canonical Replicated placement fixture must pass \
28958             `validate_placement` — every per-axis arm short-circuits on \
28959             valid input under the outer accessor's reference projection",
28960        );
28961        assert_eq!(
28962            spec.placement().estrategia(),
28963            PlacementStrategy::Replicated,
28964            "the outer accessor's reference projection must be the \
28965             canonical Replicated fixture's strategy",
28966        );
28967        assert_eq!(
28968            spec.placement().clusters(),
28969            &["rio", "mar"],
28970            "the outer accessor's reference projection must be the \
28971             canonical Replicated fixture's cluster pool",
28972        );
28973    }
28974
28975    #[test]
28976    fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
28977        // The canonical per-`:entrada` outer-composite-optional-
28978        // reference-shape pin: [`AplicacaoSpec::entrada`] must return
28979        // the `:entrada` typed `Option<Entrada>` verbatim as an
28980        // `Option<&Entrada>` reference over the same backing storage
28981        // the raw `self.entrada.as_ref()` field access borrows from,
28982        // byte-equal across every representative fixture in the
28983        // accept-set — the author-omitted `None` shape (the
28984        // "internal-only mesh" partition every downstream external-
28985        // gateway emitter treats as "emit nothing"), the minimal
28986        // singleton `:entrada` composite (host + destination + empty
28987        // paths + default port), the paths-carrying composite (the
28988        // canonical `three_member_spec` fixture's ["/api" "/health"]
28989        // path-list shape every HTTPRoute per-rule fan-out emitter
28990        // reads), and the non-default port composite (the canonical
28991        // custom-port shape the port-fallback resolver reads).
28992        //
28993        // Pins against a future silent detour that returned a fresh-
28994        // cloned `Entrada` copy (which would type-check via a `Clone`
28995        // impl but silently break every downstream caller that
28996        // relied on the reference sharing the composite's backing
28997        // identity), a reference to an operator-resolved overlay
28998        // (the future per-cluster `:entrada-overrides` slot the
28999        // MESH-COMPOSITION §V federation roadmap acknowledges — its
29000        // resolution must land at exactly this accessor body, not
29001        // silently divert the raw slot away from a second consumer),
29002        // a `None` → `Some(Entrada::default)` cluster-default
29003        // projection (which would collapse the load-bearing
29004        // "author-omitted `:entrada` ⇒ internal-only mesh" partition
29005        // the peer `gateway_routes` early-return + `feira app graph`
29006        // internal-only-mesh partition both read), or an axis-
29007        // shuffled projection (a future detour that swapped
29008        // `host` and `para` through the accessor would silently
29009        // split the paired `validate` per-`:entrada` shape-and-
29010        // membership gate's traversal input from the peer
29011        // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
29012        // fan-out input from the peer `feira app graph` external-
29013        // gateway summary line).
29014        //
29015        // Peer of the sibling M3
29016        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
29017        // (534dc21) `&MeshPolicy` byte-equal pin on the per-
29018        // `:politicas` outer mesh-policy composite-reference axis
29019        // and of the sibling M3
29020        // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
29021        // (9abb8f0) `&Placement` byte-equal pin on the per-
29022        // `:placement` outer distribution-composite composite-
29023        // reference axis — extends the outer-accessor byte-equal-
29024        // projection discipline onto the last unlifted outermost M3
29025        // mesh-slot type's per-Aplicacao external-gateway composite-
29026        // reference axis, the third and final `&Composite`-return
29027        // accessor on the outer [`AplicacaoSpec`] type.
29028        let fixtures: Vec<Option<Entrada>> = vec![
29029            None,
29030            Some(Entrada {
29031                host: "checkout.quero.cloud".into(),
29032                para: "cart".into(),
29033                paths: Vec::new(),
29034                port: DEFAULT_SERVICO_PORT,
29035            }),
29036            Some(Entrada {
29037                host: "checkout.quero.cloud".into(),
29038                para: "cart".into(),
29039                paths: vec!["/api".into(), "/health".into()],
29040                port: DEFAULT_SERVICO_PORT,
29041            }),
29042            Some(Entrada {
29043                host: "checkout.quero.cloud".into(),
29044                para: "cart".into(),
29045                paths: vec!["/api".into()],
29046                port: 9443,
29047            }),
29048        ];
29049        for entrada in fixtures {
29050            let s = AplicacaoSpec {
29051                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
29052                contratos: Vec::new(),
29053                politicas: MeshPolicy::default(),
29054                placement: Placement::default(),
29055                entrada: entrada.clone(),
29056            };
29057            assert_eq!(
29058                s.entrada(),
29059                entrada.as_ref(),
29060                "AplicacaoSpec::entrada must return :entrada verbatim \
29061                 (got {:?}, expected {:?})",
29062                s.entrada(),
29063                entrada.as_ref(),
29064            );
29065            match (s.entrada(), s.entrada.as_ref()) {
29066                (Some(a), Some(b)) => assert!(
29067                    std::ptr::eq(a, b),
29068                    "AplicacaoSpec::entrada accessor and \
29069                     self.entrada.as_ref() field access must borrow \
29070                     the same backing storage — the accessor is the \
29071                     substrate-primitive typed dispatch every \
29072                     downstream external-gateway composite consumer \
29073                     must route through, and a reference-identity \
29074                     split would silently break every consumer that \
29075                     relied on the borrow sharing the composite's \
29076                     storage",
29077                ),
29078                (None, None) => {}
29079                _ => panic!(
29080                    "AplicacaoSpec::entrada presence bit must byte-\
29081                     equal self.entrada.is_some() — a presence-bit \
29082                     drift would silently split the paired `validate` \
29083                     per-`:entrada` shape-and-membership gate's \
29084                     traversal head from the peer \
29085                     caixa-mesh gateway_routes early-return partition \
29086                     from the peer `feira app graph` internal-only-\
29087                     mesh partition",
29088                ),
29089            }
29090            assert_eq!(
29091                s.entrada().is_some(),
29092                s.entrada.is_some(),
29093                "AplicacaoSpec::entrada().is_some() must byte-equal \
29094                 self.entrada.is_some() — a presence-bit drift would \
29095                 silently split every downstream `Option<&Entrada>` \
29096                 consumer's partition on the internal-only-mesh arm",
29097            );
29098        }
29099    }
29100
29101    #[test]
29102    fn validate_reads_through_lifted_entrada_accessor() {
29103        // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
29104        // per-`:entrada` shape-and-membership gate (`if let Some(e) =
29105        // self.entrada() { … }`, followed by the per-axis fan-out
29106        // `validate_entrada_para(&e.para)` /
29107        // `EntradaMemberMissing` membership lookup /
29108        // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
29109        // per-`e.paths` `validate_entrada_path` traversal) must key
29110        // off the lifted outer accessor, so any future rebrand on
29111        // the typed slot's outer-composite reader shape lands at
29112        // exactly one place. Pins the multi-axis coherence by
29113        // exercising each per-axis refusal end-to-end: (1) the
29114        // author-omitted `None` shape short-circuits past every
29115        // per-`:entrada` refusal (the internal-only mesh partition
29116        // the accessor's `None` arm names), (2) `EntradaMemberMissing`
29117        // fires on a well-shaped but phantom `:para` under the outer
29118        // accessor's reference projection, and (3) the canonical
29119        // `three_member_spec` `:entrada` fixture passes `validate`
29120        // under the outer accessor's reference projection.
29121        //
29122        // Peer of the sibling M3
29123        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
29124        // (534dc21) multi-axis coherence pin on the per-`:politicas`
29125        // outer mesh-policy composite-reference axis and the sibling
29126        // M3
29127        // [`validate_placement_reads_through_lifted_placement_accessor`]
29128        // (9abb8f0) multi-axis coherence pin on the per-`:placement`
29129        // outer distribution-composite composite-reference axis —
29130        // extends the multi-consumer coherence discipline onto the
29131        // last unlifted outermost M3 mesh-slot type's per-Aplicacao
29132        // external-gateway composite-reference axis, the third and
29133        // final `&Composite`-return accessor on the outer
29134        // [`AplicacaoSpec`] type.
29135
29136        // (1) `None` :entrada — the internal-only-mesh partition
29137        // short-circuits past every per-`:entrada` refusal. The outer
29138        // accessor's reference projection reaches the fall-through
29139        // `Ok(())` on the `None` arm without any per-axis refusal
29140        // firing.
29141        let mut spec = three_member_spec();
29142        spec.entrada = None;
29143        assert!(
29144            spec.validate().is_ok(),
29145            "an author-omitted `:entrada` must pass `validate` — the \
29146             internal-only-mesh partition short-circuits past every \
29147             per-`:entrada` refusal under the outer accessor's \
29148             reference projection",
29149        );
29150        assert!(
29151            spec.entrada().is_none(),
29152            "the outer accessor's reference projection must name the \
29153             internal-only-mesh partition per the `None` fixture",
29154        );
29155
29156        // (2) `EntradaMemberMissing` refusal under the outer accessor's
29157        // reference projection: a well-shaped but phantom `:para` must
29158        // trip the membership-lookup refusal. The gate's second arm
29159        // reads `e.para` on the reference returned by the outer
29160        // accessor.
29161        let mut spec = three_member_spec();
29162        if let Some(e) = spec.entrada.as_mut() {
29163            e.para = "phantom".into();
29164        }
29165        assert_eq!(
29166            spec.validate().unwrap_err(),
29167            AplicacaoError::EntradaMemberMissing {
29168                para: "phantom".into(),
29169            },
29170        );
29171        match (spec.entrada(), spec.entrada.as_ref()) {
29172            (Some(a), Some(b)) => assert!(
29173                std::ptr::eq(a, b),
29174                "the `validate` per-`:entrada` gate's traversal head \
29175                 must be the same backing composite the accessor's \
29176                 reference projection borrows from",
29177            ),
29178            _ => panic!("fixture must carry Some(:entrada)"),
29179        }
29180
29181        // (3) Canonical `three_member_spec` `:entrada` fixture passes
29182        // `validate` — every per-axis arm reaches the fall-through
29183        // `Ok(())` without any per-axis refusal firing under the
29184        // outer accessor's reference projection.
29185        let spec = three_member_spec();
29186        assert!(
29187            spec.validate().is_ok(),
29188            "the canonical `:entrada` fixture must pass `validate` — \
29189             every per-axis arm short-circuits on valid input under \
29190             the outer accessor's reference projection",
29191        );
29192        assert!(
29193            spec.entrada().is_some(),
29194            "the outer accessor's reference projection must be the \
29195             canonical `:entrada` fixture's composite",
29196        );
29197    }
29198
29199    #[test]
29200    fn membro_names_matches_inline_membros_projection() {
29201        // Substrate-primitive ≡ inline-projection pin on
29202        // [`AplicacaoSpec::membro_names`]: the lifted membership oracle
29203        // must be byte-for-byte the set the pre-lift inline
29204        // `self.membros().iter().map(Membro::nome).collect()` builder
29205        // produced, on every membership shape the three
29206        // Servico-name-*reference* axes (`:contratos :de`, `:contratos
29207        // :para`, `:entrada :para`) resolve against. Pins the
29208        // projection so a future rebrand of the node-identity axis
29209        // lands at the primitive rather than diverging between the
29210        // per-`:contratos` membership arms still inline at `validate`
29211        // and the lifted `validate_entrada` gate.
29212        for membros in [
29213            vec![],
29214            vec![membro("cart", "^0.1")],
29215            vec![
29216                membro("catalog", "^0.1"),
29217                membro("cart", "^0.1"),
29218                membro("payment", "^0.2"),
29219            ],
29220        ] {
29221            let mut spec = three_member_spec();
29222            spec.membros = membros;
29223            let inline: std::collections::HashSet<&str> =
29224                spec.membros().iter().map(Membro::nome).collect();
29225            assert_eq!(
29226                spec.membro_names(),
29227                inline,
29228                "the lifted membership oracle must discriminate the \
29229                 same node set as the pre-lift inline projection",
29230            );
29231        }
29232    }
29233
29234    #[test]
29235    fn validate_entrada_matches_gate_on_every_per_axis_shape() {
29236        // Per-slot-gate ≡ validate equivalence pin on the lifted
29237        // [`AplicacaoSpec::validate_entrada`]: the named per-slot gate
29238        // must discriminate the same set as [`AplicacaoSpec::validate`]
29239        // on every `:entrada`-covered input, so a future consumer that
29240        // re-validates the one slot (the M4 admission webhook
29241        // re-checking `:entrada` after a gateway-host patch) accepts
29242        // exactly what `feira build` accepts and surfaces the same
29243        // diagnostic on the same input. Covers each of the five gated
29244        // axes plus the two clean-pass shapes (`None` — the
29245        // internal-only-mesh partition — and the canonical fixture).
29246        //
29247        // Peer of the sibling per-slot equivalence pins
29248        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
29249        // / `_on_cross_axis_and_clean_pass_shapes` (f03a154) on the
29250        // `:politicas` slot's compound entry gate, extended here onto
29251        // the `:entrada` slot's newly-named per-slot gate.
29252        /// One `:entrada` equivalence case: a label, the per-axis
29253        /// mutation applied to the canonical fixture's composite, and
29254        /// the diagnostic both the per-slot gate and `validate` must
29255        /// surface on it (`None` = clean pass).
29256        type EntradaCase = (&'static str, fn(&mut Entrada), Option<AplicacaoError>);
29257
29258        let cases: &[EntradaCase] = &[
29259            (
29260                ":para shape — empty",
29261                |e| e.para = String::new(),
29262                Some(AplicacaoError::EntradaParaEmpty),
29263            ),
29264            (
29265                ":para membership — well-shaped phantom",
29266                |e| e.para = "phantom".into(),
29267                Some(AplicacaoError::EntradaMemberMissing {
29268                    para: "phantom".into(),
29269                }),
29270            ),
29271            (
29272                ":host emptiness",
29273                |e| e.host = String::new(),
29274                Some(AplicacaoError::EmptyEntradaHost),
29275            ),
29276            (
29277                ":port structural floor",
29278                |e| e.port = 0,
29279                Some(AplicacaoError::EntradaPortZero),
29280            ),
29281            (
29282                ":paths per-entry emptiness",
29283                |e| e.paths = vec![String::new()],
29284                Some(AplicacaoError::EntradaPathEmpty),
29285            ),
29286            (
29287                ":paths leading-slash grammar",
29288                |e| e.paths = vec!["api/cart".into()],
29289                Some(AplicacaoError::EntradaPathNotAbsolute {
29290                    path: "api/cart".into(),
29291                }),
29292            ),
29293            (
29294                ":paths set-not-multiset",
29295                |e| e.paths = vec!["/api/cart".into(), "/api/cart".into()],
29296                Some(AplicacaoError::EntradaPathDuplicate {
29297                    path: "/api/cart".into(),
29298                }),
29299            ),
29300            ("clean pass — canonical fixture", |_| {}, None),
29301        ];
29302        for (label, mutate, expected) in cases {
29303            let mut spec = three_member_spec();
29304            mutate(spec.entrada.as_mut().expect("fixture carries :entrada"));
29305            assert_eq!(
29306                spec.validate_entrada().err(),
29307                *expected,
29308                "per-slot gate disagreed with the expected diagnostic on {label}",
29309            );
29310            assert_eq!(
29311                spec.validate().err(),
29312                *expected,
29313                "`validate` disagreed with the per-slot gate on {label}",
29314            );
29315        }
29316
29317        // The `None` arm is the internal-only-mesh partition: a clean
29318        // pass through both the per-slot gate and `validate`, not a
29319        // refusal.
29320        let mut spec = three_member_spec();
29321        spec.entrada = None;
29322        assert_eq!(spec.validate_entrada().err(), None);
29323        assert_eq!(spec.validate().err(), None);
29324    }
29325
29326    #[test]
29327    fn validate_entrada_resolves_membership_through_own_oracle() {
29328        // Self-containment pin on the lifted per-slot gate:
29329        // [`AplicacaoSpec::validate_entrada`] resolves `:entrada :para`
29330        // against the oracle *it* builds through
29331        // [`AplicacaoSpec::membro_names`], not one threaded down from
29332        // [`AplicacaoSpec::validate`]. A spec whose `:membros` no
29333        // longer contains the `:entrada :para` target must trip
29334        // `EntradaMemberMissing` when the per-slot gate is called
29335        // directly — the shape a future single-slot re-validator
29336        // (the M4 admission webhook) reaches the axis through, without
29337        // re-walking `:membros` / `:contratos` / the sync-cycle
29338        // detector first. Same self-contained posture
29339        // [`AplicacaoSpec::detect_sync_cycles`] already carries for
29340        // the M4 per-edge policy resolver.
29341        let mut spec = three_member_spec();
29342        spec.membros.retain(|m| m.nome() != "cart");
29343        assert_eq!(
29344            spec.validate_entrada().unwrap_err(),
29345            AplicacaoError::EntradaMemberMissing {
29346                para: "cart".into(),
29347            },
29348            "the per-slot gate must resolve `:para` against the oracle \
29349             it builds itself, with no membership set threaded in",
29350        );
29351        assert!(
29352            !spec.membro_names().contains("cart"),
29353            "fixture must have dropped the `:entrada :para` target \
29354             from the graph's node set",
29355        );
29356    }
29357
29358    #[test]
29359    fn validate_contratos_matches_gate_on_every_per_axis_shape() {
29360        // Per-slot-gate ≡ validate equivalence pin on the lifted
29361        // [`AplicacaoSpec::validate_contratos`]: the named per-slot
29362        // gate must discriminate the same set as
29363        // [`AplicacaoSpec::validate`] on every `:contratos`-covered
29364        // input, so a future consumer that re-validates the one slot
29365        // (the M4 admission webhook re-checking `:contratos` after a
29366        // per-`(:de, :para)` edge patch, the per-`:contratos`-edge
29367        // `:politicas` override MESH-COMPOSITION §III.2 #3
29368        // acknowledges — which resolves an effective per-edge
29369        // [`MeshPolicy`] and must re-check the edge's identity closure
29370        // before it can key a per-edge override off the endpoint
29371        // tuple) accepts exactly what `feira build` accepts and
29372        // surfaces the same diagnostic on the same input. Covers each
29373        // of the six gated axes (`:de`/`:para` per-arm shape,
29374        // per-arm graph-membership, structural self-loop, `:wit`
29375        // emptiness) plus the clean-pass canonical fixture; the
29376        // reason-carrying arms (`ContratoCaixaInvalid` on `:de`/`:para`
29377        // shape, `ContratoWitInvalid` on WIT-shape ↔ target dispatch,
29378        // `ContratoDuplicate` on whole-edge dedup) whose `reason:` /
29379        // `target:` carriers depend on library implementation
29380        // details are pinned separately below with a `matches!`
29381        // predicate on the arm identity plus the mirror equivalence
29382        // between the two entry points.
29383        //
29384        // Peer of the sibling per-slot equivalence pins
29385        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
29386        // / `_on_cross_axis_and_clean_pass_shapes` (f03a154) on the
29387        // `:politicas` slot's compound entry gate, and
29388        // `validate_entrada_matches_gate_on_every_per_axis_shape`
29389        // (20cd523) on the `:entrada` slot's per-slot gate — extended
29390        // here onto the `:contratos` slot's newly-named per-slot gate,
29391        // closing the last unlifted per-slot gate on the M3 mesh-slot
29392        // family.
29393        /// One `:contratos` equivalence case: a label, the per-axis
29394        /// mutation applied to the canonical fixture's spec, and the
29395        /// diagnostic both the per-slot gate and `validate` must
29396        /// surface on it (`None` = clean pass).
29397        type ContratoCase = (&'static str, fn(&mut AplicacaoSpec), Option<AplicacaoError>);
29398
29399        let cases: &[ContratoCase] = &[
29400            (
29401                ":de shape — empty",
29402                |s| s.contratos[0].de = String::new(),
29403                Some(AplicacaoError::ContratoCaixaEmpty {
29404                    slot: crate::render::CONTRATO_AUTHOR_KEY_DE,
29405                }),
29406            ),
29407            (
29408                ":para shape — empty",
29409                |s| s.contratos[0].para = String::new(),
29410                Some(AplicacaoError::ContratoCaixaEmpty {
29411                    slot: crate::render::CONTRATO_AUTHOR_KEY_PARA,
29412                }),
29413            ),
29414            (
29415                ":de membership — well-shaped phantom",
29416                |s| s.contratos[0].de = "phantom".into(),
29417                Some(AplicacaoError::ContratoMemberMissing {
29418                    caixa: "phantom".into(),
29419                }),
29420            ),
29421            (
29422                ":para membership — well-shaped phantom",
29423                |s| s.contratos[0].para = "phantom".into(),
29424                Some(AplicacaoError::ContratoMemberMissing {
29425                    caixa: "phantom".into(),
29426                }),
29427            ),
29428            (
29429                "structural self-loop",
29430                |s| s.contratos[0].para = "cart".into(),
29431                Some(AplicacaoError::ContratoSelfLoop {
29432                    caixa: "cart".into(),
29433                    wit: "wasi:http/proxy".into(),
29434                }),
29435            ),
29436            (
29437                ":wit emptiness",
29438                |s| s.contratos[0].wit = String::new(),
29439                Some(AplicacaoError::EmptyWit {
29440                    de: "cart".into(),
29441                    para: "catalog".into(),
29442                }),
29443            ),
29444            ("clean pass — canonical fixture", |_| {}, None),
29445        ];
29446        for (label, mutate, expected) in cases {
29447            let mut spec = three_member_spec();
29448            mutate(&mut spec);
29449            assert_eq!(
29450                spec.validate_contratos().err(),
29451                *expected,
29452                "per-slot gate disagreed with the expected diagnostic on {label}",
29453            );
29454            assert_eq!(
29455                spec.validate().err(),
29456                *expected,
29457                "`validate` disagreed with the per-slot gate on {label}",
29458            );
29459        }
29460    }
29461
29462    #[test]
29463    fn validate_contratos_matches_gate_on_reason_carrying_arms() {
29464        // Companion pin to
29465        // [`validate_contratos_matches_gate_on_every_per_axis_shape`]:
29466        // the per-slot gate ≡ `validate` equivalence on the three
29467        // `:contratos` refusal arms whose diagnostic carries a
29468        // library-owned string ([`AplicacaoError::ContratoCaixaInvalid`]
29469        // and [`AplicacaoError::ContratoWrongTarget`] via the paired
29470        // `is_dns_1123_label` / `WitContract::target` shape helpers,
29471        // and [`AplicacaoError::ContratoDuplicate`] via [`WitTarget::label`]'s
29472        // library-formatted `target:` scalar). Value equality between
29473        // the per-slot gate and `validate` outputs pins the full
29474        // `Option<AplicacaoError>` (including reason-strings), and the
29475        // per-arm `matches!` predicate pins the arm-discriminator
29476        // identity on the specific `Contrato*` variant. Split from
29477        // the primary equivalence pin so each pin body stays under
29478        // [`clippy::too_many_lines`], the same shape the peer
29479        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
29480        // / `_on_cross_axis_and_clean_pass_shapes` split (f03a154)
29481        // carries on the `:politicas` slot's compound entry gate.
29482        type ContratoReasonCase = (
29483            &'static str,
29484            fn(&mut AplicacaoSpec),
29485            fn(&AplicacaoError) -> bool,
29486        );
29487        let cases: &[ContratoReasonCase] = &[
29488            (
29489                ":de shape — DNS-1123 invalid",
29490                |s| s.contratos[0].de = "Cart".into(),
29491                |err| {
29492                    matches!(
29493                        err,
29494                        AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. }
29495                            if *slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
29496                    )
29497                },
29498            ),
29499            (
29500                ":wit target-shape mismatch — payload on capability arm",
29501                |s| s.contratos[0].wit = "wasi:junk/nope".into(),
29502                |err| {
29503                    matches!(
29504                        err,
29505                        AplicacaoError::ContratoWrongTarget { de, para, wit, .. }
29506                            if de == "cart" && para == "catalog" && wit == "wasi:junk/nope"
29507                    )
29508                },
29509            ),
29510            (
29511                "whole-edge dedup — six-axis identity collision",
29512                |s| {
29513                    let dup = s.contratos[0].clone();
29514                    s.contratos.push(dup);
29515                },
29516                |err| {
29517                    matches!(
29518                        err,
29519                        AplicacaoError::ContratoDuplicate { de, para, wit, .. }
29520                            if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
29521                    )
29522                },
29523            ),
29524        ];
29525        for (label, mutate, arm_matches) in cases {
29526            let mut spec = three_member_spec();
29527            mutate(&mut spec);
29528            let per_slot = spec.validate_contratos().err();
29529            let gate = spec.validate().err();
29530            assert_eq!(
29531                per_slot, gate,
29532                "per-slot gate and `validate` must return byte-equal \
29533                 `Option<AplicacaoError>` on {label} (including \
29534                 library-owned reason strings)",
29535            );
29536            let err = per_slot
29537                .as_ref()
29538                .unwrap_or_else(|| panic!("expected refusal on {label}, got clean pass"));
29539            assert!(
29540                arm_matches(err),
29541                "per-slot gate surfaced the wrong arm on {label}: got {err:?}",
29542            );
29543        }
29544    }
29545
29546    #[test]
29547    fn validate_contratos_resolves_membership_through_own_oracle() {
29548        // Self-containment pin on the lifted per-slot gate:
29549        // [`AplicacaoSpec::validate_contratos`] resolves each edge's
29550        // `:de` / `:para` against the oracle *it* builds through
29551        // [`AplicacaoSpec::membro_names`], not one threaded down from
29552        // [`AplicacaoSpec::validate`]. A spec whose `:membros` no
29553        // longer contains a `:contratos` edge's endpoint must trip
29554        // `ContratoMemberMissing` when the per-slot gate is called
29555        // directly — the shape a future single-slot re-validator
29556        // (the M4 admission webhook re-checking `:contratos` after a
29557        // per-`(:de, :para)` edge patch, the M4 per-edge policy
29558        // resolver on the `:politicas` override axis) reaches the
29559        // axis through, without re-walking `:membros` / `:entrada` /
29560        // `:placement` / `:politicas` first. Same self-contained
29561        // posture the peer per-slot gates
29562        // [`AplicacaoSpec::detect_sync_cycles`] and
29563        // [`AplicacaoSpec::validate_entrada`] already carry for the
29564        // same M4 consumers.
29565        let mut spec = three_member_spec();
29566        spec.membros.retain(|m| m.nome() != "catalog");
29567        assert_eq!(
29568            spec.validate_contratos().unwrap_err(),
29569            AplicacaoError::ContratoMemberMissing {
29570                caixa: "catalog".into(),
29571            },
29572            "the per-slot gate must resolve `:de` / `:para` against \
29573             the oracle it builds itself, with no membership set \
29574             threaded in",
29575        );
29576        assert!(
29577            !spec.membro_names().contains("catalog"),
29578            "fixture must have dropped the `:contratos` edge's \
29579             `:para` target from the graph's node set",
29580        );
29581    }
29582
29583    #[test]
29584    fn validate_contratos_folds_cycle_axis_matches_gate() {
29585        // Fold-into-per-slot-gate equivalence pin on the
29586        // cross-edge cycle axis: an [`AplicacaoError::ContratoCycle`]
29587        // surfaces byte-equal through both
29588        // [`AplicacaoSpec::validate_contratos`] and
29589        // [`AplicacaoSpec::validate`] on a fixture whose only defect is
29590        // a synchronous-edge cycle in `:contratos`. Pins the fold that
29591        // moved the cross-edge cycle axis onto the per-slot gate — a
29592        // future silent regression that de-folded the axis back to the
29593        // outer [`AplicacaoSpec::validate`] dispatch (a rebase artifact,
29594        // a peer per-slot gate lift that skipped the cross-axis half of
29595        // the [`MeshPolicy::validate`]-analogous discipline) would
29596        // surface here as `Some(ContratoCycle)` from `validate` and
29597        // `None` from `validate_contratos`.
29598        //
29599        // Cycle fixture is the same shape as the peer
29600        // [`rejects_three_node_synchronous_cycle`] test carries: a
29601        // clean 3-cycle over the HTTP subgraph (catalog → cart →
29602        // payment → catalog), so the per-entry cascade (shape +
29603        // membership + self-loop + `:wit` emptiness + WIT-target +
29604        // whole-edge dedup) passes cleanly and the sole surviving
29605        // refusal shape is the cross-edge cycle axis. The `cycle`
29606        // vector is normalized to a sorted body set for the equality
29607        // compare (the traversal path's starting node depends on
29608        // BTreeMap iteration order, which is deterministic but is not
29609        // the load-bearing property this pin covers).
29610        //
29611        // Peer of the sibling per-slot ≡ `validate` equivalence pins
29612        // [`validate_contratos_matches_gate_on_every_per_axis_shape`]
29613        // (per-entry axes) and
29614        // [`validate_contratos_matches_gate_on_reason_carrying_arms`]
29615        // (parser-owned reason arms) already carry on the six
29616        // per-entry axes — this extends the discipline onto the
29617        // cross-edge cycle axis newly folded into the per-slot gate,
29618        // matching the peer per-slot compound gate
29619        // [`AplicacaoSpec::validate_politicas`] (f03a154) which folded
29620        // both per-axis and cross-axis surfaces on `:politicas`.
29621        let mut spec = three_member_spec();
29622        spec.contratos = vec![
29623            contract_http("catalog", "cart", "/x"),
29624            contract_http("cart", "payment", "/y"),
29625            contract_http("payment", "catalog", "/z"),
29626        ];
29627        let per_slot_err = spec.validate_contratos().unwrap_err();
29628        let gate_err = spec.validate().unwrap_err();
29629        assert_eq!(
29630            per_slot_err, gate_err,
29631            "the per-slot gate and `validate` must return byte-equal \
29632             `AplicacaoError::ContratoCycle` on a cycle-only fixture \
29633             — the fold pins the cross-edge axis onto the per-slot \
29634             gate the same way the peer `validate_politicas` fold \
29635             pinned the `:politicas` cross-axis surface",
29636        );
29637        match per_slot_err {
29638            AplicacaoError::ContratoCycle { ref cycle } => {
29639                assert_eq!(
29640                    cycle.first(),
29641                    cycle.last(),
29642                    "cycle traversal must close on the back-edge \
29643                     target — the diagnostic shape the peer \
29644                     `rejects_three_node_synchronous_cycle` pins",
29645                );
29646                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
29647                assert_eq!(body.len(), 3, "3-cycle must visit 3 distinct nodes");
29648                assert!(body.contains("cart"));
29649                assert!(body.contains("catalog"));
29650                assert!(body.contains("payment"));
29651            }
29652            other => panic!("expected ContratoCycle, got {other:?}"),
29653        }
29654    }
29655
29656    #[test]
29657    fn validate_contratos_per_entry_arm_fires_before_cycle_arm() {
29658        // Diagnostic-ordering pin on the fold: a `:contratos` fixture
29659        // carrying *both* a per-entry defect (a self-loop, the
29660        // structural-self-edge arm on the per-entry cascade — chosen
29661        // because it never masks or is masked by the cycle diagnostic
29662        // on the peer arms) *and* a would-be synchronous-edge cycle in
29663        // the remaining edges must surface the per-entry diagnostic
29664        // first through both [`AplicacaoSpec::validate_contratos`] and
29665        // [`AplicacaoSpec::validate`] — pinning the fold's canonical
29666        // per-entry-before-cross-edge dispatch ordering, byte-equal to
29667        // the pre-fold `validate`-side sequence
29668        // (`validate_contratos()? → detect_sync_cycles()?`) the
29669        // dispatch encoded verbatim. A silent regression that reversed
29670        // the ordering inside the fold would surface here as a cycle
29671        // diagnostic on a fixture carrying an earlier per-entry defect
29672        // — masking the narrower "this edge is degenerate" arm behind
29673        // the coarser "this graph deadlocks" arm.
29674        //
29675        // Peer of the diagnostic-ordering property the pre-fold
29676        // dispatch encoded at the [`AplicacaoSpec::validate`]
29677        // altitude (`validate_contratos()? → detect_sync_cycles()?`),
29678        // now enforced inside the per-slot gate's own body, so a future
29679        // consumer that reaches only the per-slot gate (the M4
29680        // admission webhook re-checking `:contratos` after a per-edge
29681        // patch) inherits the ordering property by construction.
29682        let mut spec = three_member_spec();
29683        // The three-member fixture already has cart → catalog and
29684        // cart → payment; adding catalog → cart closes a 2-cycle on
29685        // the HTTP subgraph.
29686        spec.contratos
29687            .push(contract_http("catalog", "cart", "/refresh"));
29688        // Add a self-loop on `payment` — the per-entry structural-
29689        // self-edge arm — which must surface first.
29690        spec.contratos
29691            .push(contract_http("payment", "payment", "/loop"));
29692        let per_slot_err = spec.validate_contratos().unwrap_err();
29693        let gate_err = spec.validate().unwrap_err();
29694        assert_eq!(
29695            per_slot_err, gate_err,
29696            "per-slot gate and `validate` must agree on the ordering \
29697             fixture's surfaced diagnostic — a divergence here means \
29698             the fold reshaped one dispatch's ordering without the \
29699             other",
29700        );
29701        assert!(
29702            matches!(
29703                per_slot_err,
29704                AplicacaoError::ContratoSelfLoop { ref caixa, .. }
29705                    if caixa == "payment"
29706            ),
29707            "the per-entry structural-self-edge arm must fire before \
29708             the cross-edge cycle arm — pinning the fold's per-entry-\
29709             before-cross-edge dispatch ordering byte-equal to the \
29710             pre-fold `validate_contratos()? → detect_sync_cycles()?` \
29711             sequence; got {per_slot_err:?}",
29712        );
29713    }
29714
29715    #[test]
29716    fn validate_contratos_cycle_axis_is_self_contained_on_slot() {
29717        // Self-containment pin on the folded cross-edge cycle axis:
29718        // [`AplicacaoSpec::validate_contratos`] surfaces
29719        // [`AplicacaoError::ContratoCycle`] directly against `&self`
29720        // without depending on the peer per-slot gates
29721        // ([`AplicacaoSpec::validate_membros`],
29722        // [`AplicacaoSpec::validate_entrada`],
29723        // [`AplicacaoSpec::validate_placement`],
29724        // [`AplicacaoSpec::validate_politicas`]) running first — the
29725        // shape a future single-slot re-validator (the M4 admission
29726        // webhook re-checking `:contratos` after a per-`(:de, :para)`
29727        // edge patch, the per-edge policy resolver MESH-COMPOSITION
29728        // §III.2 #3 acknowledges) reaches *both* structural axes on
29729        // the slot through one call. A spec with a per-`:politicas`
29730        // refusal shape (zero `:timeout`, the first per-axis arm the
29731        // peer [`MeshPolicy::validate`] gate covers) AND a
29732        // synchronous-edge cycle in `:contratos` must:
29733        //
29734        //   - surface [`AplicacaoError::ContratoCycle`] through the
29735        //     per-slot gate `validate_contratos` directly (proves the
29736        //     cycle axis reaches the per-slot altitude without the
29737        //     peer `:politicas` gate running first);
29738        //   - surface [`AplicacaoError::ContratoCycle`] through
29739        //     `validate` (which reaches `validate_contratos` before
29740        //     `validate_politicas` per the fixed dispatch order), so
29741        //     the fold's cross-slot ordering (`:membros` →
29742        //     `:contratos` → `:entrada` → `:placement` → `:politicas`)
29743        //     is byte-equal to the pre-fold dispatch's ordering.
29744        //
29745        // Same self-contained-on-`&self` posture the peer per-slot
29746        // gates [`AplicacaoSpec::validate_entrada`] (20cd523),
29747        // [`AplicacaoSpec::validate_contratos`] per-entry axis
29748        // (906a5c6), and [`AplicacaoSpec::validate_politicas`]
29749        // (f03a154) already carry — extended here onto the newly-
29750        // folded cross-edge cycle axis. Peer of the sibling per-slot
29751        // self-containment pins
29752        // `validate_entrada_resolves_membership_through_own_oracle`
29753        // and `validate_contratos_resolves_membership_through_own_oracle`
29754        // on the per-entry membership axis — extends the discipline
29755        // onto the cross-edge cycle axis of the same per-slot gate.
29756        let mut spec = three_member_spec();
29757        // Poison `:politicas` — zero-`:timeout` trips the first per-
29758        // axis arm the [`MeshPolicy::validate`] gate covers, so any
29759        // dispatch that reached `:politicas` would surface a
29760        // `:politicas` diagnostic instead of `ContratoCycle`.
29761        spec.politicas.timeout = Some(Duration::from_secs(0));
29762        // Close a synchronous-edge cycle on the HTTP subgraph.
29763        spec.contratos
29764            .push(contract_http("catalog", "cart", "/refresh"));
29765        let per_slot_err = spec.validate_contratos().unwrap_err();
29766        assert!(
29767            matches!(per_slot_err, AplicacaoError::ContratoCycle { .. }),
29768            "the per-slot gate must surface `ContratoCycle` directly \
29769             against `&self` — a peer per-slot gate's regression \
29770             would surface a non-`ContratoCycle` diagnostic here; \
29771             got {per_slot_err:?}",
29772        );
29773        let gate_err = spec.validate().unwrap_err();
29774        assert!(
29775            matches!(gate_err, AplicacaoError::ContratoCycle { .. }),
29776            "`validate`'s five-slot dispatch must reach the fold's \
29777             cross-edge cycle axis on `:contratos` before the peer \
29778             `:politicas` gate — a dispatch-order regression would \
29779             surface a `:politicas` diagnostic here; got {gate_err:?}",
29780        );
29781        // Sanity: the poisoned `:politicas` alone would trip
29782        // [`MeshPolicy::validate`] under the peer per-slot gate, so
29783        // the cycle-first surfacing above is a real ordering property,
29784        // not a case where the `:politicas` axis silently accepts the
29785        // fixture.
29786        let mut politicas_only = three_member_spec();
29787        politicas_only.politicas.timeout = Some(Duration::from_secs(0));
29788        assert!(
29789            politicas_only.validate_politicas().is_err(),
29790            "the poisoned `:politicas` fixture must trip the peer \
29791             per-slot gate on its own — otherwise the self-contained \
29792             cycle-first surfacing above would not be an ordering \
29793             property",
29794        );
29795    }
29796
29797    #[test]
29798    fn wit_contract_require_endpoints_in_folds_per_arm_membership_cascade() {
29799        // Fail-before-pass-after equivalence pin on the lifted
29800        // per-edge substrate primitive [`WitContract::require_endpoints_in`]:
29801        // both arms (`:de` phantom and `:para` phantom) must fire the
29802        // `AplicacaoError::ContratoMemberMissing` diagnostic with a
29803        // `caixa` carrier byte-equal to the offending accessor's
29804        // projection, and `:de` must fire before `:para` when both
29805        // arms would trip on the same call — preserving the canonical
29806        // edge-direction order the peer per-arm shape gate
29807        // [`validate_contrato_caixa`], the [`WitContract::is_self_loop`]
29808        // diagnostic, and every peer per-arm ordering in
29809        // [`AplicacaoSpec::validate_contratos`] already carry.
29810        //
29811        // Two-endpoint oracle covers exactly enough graph nodes to
29812        // exercise each arm in isolation: the `:de` arm fires when
29813        // the source is off-oracle and the destination is on-oracle,
29814        // the `:para` arm fires when the source is on-oracle and the
29815        // destination is off-oracle, and the `:de`-before-`:para`
29816        // ordering falls out from a probe where *both* endpoints are
29817        // off-oracle — the diagnostic's `caixa` field must byte-equal
29818        // the source, not the destination, pinning the primitive's
29819        // arm ordering as `:de` first.
29820        let mut names: std::collections::HashSet<&str> = std::collections::HashSet::new();
29821        names.insert("cart");
29822        names.insert("catalog");
29823
29824        // `:de` phantom, `:para` on-oracle
29825        let de_phantom = contract_http("phantom-de", "catalog", "/x");
29826        let err = de_phantom.require_endpoints_in(&names).unwrap_err();
29827        assert_eq!(
29828            err,
29829            AplicacaoError::ContratoMemberMissing {
29830                caixa: de_phantom.source().to_string(),
29831            },
29832            "the `:de` phantom arm must fire ContratoMemberMissing \
29833             with `caixa` byte-equal to `WitContract::source` — a \
29834             bypass here (a raw `.de.clone()` regression, a divergent \
29835             accessor on a per-CR alias table) would silently split \
29836             the primitive's diagnostic from the substrate-primitive \
29837             scalar accessor every downstream consumer routes through",
29838        );
29839
29840        // `:de` on-oracle, `:para` phantom
29841        let para_phantom = contract_http("cart", "phantom-para", "/x");
29842        let err = para_phantom.require_endpoints_in(&names).unwrap_err();
29843        assert_eq!(
29844            err,
29845            AplicacaoError::ContratoMemberMissing {
29846                caixa: para_phantom.destination().to_string(),
29847            },
29848            "the `:para` phantom arm must fire ContratoMemberMissing \
29849             with `caixa` byte-equal to `WitContract::destination` — \
29850             symmetric callee-side pin to the `:de` arm above",
29851        );
29852
29853        // Both endpoints off-oracle: the `:de` arm must fire first,
29854        // pinning the primitive's canonical edge-direction order.
29855        let both_phantom = contract_http("phantom-de", "phantom-para", "/x");
29856        let err = both_phantom.require_endpoints_in(&names).unwrap_err();
29857        assert_eq!(
29858            err,
29859            AplicacaoError::ContratoMemberMissing {
29860                caixa: both_phantom.source().to_string(),
29861            },
29862            "when both endpoints are off-oracle, the `:de` arm must \
29863             fire before the `:para` arm — preserving byte-equal \
29864             ordering with the pre-lift inline cascade in \
29865             `validate_contratos` and with every peer per-arm \
29866             ordering the sibling per-edge substrate primitives \
29867             already carry",
29868        );
29869
29870        // Both endpoints on-oracle: clean pass.
29871        let clean = contract_http("cart", "catalog", "/x");
29872        clean.require_endpoints_in(&names).unwrap();
29873    }
29874
29875    #[test]
29876    fn validate_contratos_membership_gate_routes_through_require_endpoints_in() {
29877        // Convergence pin: the whole-spec end-to-end route through
29878        // [`AplicacaoSpec::validate_contratos`] must reach the
29879        // per-edge substrate primitive
29880        // [`WitContract::require_endpoints_in`] on every membership
29881        // arm — the diagnostic fired at the per-slot altitude must
29882        // byte-equal the diagnostic the primitive fires when called
29883        // directly on the same edge and the same oracle. Pins the
29884        // primitive as the sole load-bearing gate on the membership
29885        // axis, so any future silent detour that re-inlined the twin
29886        // `if !names.contains(...)` cascade back into the per-slot
29887        // gate (a rebase-artifact regression, an M4 admission-webhook
29888        // consumer that bypassed the primitive) would surface here as
29889        // a byte-equal miss between the two dispatches.
29890        //
29891        // Same equivalence-pin discipline the peer
29892        // [`validate_contratos_matches_gate_on_every_per_axis_shape`]
29893        // pin already carries on the per-slot gate ≡ `validate` axis,
29894        // extended here onto the per-slot gate ≡ per-edge primitive
29895        // axis at one altitude deeper.
29896        for phantom_edge in [
29897            contract_http("phantom-de", "catalog", "/x"),
29898            contract_http("cart", "phantom-para", "/x"),
29899        ] {
29900            let mut spec = three_member_spec();
29901            spec.contratos.push(phantom_edge.clone());
29902            let per_slot_err = spec.validate_contratos().unwrap_err();
29903            let primitive_err = phantom_edge
29904                .require_endpoints_in(&spec.membro_names())
29905                .unwrap_err();
29906            assert_eq!(
29907                per_slot_err, primitive_err,
29908                "the per-slot gate must reach the per-edge substrate \
29909                 primitive on every membership arm — a bypass here \
29910                 would silently split the two dispatches on the \
29911                 same edge + same oracle input",
29912            );
29913            // And the diagnostic's `caixa` carrier must byte-equal
29914            // the offending accessor's projection at both altitudes,
29915            // pinning the accessor routing across the whole-spec
29916            // path.
29917            let AplicacaoError::ContratoMemberMissing { ref caixa } = per_slot_err else {
29918                panic!("expected ContratoMemberMissing, got {per_slot_err:?}");
29919            };
29920            let expected = if spec.membro_names().contains(phantom_edge.source()) {
29921                phantom_edge.destination()
29922            } else {
29923                phantom_edge.source()
29924            };
29925            assert_eq!(
29926                caixa, expected,
29927                "the whole-spec ContratoMemberMissing.caixa carrier \
29928                 must byte-equal the offending edge's accessor \
29929                 projection — a bypass here would silently split \
29930                 the wrap envelope's `caixa` field from the \
29931                 substrate-primitive scalar accessor every \
29932                 downstream consumer routes through",
29933            );
29934        }
29935    }
29936
29937    #[test]
29938    fn port_for_destination_reads_through_lifted_entrada_accessor() {
29939        // Peer coherence pin: the
29940        // [`AplicacaoSpec::port_for_destination`] per-destination
29941        // L4-port fallback resolver's composite-projection seed
29942        // (`self.entrada().filter(…).map_or(…)`) must key off the
29943        // lifted outer accessor. Pins the coherence by exercising
29944        // the resolver end-to-end: (1) the `None` `:entrada` shape
29945        // falls through to `DEFAULT_SERVICO_PORT` under the outer
29946        // accessor's reference projection, (2) a non-matching
29947        // destination falls through to `DEFAULT_SERVICO_PORT` under
29948        // the outer accessor's reference projection, and (3) the
29949        // matching destination resolves to the `:entrada :port`
29950        // value under the outer accessor's reference projection.
29951        //
29952        // Peer of the sibling
29953        // [`validate_reads_through_lifted_entrada_accessor`] multi-
29954        // consumer coherence pin on the same per-`:entrada` outer-
29955        // composite axis — extends the multi-consumer coherence
29956        // discipline onto the second per-`:entrada` production
29957        // consumer, the L4-port fallback resolver.
29958
29959        // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
29960        // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
29961        // arm under the outer accessor's reference projection.
29962        let mut spec = three_member_spec();
29963        spec.entrada = None;
29964        assert_eq!(
29965            spec.port_for_destination("cart"),
29966            DEFAULT_SERVICO_PORT,
29967            "the port-fallback resolver must fall through to \
29968             DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
29969             under the outer accessor's reference projection",
29970        );
29971
29972        // (2) Non-matching destination — the resolver's `filter(…)`
29973        // arm rejects a mismatched destination and falls through
29974        // to `DEFAULT_SERVICO_PORT` under the outer accessor's
29975        // reference projection.
29976        let mut spec = three_member_spec();
29977        if let Some(e) = spec.entrada.as_mut() {
29978            e.para = "cart".into();
29979            e.port = 9443;
29980        }
29981        assert_eq!(
29982            spec.port_for_destination("catalog"),
29983            DEFAULT_SERVICO_PORT,
29984            "the port-fallback resolver must fall through to \
29985             DEFAULT_SERVICO_PORT on a non-matching destination \
29986             under the outer accessor's reference projection",
29987        );
29988
29989        // (3) Matching destination — the resolver's `map_or(…)` arm
29990        // returns the `:entrada :port` value under the outer
29991        // accessor's reference projection.
29992        let mut spec = three_member_spec();
29993        if let Some(e) = spec.entrada.as_mut() {
29994            e.para = "cart".into();
29995            e.port = 9443;
29996        }
29997        assert_eq!(
29998            spec.port_for_destination("cart"),
29999            9443,
30000            "the port-fallback resolver must return the \
30001             `:entrada :port` value on a matching destination \
30002             under the outer accessor's reference projection",
30003        );
30004    }
30005
30006    #[test]
30007    fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
30008        // The canonical per-`:politicas` `:mtls-required` mTLS-
30009        // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
30010        // must return the `:politicas :mtls-required` typed bool
30011        // verbatim as an `Option<bool>`, byte-equal to the raw field
30012        // access across every value in the three-way accept-set —
30013        // `None` (cluster default applies), `Some(true)` (mTLS
30014        // handshake enforced — the sandboxing-by-default arm the
30015        // MeshPolicy's docstring names), `Some(false)` (handshake
30016        // skipped — the explicit debug-edge opt-out).
30017        //
30018        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
30019        // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
30020        // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
30021        // shape — first `Option<Copy-T>`-return accessor on the M3
30022        // mesh-slot family. Pins against a future silent detour that
30023        // re-derived the toggle from a peer axis (an accidental
30024        // `.circuit_breaker.is_some()` collapse that assumed mTLS on
30025        // whenever a breaker is set), a `None` → `Some(false)` cluster-
30026        // default projection (the canonical `Option<bool>` → `bool`
30027        // collapse footgun the surrounding `is_empty()` predicate
30028        // guards on the peer emptiness axis), or a `Some(true)` /
30029        // `Some(false)` variant swap that landed on one consumer
30030        // without the other.
30031        for required in [None, Some(true), Some(false)] {
30032            let p = MeshPolicy {
30033                mtls_required: required,
30034                ..MeshPolicy::default()
30035            };
30036            assert_eq!(
30037                p.mtls_required(),
30038                required,
30039                "MeshPolicy::mtls_required must return :politicas \
30040                 :mtls-required verbatim (got {:?}, expected {required:?})",
30041                p.mtls_required(),
30042            );
30043            assert_eq!(
30044                p.mtls_required(),
30045                p.mtls_required,
30046                "MeshPolicy::mtls_required must byte-equal the raw \
30047                 .mtls_required field access across every value in the \
30048                 three-way accept-set",
30049            );
30050        }
30051    }
30052
30053    #[test]
30054    fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
30055        // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
30056        // arm must key off [`MeshPolicy::mtls_required`], not the raw
30057        // `.mtls_required` field access. Structurally: toggling ONLY
30058        // the `mtls_required` slot on an otherwise-default MeshPolicy
30059        // must flip `is_empty()` from `true` (all-`None`) to `false`
30060        // (one axis carries a value); the flip must be observed for
30061        // both `Some(true)` and `Some(false)` since the emptiness
30062        // semantic reads "any axis carries a value" — not "any axis
30063        // carries a truthy value" — the same non-collapsing shape the
30064        // sibling M2 [`crate::LimitsSpec::is_empty`] /
30065        // [`crate::BehaviorSpec::is_empty`] predicates carry on their
30066        // peer `Option<T>`-typed slot surfaces.
30067        //
30068        // Pins against a future silent detour that re-derived the
30069        // emptiness predicate off a peer axis (an accidental
30070        // `.rate_limit.is_none()`-only chain that dropped the
30071        // `mtls_required` arm entirely), a `mtls_required == Some(_)`
30072        // collapse to a truthy-only check (which would silently
30073        // classify `Some(false)` as empty), or an accessor-side
30074        // detour that no longer names the substrate-primitive typed
30075        // dispatch (an accidental `self.mtls_required.unwrap_or(false)
30076        // == false` fallback in the accessor that would silently
30077        // classify both `None` and `Some(false)` as the same value).
30078        //
30079        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
30080        // (7cd2a28) accessor-composition pin on the sibling optional-
30081        // scalar axis — same "the emptiness / shape-gate predicate
30082        // must route through the substrate-primitive typed dispatch"
30083        // discipline extended onto the peer per-`:politicas` emptiness
30084        // predicate.
30085        let empty = MeshPolicy::default();
30086        assert!(
30087            empty.is_empty(),
30088            "MeshPolicy::default() must be is_empty() — every axis \
30089             defaults to None",
30090        );
30091        for required in [Some(true), Some(false)] {
30092            let p = MeshPolicy {
30093                mtls_required: required,
30094                ..MeshPolicy::default()
30095            };
30096            assert!(
30097                !p.is_empty(),
30098                "MeshPolicy::is_empty must return false when \
30099                 :mtls-required is {required:?} — the emptiness \
30100                 predicate reads \"any axis carries a value\", not \
30101                 \"any axis carries a truthy value\"",
30102            );
30103            assert_eq!(
30104                p.mtls_required().is_none(),
30105                p.is_empty(),
30106                "when :mtls-required is the only set axis, \
30107                 is_empty() must equal mtls_required().is_none() — \
30108                 the accessor and the emptiness predicate must \
30109                 route through the same substrate-primitive typed \
30110                 dispatch on the :mtls-required arm",
30111            );
30112        }
30113    }
30114
30115    #[test]
30116    fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
30117        // The by-copy pin: [`MeshPolicy::mtls_required`] returns
30118        // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
30119        // accessor must return by value, not by reference. Peer of the
30120        // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
30121        // borrow-invariant pin on the sibling `Option<String>` slot,
30122        // but extended onto the peer `Option<bool>` copy-invariant
30123        // shape — the accessor's returned `Option<bool>` must outlive
30124        // `&self` (multiple calls must return equal values from a
30125        // dropped-`&self` copy, since the returned Option carries no
30126        // borrow), and calling the accessor twice on the same
30127        // MeshPolicy must yield the same `Option<bool>` verbatim
30128        // (idempotent, no side effects on `&self`).
30129        //
30130        // Pins against a future silent detour that returned
30131        // `Option<&bool>` (which would type-check but silently break
30132        // every downstream caller — [`single_field_overlay`]'s first
30133        // parameter is `Option<T: Clone>`, and `&bool` would fold to a
30134        // detached copy at the call site), an accidental
30135        // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
30136        // would also type-check but return `Option<&bool>`), or a
30137        // one-arm-only accessor that reads `Some(*b)` in the Some arm
30138        // but reads a fresh Default::default() in the None arm.
30139        for required in [None, Some(true), Some(false)] {
30140            let p = MeshPolicy {
30141                mtls_required: required,
30142                ..MeshPolicy::default()
30143            };
30144            let first = p.mtls_required();
30145            let second = p.mtls_required();
30146            assert_eq!(
30147                first, second,
30148                "MeshPolicy::mtls_required must be idempotent — two \
30149                 successive calls on the same &self must return the \
30150                 same Option<bool>",
30151            );
30152            assert_eq!(
30153                first, required,
30154                "MeshPolicy::mtls_required must return :politicas \
30155                 :mtls-required verbatim by copy — got {first:?}, \
30156                 expected {required:?}",
30157            );
30158        }
30159    }
30160
30161    #[test]
30162    fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
30163        // The canonical per-`:politicas` `:retries` transient-failure-
30164        // retry-budget scalar pin: [`MeshPolicy::retries`] must return
30165        // the `:politicas :retries` typed `u32` verbatim as an
30166        // `Option<u32>`, byte-equal to the raw field access across every
30167        // representative value in the accept-set — `None` (cluster
30168        // default applies — typically "no retries beyond a single
30169        // dispatch attempt" the caixa-mesh `retry_overlay` builder
30170        // documents), `Some(1)` (the lower boundary of the
30171        // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
30172        // `AplicacaoSpec::validate_politicas` gate carves out on the
30173        // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
30174        // (the upper boundary the same gate carves out on the sibling
30175        // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
30176        // past-the-guard sentinel that pins the accessor doesn't perform
30177        // a silent bounds-collapse at the return path).
30178        //
30179        // Sibling of the peer per-`:politicas`
30180        // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
30181        // sibling `Option<Copy-T>` optional-scalar axis, extended to the
30182        // peer per-`:politicas` `Option<u32>` shape — second
30183        // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
30184        // Pins against a future silent detour that re-derived the retry
30185        // cap from a peer axis (an accidental `.circuit_breaker
30186        // .as_ref().map(|b| b.max_failures)` collapse that read the
30187        // breaker's max-failure count as a retry budget), a
30188        // `None → Some(0)` cluster-default projection (which would
30189        // silently re-introduce the `PolicyRetriesZero` refusal case at
30190        // the emit boundary), or a bounds-collapsing accessor that
30191        // clamped the return through `POLICY_RETRIES_MAX` (the
30192        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
30193        // must ship the raw slot verbatim so a validate-time gate
30194        // regression surfaces at the emit boundary rather than being
30195        // silently absorbed).
30196        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
30197            let p = MeshPolicy {
30198                retries,
30199                ..MeshPolicy::default()
30200            };
30201            assert_eq!(
30202                p.retries(),
30203                retries,
30204                "MeshPolicy::retries must return :politicas :retries \
30205                 verbatim (got {:?}, expected {retries:?})",
30206                p.retries(),
30207            );
30208            assert_eq!(
30209                p.retries(),
30210                p.retries,
30211                "MeshPolicy::retries must byte-equal the raw .retries \
30212                 field access across every value in the accept-set",
30213            );
30214        }
30215    }
30216
30217    #[test]
30218    fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
30219        // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
30220        // must key off [`MeshPolicy::retries`], not the raw `.retries`
30221        // field access. Structurally: toggling ONLY the `retries` slot
30222        // on an otherwise-default MeshPolicy must flip `is_empty()`
30223        // from `true` (all-`None`) to `false` (one axis carries a
30224        // value); the flip must be observed for every value in the
30225        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
30226        // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
30227        // the emptiness semantic reads "any axis carries a value" —
30228        // not "any axis carries a value the validate gate accepts" —
30229        // the same non-collapsing shape the peer M2
30230        // [`crate::LimitsSpec::is_empty`] /
30231        // [`crate::BehaviorSpec::is_empty`] predicates carry.
30232        //
30233        // Pins against a future silent detour that re-derived the
30234        // emptiness predicate off a peer axis (an accidental
30235        // `.rate_limit.is_none()`-only chain that dropped the
30236        // `retries` arm entirely), a `retries == Some(_)` collapse
30237        // that key-off a validate-gate-clamped bounds check (which
30238        // would silently classify a past-the-guard `Some(u32::MAX)`
30239        // as empty because it fails the `1..=POLICY_RETRIES_MAX`
30240        // check), or an accessor-side detour that no longer names the
30241        // substrate-primitive typed dispatch.
30242        //
30243        // Sibling of the peer per-`:politicas`
30244        // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
30245        // pin on the sibling `Option<Copy-T>` optional-scalar axis —
30246        // same "the emptiness predicate must route through the
30247        // substrate-primitive typed dispatch" discipline extended onto
30248        // the peer per-`:politicas` `Option<u32>` axis.
30249        let empty = MeshPolicy::default();
30250        assert!(
30251            empty.is_empty(),
30252            "MeshPolicy::default() must be is_empty() — every axis \
30253             defaults to None",
30254        );
30255        for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
30256            let p = MeshPolicy {
30257                retries,
30258                ..MeshPolicy::default()
30259            };
30260            assert!(
30261                !p.is_empty(),
30262                "MeshPolicy::is_empty must return false when \
30263                 :retries is {retries:?} — the emptiness \
30264                 predicate reads \"any axis carries a value\", not \
30265                 \"any axis carries a value the validate gate \
30266                 accepts\"",
30267            );
30268            assert_eq!(
30269                p.retries().is_none(),
30270                p.is_empty(),
30271                "when :retries is the only set axis, is_empty() \
30272                 must equal retries().is_none() — the accessor and \
30273                 the emptiness predicate must route through the same \
30274                 substrate-primitive typed dispatch on the :retries \
30275                 arm",
30276            );
30277        }
30278    }
30279
30280    #[test]
30281    fn mesh_policy_retries_projects_option_u32_by_copy() {
30282        // The by-copy pin: [`MeshPolicy::retries`] returns
30283        // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
30284        // accessor must return by value, not by reference. Sibling of
30285        // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
30286        // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
30287        // extended onto the sibling `Option<u32>` copy-invariant
30288        // shape — the accessor's returned `Option<u32>` must outlive
30289        // `&self` (multiple calls must return equal values from a
30290        // dropped-`&self` copy, since the returned Option carries no
30291        // borrow), and calling the accessor twice on the same
30292        // MeshPolicy must yield the same `Option<u32>` verbatim
30293        // (idempotent, no side effects on `&self`).
30294        //
30295        // Pins against a future silent detour that returned
30296        // `Option<&u32>` (which would type-check but silently break
30297        // every downstream caller — [`crate::render::single_field_overlay`]'s
30298        // first parameter is `Option<T: Clone>`, and `&u32` would
30299        // fold to a detached copy at the call site), an accidental
30300        // `Option::as_ref()` projection (`self.retries.as_ref()` would
30301        // also type-check but return `Option<&u32>`), or a one-arm-
30302        // only accessor that reads `Some(*n)` in the Some arm but
30303        // reads a fresh `Default::default()` (`0_u32`) in the None
30304        // arm.
30305        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
30306            let p = MeshPolicy {
30307                retries,
30308                ..MeshPolicy::default()
30309            };
30310            let first = p.retries();
30311            let second = p.retries();
30312            assert_eq!(
30313                first, second,
30314                "MeshPolicy::retries must be idempotent — two \
30315                 successive calls on the same &self must return the \
30316                 same Option<u32>",
30317            );
30318            assert_eq!(
30319                first, retries,
30320                "MeshPolicy::retries must return :politicas :retries \
30321                 verbatim by copy — got {first:?}, expected {retries:?}",
30322            );
30323        }
30324    }
30325
30326    #[test]
30327    fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
30328        // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
30329        // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
30330        // return the `:politicas :timeout` typed [`Duration`] verbatim
30331        // as an `Option<Duration>`, byte-equal to the raw field access
30332        // across every representative value in the accept-set — `None`
30333        // (cluster default applies — typically the gateway class's
30334        // implementation-side per-request wall-clock cap the caixa-mesh
30335        // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
30336        // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
30337        // set the surrounding `AplicacaoSpec::validate_politicas` gate
30338        // carves out on the sibling `PolicyTimeoutZero` /
30339        // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
30340        // (the upper boundary the same gate carves out on the sibling
30341        // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
30342        // (a past-the-guard sentinel that pins the accessor doesn't
30343        // perform a silent bounds-collapse into `None` on the zero-
30344        // Duration arm — validate rejects zero but the accessor must
30345        // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
30346        // past-the-guard sentinel that pins the accessor doesn't
30347        // perform a silent bounds-collapse at the return path).
30348        //
30349        // Sibling of the peer per-`:politicas`
30350        // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
30351        // `Option<u32>` optional-scalar axis and the peer per-
30352        // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
30353        // pin on the sibling `Option<bool>` optional-scalar axis,
30354        // extended onto the peer per-`:politicas` `Option<Duration>`
30355        // shape — third `Option<Copy-T>`-return accessor on the M3
30356        // mesh-slot family. Pins against a future silent detour that
30357        // re-derived the per-call cap from a peer axis (an accidental
30358        // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
30359        // read the breaker's rolling-window duration as a per-call
30360        // deadline), a `None → Some(Duration::MAX)` cluster-default
30361        // projection (which would silently re-introduce the
30362        // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
30363        // blocking" arm at the emit boundary), or a bounds-collapsing
30364        // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
30365        // (the `AplicacaoSpec::validate` gate owns the bounds; the
30366        // accessor must ship the raw slot verbatim so a validate-time
30367        // gate regression surfaces at the emit boundary rather than
30368        // being silently absorbed).
30369        for timeout in [
30370            None,
30371            Some(Duration::from_millis(1)),
30372            Some(POLICY_TIMEOUT_MAX),
30373            Some(Duration::ZERO),
30374            Some(Duration::MAX),
30375        ] {
30376            let p = MeshPolicy {
30377                timeout,
30378                ..MeshPolicy::default()
30379            };
30380            assert_eq!(
30381                p.timeout(),
30382                timeout,
30383                "MeshPolicy::timeout must return :politicas :timeout \
30384                 verbatim (got {:?}, expected {timeout:?})",
30385                p.timeout(),
30386            );
30387            assert_eq!(
30388                p.timeout(),
30389                p.timeout,
30390                "MeshPolicy::timeout must byte-equal the raw .timeout \
30391                 field access across every value in the accept-set",
30392            );
30393        }
30394    }
30395
30396    #[test]
30397    fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
30398        // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
30399        // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
30400        // field access. Structurally: toggling ONLY the `timeout` slot
30401        // on an otherwise-default MeshPolicy must flip `is_empty()`
30402        // from `true` (all-`None`) to `false` (one axis carries a
30403        // value); the flip must be observed for every value in the
30404        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
30405        // gate accepts (`Some(Duration::from_millis(1))`,
30406        // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
30407        // reads "any axis carries a value" — not "any axis carries a
30408        // value the validate gate accepts" — the same non-collapsing
30409        // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
30410        // [`crate::BehaviorSpec::is_empty`] predicates carry.
30411        //
30412        // Pins against a future silent detour that re-derived the
30413        // emptiness predicate off a peer axis (an accidental
30414        // `.rate_limit.is_none()`-only chain that dropped the
30415        // `timeout` arm entirely), a `timeout == Some(_)` collapse
30416        // that key-off a validate-gate-clamped bounds check (which
30417        // would silently classify a past-the-guard `Some(Duration::MAX)`
30418        // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
30419        // check), or an accessor-side detour that no longer names the
30420        // substrate-primitive typed dispatch.
30421        //
30422        // Sibling of the peer per-`:politicas`
30423        // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
30424        // the sibling `Option<u32>` optional-scalar axis and the peer
30425        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
30426        // accessor-composition pin on the sibling `Option<bool>`
30427        // optional-scalar axis — same "the emptiness predicate must
30428        // route through the substrate-primitive typed dispatch"
30429        // discipline extended onto the peer per-`:politicas`
30430        // `Option<Duration>` axis.
30431        let empty = MeshPolicy::default();
30432        assert!(
30433            empty.is_empty(),
30434            "MeshPolicy::default() must be is_empty() — every axis \
30435             defaults to None",
30436        );
30437        for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
30438            let p = MeshPolicy {
30439                timeout,
30440                ..MeshPolicy::default()
30441            };
30442            assert!(
30443                !p.is_empty(),
30444                "MeshPolicy::is_empty must return false when \
30445                 :timeout is {timeout:?} — the emptiness \
30446                 predicate reads \"any axis carries a value\", not \
30447                 \"any axis carries a value the validate gate \
30448                 accepts\"",
30449            );
30450            assert_eq!(
30451                p.timeout().is_none(),
30452                p.is_empty(),
30453                "when :timeout is the only set axis, is_empty() \
30454                 must equal timeout().is_none() — the accessor and \
30455                 the emptiness predicate must route through the same \
30456                 substrate-primitive typed dispatch on the :timeout \
30457                 arm",
30458            );
30459        }
30460    }
30461
30462    #[test]
30463    fn mesh_policy_timeout_projects_option_duration_by_copy() {
30464        // The by-copy pin: [`MeshPolicy::timeout`] returns
30465        // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
30466        // and the accessor must return by value, not by reference.
30467        // Sibling of the peer per-`:politicas`
30468        // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
30469        // sibling `Option<u32>` optional-scalar axis and the peer
30470        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
30471        // by-copy pin on the sibling `Option<bool>` optional-scalar
30472        // axis, extended onto the peer per-`:politicas`
30473        // `Option<Duration>` copy-invariant shape — the accessor's
30474        // returned `Option<Duration>` must outlive `&self` (multiple
30475        // calls must return equal values from a dropped-`&self`
30476        // copy, since the returned Option carries no borrow), and
30477        // calling the accessor twice on the same MeshPolicy must
30478        // yield the same `Option<Duration>` verbatim (idempotent, no
30479        // side effects on `&self`).
30480        //
30481        // Pins against a future silent detour that returned
30482        // `Option<&Duration>` (which would type-check but silently
30483        // break every downstream caller — [`crate::render::single_field_overlay`]'s
30484        // first parameter is `Option<T: Clone>`, and `&Duration`
30485        // would fold to a detached copy at the call site), an
30486        // accidental `Option::as_ref()` projection
30487        // (`self.timeout.as_ref()` would also type-check but return
30488        // `Option<&Duration>`), or a one-arm-only accessor that
30489        // reads `Some(*d)` in the Some arm but reads a fresh
30490        // `Default::default()` (`Duration::ZERO`) in the None arm
30491        // (which would silently re-classify every unset `:timeout`
30492        // as the `PolicyTimeoutZero`-refused zero-Duration value at
30493        // the accessor boundary).
30494        for timeout in [
30495            None,
30496            Some(Duration::from_millis(1)),
30497            Some(POLICY_TIMEOUT_MAX),
30498            Some(Duration::ZERO),
30499            Some(Duration::MAX),
30500        ] {
30501            let p = MeshPolicy {
30502                timeout,
30503                ..MeshPolicy::default()
30504            };
30505            let first = p.timeout();
30506            let second = p.timeout();
30507            assert_eq!(
30508                first, second,
30509                "MeshPolicy::timeout must be idempotent — two \
30510                 successive calls on the same &self must return the \
30511                 same Option<Duration>",
30512            );
30513            assert_eq!(
30514                first, timeout,
30515                "MeshPolicy::timeout must return :politicas :timeout \
30516                 verbatim by copy — got {first:?}, expected {timeout:?}",
30517            );
30518        }
30519    }
30520
30521    #[test]
30522    fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
30523        // The canonical per-`:politicas` `:rate-limit` Envoy-
30524        // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
30525        // [`MeshPolicy::rate_limit`] must return the `:politicas
30526        // :rate-limit` typed [`RateLimit`] verbatim as an
30527        // `Option<RateLimit>`, byte-equal to the raw field access
30528        // across every representative value in the accept-set — `None`
30529        // (cluster default applies — no per-Aplicacao rate declaration,
30530        // the gateway-class per-listener default arm the future caixa-
30531        // mesh `local_rate_limit_overlay` emitter documents),
30532        // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
30533        // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
30534        // accept-set the surrounding
30535        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
30536        // sibling `PolicyRateLimitZero` refusal, paired with the
30537        // canonical-window "1 second" arm of the three-unit
30538        // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
30539        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
30540        // (the upper boundary the same gate carves out on the sibling
30541        // `PolicyRateLimitExceedsCap` refusal, paired with the
30542        // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
30543        // (a past-the-guard sentinel that pins the accessor doesn't
30544        // perform a silent bounds-collapse into `None` on the
30545        // zero-rate/zero-window arm — validate rejects zero but the
30546        // accessor must ship the raw slot verbatim so a validate-time
30547        // gate regression surfaces at the emit boundary rather than
30548        // being silently absorbed), and
30549        // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
30550        // (a past-the-guard sentinel that pins the accessor doesn't
30551        // perform a silent bounds-collapse at the return path).
30552        //
30553        // First `Option<Copy-composite-T>`-return accessor pin on the
30554        // M3 mesh-slot family (peer of the sibling per-`:politicas`
30555        // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
30556        // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
30557        // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
30558        // Copy accessor pins, extended onto the peer per-`:politicas`
30559        // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
30560        // and the accessor returns by value). Pins against a future
30561        // silent detour that re-derived the rate declaration from a
30562        // peer axis (an accidental
30563        // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
30564        // collapse that read the breaker's trip threshold + rolling
30565        // window as a rate declaration), a `None → Some(default())`
30566        // cluster-default projection (which would silently re-
30567        // introduce a "cluster default is 0/s" arm the emit boundary
30568        // would take as "declared but inert" — the canonical
30569        // declared-but-inert footgun the sibling
30570        // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
30571        // amplification-shape axis), a bounds-collapsing accessor
30572        // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
30573        // clamped `rl.window` through [`is_canonical_rate_limit_window`]
30574        // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
30575        // accessor must ship the raw slot verbatim), or a
30576        // by-reference detour (`Option<&RateLimit>`) that broke every
30577        // downstream consumer keying off `Option<RateLimit>` by-copy.
30578        for rl in [
30579            None,
30580            Some(RateLimit {
30581                rate: 1,
30582                window: Duration::from_secs(1),
30583            }),
30584            Some(RateLimit {
30585                rate: POLICY_RATE_LIMIT_MAX,
30586                window: Duration::from_secs(3600),
30587            }),
30588            Some(RateLimit {
30589                rate: 0,
30590                window: Duration::ZERO,
30591            }),
30592            Some(RateLimit {
30593                rate: u32::MAX,
30594                window: Duration::MAX,
30595            }),
30596        ] {
30597            let p = MeshPolicy {
30598                rate_limit: rl,
30599                ..MeshPolicy::default()
30600            };
30601            assert_eq!(
30602                p.rate_limit(),
30603                rl,
30604                "MeshPolicy::rate_limit must return :politicas :rate-limit \
30605                 verbatim (got {:?}, expected {rl:?})",
30606                p.rate_limit(),
30607            );
30608            assert_eq!(
30609                p.rate_limit(),
30610                p.rate_limit,
30611                "MeshPolicy::rate_limit must byte-equal the raw \
30612                 .rate_limit field access across every value in the \
30613                 accept-set",
30614            );
30615        }
30616    }
30617
30618    #[test]
30619    fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
30620        // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
30621        // must key off [`MeshPolicy::rate_limit`], not the raw
30622        // `.rate_limit` field access. Structurally: toggling ONLY the
30623        // `rate_limit` slot on an otherwise-default MeshPolicy must
30624        // flip `is_empty()` from `true` (all-`None`) to `false` (one
30625        // axis carries a value); the flip must be observed for every
30626        // representative value in the accept-set the surrounding
30627        // [`AplicacaoSpec::validate_politicas`] gate accepts
30628        // (`Some(RateLimit { rate: 1, window: 1s })`,
30629        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
30630        // since the emptiness semantic reads "any axis carries a
30631        // value" — not "any axis carries a value the validate gate
30632        // accepts" — the same non-collapsing shape the peer M2
30633        // [`crate::LimitsSpec::is_empty`] /
30634        // [`crate::BehaviorSpec::is_empty`] predicates carry.
30635        //
30636        // Pins against a future silent detour that re-derived the
30637        // emptiness predicate off a peer axis (an accidental
30638        // `.timeout.is_none()`-only chain that dropped the
30639        // `rate_limit` arm entirely — the last unlifted inline field
30640        // access on `is_empty` before this lift), a `rate_limit ==
30641        // Some(_)` collapse that key-off a validate-gate-clamped
30642        // bounds check (which would silently classify a past-the-
30643        // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
30644        // because it fails the value-shape gate), or an accessor-
30645        // side detour that no longer names the substrate-primitive
30646        // typed dispatch.
30647        //
30648        // Fourth "the emptiness predicate must route through the
30649        // substrate-primitive typed dispatch" composition pin on the
30650        // M3 mesh-slot family — closes the last unlifted composition
30651        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
30652        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
30653        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
30654        // 7073d0f is_empty-composition pins on the sibling primitive-
30655        // Copy axes, extended onto the peer per-`:politicas`
30656        // composite-Copy `Option<RateLimit>` axis).
30657        let empty = MeshPolicy::default();
30658        assert!(
30659            empty.is_empty(),
30660            "MeshPolicy::default() must be is_empty() — every axis \
30661             defaults to None",
30662        );
30663        for rl in [
30664            RateLimit {
30665                rate: 1,
30666                window: Duration::from_secs(1),
30667            },
30668            RateLimit {
30669                rate: POLICY_RATE_LIMIT_MAX,
30670                window: Duration::from_secs(3600),
30671            },
30672        ] {
30673            let p = MeshPolicy {
30674                rate_limit: Some(rl),
30675                ..MeshPolicy::default()
30676            };
30677            assert!(
30678                !p.is_empty(),
30679                "MeshPolicy::is_empty must return false when \
30680                 :rate-limit is {rl:?} — the emptiness predicate \
30681                 reads \"any axis carries a value\", not \"any axis \
30682                 carries a value the validate gate accepts\"",
30683            );
30684            assert_eq!(
30685                p.rate_limit().is_none(),
30686                p.is_empty(),
30687                "when :rate-limit is the only set axis, is_empty() \
30688                 must equal rate_limit().is_none() — the accessor \
30689                 and the emptiness predicate must route through the \
30690                 same substrate-primitive typed dispatch on the \
30691                 :rate-limit arm",
30692            );
30693        }
30694    }
30695
30696    #[test]
30697    fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
30698        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
30699        // `:rate-limit` value-shape gate must key off
30700        // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
30701        // field bind. Structurally: a `MeshPolicy` whose only set
30702        // axis is a `Some(RateLimit { rate: 0, .. })` must surface
30703        // the `PolicyRateLimitZero` refusal exactly, and the same
30704        // MeshPolicy with the rate at the canonical lower boundary
30705        // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
30706        // The pair jointly pins the accessor + validate-gate
30707        // composition: any future silent detour that had the accessor
30708        // omit the `Some(RateLimit { rate: 0, .. })` arm (a
30709        // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
30710        // silently absorb the `PolicyRateLimitZero` refusal at the
30711        // accessor boundary — the composition pin catches that at
30712        // caixa-core build time.
30713        //
30714        // Sibling of the peer [`validate_politicas`]
30715        // `:mtls-required` / `:retries` / `:timeout` composition pins
30716        // on the sibling primitive-Copy optional-scalar axes — same
30717        // "the validate / shape-gate predicate must route through the
30718        // substrate-primitive typed dispatch" discipline extended
30719        // onto the peer per-`:politicas` composite-Copy
30720        // `Option<RateLimit>` axis. Second composition-with-accessor
30721        // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
30722        // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
30723        let mut spec = three_member_spec();
30724        spec.politicas = MeshPolicy {
30725            rate_limit: Some(RateLimit {
30726                rate: 0,
30727                window: Duration::from_secs(1),
30728            }),
30729            ..MeshPolicy::default()
30730        };
30731        assert!(
30732            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
30733            "validate_politicas must reject rate == 0 with \
30734             PolicyRateLimitZero — the accessor and the validate gate \
30735             must route through the same substrate-primitive typed \
30736             dispatch on the :rate-limit zero-floor arm",
30737        );
30738        spec.politicas = MeshPolicy {
30739            rate_limit: Some(RateLimit {
30740                rate: 1,
30741                window: Duration::from_secs(1),
30742            }),
30743            ..MeshPolicy::default()
30744        };
30745        assert!(
30746            spec.validate().is_ok(),
30747            "validate_politicas must accept rate == 1 (the canonical \
30748             lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
30749             set) with a canonical 1s window",
30750        );
30751    }
30752
30753    #[test]
30754    fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
30755        // The canonical per-`:politicas` `:circuit-breaker` Envoy-
30756        // `outlier_detection`-mesh consecutive-failure-ejection scalar
30757        // pin: [`MeshPolicy::circuit_breaker`] must return the
30758        // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
30759        // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
30760        // raw field access across every representative value in the
30761        // accept-set — `None` (cluster default applies — no
30762        // per-Aplicacao breaker declaration, the gateway-class per-
30763        // listener default arm the future caixa-mesh
30764        // `outlier_detection_overlay` emitter documents),
30765        // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
30766        // (the lower boundary of the accept-set the surrounding
30767        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
30768        // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
30769        // refusals),
30770        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
30771        // (the upper boundary the same gate carves out on the sibling
30772        // `PolicyBreakerMaxFailuresExceedsCap` /
30773        // `PolicyBreakerWindowExceedsCap` refusals),
30774        // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
30775        // (a past-the-guard sentinel that pins the accessor doesn't
30776        // perform a silent bounds-collapse into `None` on the
30777        // zero-failures/zero-window arm — validate rejects zero but
30778        // the accessor must ship the raw slot verbatim so a validate-
30779        // time gate regression surfaces at the emit boundary rather
30780        // than being silently absorbed), and
30781        // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
30782        // (a past-the-guard sentinel that pins the accessor doesn't
30783        // perform a silent bounds-collapse at the return path).
30784        //
30785        // Second `Option<Copy-composite-T>`-return accessor pin on the
30786        // M3 mesh-slot family (peer of the sibling per-`:politicas`
30787        // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
30788        // composite-Copy accessor pin, and of the sibling per-
30789        // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
30790        // [`MeshPolicy::retries`] bdfb399 /
30791        // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
30792        // accessor pins). Pins against a future silent detour that
30793        // re-derived the breaker declaration from a peer axis (an
30794        // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
30795        // collapse that read the rate-limit's bucket capacity + refill
30796        // period as a breaker declaration), a `None → Some(default())`
30797        // cluster-default projection (which would silently re-
30798        // introduce the `PolicyBreakerZeroFailures` /
30799        // `PolicyBreakerZeroWindow` refusal cases at the emit
30800        // boundary), a bounds-collapsing accessor that clamped
30801        // `cb.max_failures` through
30802        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
30803        // through [`POLICY_BREAKER_WINDOW_MAX`] (the
30804        // [`AplicacaoSpec::validate`] gate owns the bounds; the
30805        // accessor must ship the raw slot verbatim), or a
30806        // by-reference detour (`Option<&CircuitBreaker>`) that broke
30807        // every downstream consumer keying off `Option<CircuitBreaker>`
30808        // by-copy.
30809        for cb in [
30810            None,
30811            Some(CircuitBreaker {
30812                max_failures: 1,
30813                window: Duration::from_millis(1),
30814            }),
30815            Some(CircuitBreaker {
30816                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
30817                window: POLICY_BREAKER_WINDOW_MAX,
30818            }),
30819            Some(CircuitBreaker {
30820                max_failures: 0,
30821                window: Duration::ZERO,
30822            }),
30823            Some(CircuitBreaker {
30824                max_failures: u32::MAX,
30825                window: Duration::MAX,
30826            }),
30827        ] {
30828            let p = MeshPolicy {
30829                circuit_breaker: cb,
30830                ..MeshPolicy::default()
30831            };
30832            assert_eq!(
30833                p.circuit_breaker(),
30834                cb,
30835                "MeshPolicy::circuit_breaker must return :politicas \
30836                 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
30837                p.circuit_breaker(),
30838            );
30839            assert_eq!(
30840                p.circuit_breaker(),
30841                p.circuit_breaker,
30842                "MeshPolicy::circuit_breaker must byte-equal the raw \
30843                 .circuit_breaker field access across every value in \
30844                 the accept-set",
30845            );
30846        }
30847    }
30848
30849    #[test]
30850    fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
30851        // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
30852        // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
30853        // `.circuit_breaker` field access. Structurally: toggling ONLY
30854        // the `circuit_breaker` slot on an otherwise-default MeshPolicy
30855        // must flip `is_empty()` from `true` (all-`None`) to `false`
30856        // (one axis carries a value); the flip must be observed for
30857        // every representative value in the accept-set the surrounding
30858        // [`AplicacaoSpec::validate_politicas`] gate accepts
30859        // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
30860        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
30861        // since the emptiness semantic reads "any axis carries a
30862        // value" — not "any axis carries a value the validate gate
30863        // accepts" — the same non-collapsing shape the peer M2
30864        // [`crate::LimitsSpec::is_empty`] /
30865        // [`crate::BehaviorSpec::is_empty`] predicates carry.
30866        //
30867        // Pins against a future silent detour that re-derived the
30868        // emptiness predicate off a peer axis (an accidental
30869        // `.rate_limit.is_none()`-only chain that dropped the
30870        // `circuit_breaker` arm entirely — the last unlifted inline
30871        // field access on `is_empty` before this lift), a
30872        // `circuit_breaker == Some(_)` collapse that key-off a
30873        // validate-gate-clamped bounds check (which would silently
30874        // classify a past-the-guard `Some(CircuitBreaker { max_failures:
30875        // 0, window: 0s })` as empty because it fails the value-shape
30876        // gate), or an accessor-side detour that no longer names the
30877        // substrate-primitive typed dispatch.
30878        //
30879        // Fifth "the emptiness predicate must route through the
30880        // substrate-primitive typed dispatch" composition pin on the
30881        // M3 mesh-slot family — closes the last unlifted composition
30882        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
30883        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
30884        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
30885        // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
30886        // composition pins on the sibling primitive-Copy + composite-
30887        // Copy axes, extended onto the peer per-`:politicas`
30888        // composite-Copy `Option<CircuitBreaker>` axis).
30889        let empty = MeshPolicy::default();
30890        assert!(
30891            empty.is_empty(),
30892            "MeshPolicy::default() must be is_empty() — every axis \
30893             defaults to None",
30894        );
30895        for cb in [
30896            CircuitBreaker {
30897                max_failures: 1,
30898                window: Duration::from_millis(1),
30899            },
30900            CircuitBreaker {
30901                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
30902                window: POLICY_BREAKER_WINDOW_MAX,
30903            },
30904        ] {
30905            let p = MeshPolicy {
30906                circuit_breaker: Some(cb),
30907                ..MeshPolicy::default()
30908            };
30909            assert!(
30910                !p.is_empty(),
30911                "MeshPolicy::is_empty must return false when \
30912                 :circuit-breaker is {cb:?} — the emptiness predicate \
30913                 reads \"any axis carries a value\", not \"any axis \
30914                 carries a value the validate gate accepts\"",
30915            );
30916            assert_eq!(
30917                p.circuit_breaker().is_none(),
30918                p.is_empty(),
30919                "when :circuit-breaker is the only set axis, \
30920                 is_empty() must equal circuit_breaker().is_none() — \
30921                 the accessor and the emptiness predicate must route \
30922                 through the same substrate-primitive typed dispatch \
30923                 on the :circuit-breaker arm",
30924            );
30925        }
30926    }
30927
30928    #[test]
30929    fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
30930        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
30931        // `:circuit-breaker` value-shape gate must key off
30932        // [`MeshPolicy::circuit_breaker`], not the raw
30933        // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
30934        // whose only set axis is a `Some(CircuitBreaker { max_failures:
30935        // 0, .. })` must surface the `PolicyBreakerZeroFailures`
30936        // refusal exactly, and the same MeshPolicy with the breaker at
30937        // the canonical lower boundary
30938        // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
30939        // pass validate. The pair jointly pins the accessor +
30940        // validate-gate composition: any future silent detour that had
30941        // the accessor omit the `Some(CircuitBreaker { max_failures:
30942        // 0, .. })` arm (a
30943        // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
30944        // collapse) would silently absorb the
30945        // `PolicyBreakerZeroFailures` refusal at the accessor
30946        // boundary — the composition pin catches that at caixa-core
30947        // build time.
30948        //
30949        // Sibling of the peer [`validate_politicas`]
30950        // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
30951        // composition pins on the sibling primitive-Copy + composite-
30952        // Copy optional-scalar axes — same "the validate / shape-gate
30953        // predicate must route through the substrate-primitive typed
30954        // dispatch" discipline extended onto the peer per-`:politicas`
30955        // composite-Copy `Option<CircuitBreaker>` axis. Second
30956        // composition-with-accessor pin on the M3 mesh-slot
30957        // `Option<CircuitBreaker>` arm alongside the
30958        // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
30959        let mut spec = three_member_spec();
30960        spec.politicas = MeshPolicy {
30961            circuit_breaker: Some(CircuitBreaker {
30962                max_failures: 0,
30963                window: Duration::from_millis(1),
30964            }),
30965            ..MeshPolicy::default()
30966        };
30967        assert!(
30968            matches!(
30969                spec.validate(),
30970                Err(AplicacaoError::PolicyBreakerZeroFailures)
30971            ),
30972            "validate_politicas must reject max_failures == 0 with \
30973             PolicyBreakerZeroFailures — the accessor and the validate \
30974             gate must route through the same substrate-primitive \
30975             typed dispatch on the :circuit-breaker zero-floor arm",
30976        );
30977        spec.politicas = MeshPolicy {
30978            circuit_breaker: Some(CircuitBreaker {
30979                max_failures: 1,
30980                window: Duration::from_millis(1),
30981            }),
30982            ..MeshPolicy::default()
30983        };
30984        assert!(
30985            spec.validate().is_ok(),
30986            "validate_politicas must accept a CircuitBreaker at the \
30987             canonical lower boundary (max_failures = 1, window = \
30988             1ms) — the accessor and the validate gate must route \
30989             through the same substrate-primitive typed dispatch on \
30990             the :circuit-breaker arm",
30991        );
30992    }
30993
30994    #[test]
30995    fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
30996        // The canonical per-`:politicas :circuit-breaker` `:max-failures`
30997        // Envoy-outlier-detection trip-threshold scalar pin:
30998        // [`CircuitBreaker::max_failures`] must return the
30999        // `:politicas :circuit-breaker :max-failures` typed `u32`
31000        // verbatim, byte-equal to the raw field access across every
31001        // representative value in the accept-set — `1` (the lower
31002        // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
31003        // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
31004        // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
31005        // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
31006        // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
31007        // refusal), `0` (a past-the-guard sentinel that pins the accessor
31008        // doesn't perform a silent bounds-collapse into `1` on the zero
31009        // arm — validate rejects zero but the accessor must ship the
31010        // raw slot verbatim so a validate-time gate regression surfaces
31011        // at the emit boundary rather than being silently absorbed),
31012        // `u32::MAX` (a past-the-guard sentinel that pins the accessor
31013        // doesn't perform a silent bounds-collapse through
31014        // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
31015        //
31016        // First sub-struct required-scalar accessor pin on the M3
31017        // mesh-slot family — sibling in shape to the peer per-`:membros`
31018        // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
31019        // (a40b0e3) required-`String`-carry accessor pins and the peer
31020        // per-`:contratos` [`WitContract::source`] /
31021        // [`WitContract::destination`] (7f0fd43) required-`String`-carry
31022        // accessor pins, extended onto the peer per-`CircuitBreaker`
31023        // required-`u32` scalar-value axis. Pins against a future silent
31024        // detour that re-derived the trip threshold from a peer axis (an
31025        // accidental `self.window.as_secs() as u32` collapse that read
31026        // the breaker's rolling-window duration as a failure count), a
31027        // `0 → 1` cluster-default projection (which would silently absorb
31028        // the `PolicyBreakerZeroFailures` refusal case at the accessor
31029        // boundary), or a bounds-collapsing accessor that clamped the
31030        // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
31031        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
31032        // must ship the raw slot verbatim).
31033        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
31034            let cb = CircuitBreaker {
31035                max_failures,
31036                window: Duration::from_secs(60),
31037            };
31038            assert_eq!(
31039                cb.max_failures(),
31040                max_failures,
31041                "CircuitBreaker::max_failures must return :politicas \
31042                 :circuit-breaker :max-failures verbatim (got {}, \
31043                 expected {max_failures})",
31044                cb.max_failures(),
31045            );
31046            assert_eq!(
31047                cb.max_failures(),
31048                cb.max_failures,
31049                "CircuitBreaker::max_failures must byte-equal the raw \
31050                 .max_failures field access across every value in the \
31051                 u32 accept-set",
31052            );
31053        }
31054    }
31055
31056    #[test]
31057    fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
31058        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
31059        // `:circuit-breaker :max-failures` zero-floor arm must key off
31060        // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
31061        // field access. Structurally: a `CircuitBreaker { max_failures:
31062        // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
31063        // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
31064        // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
31065        // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
31066        // pass validate. The pair jointly pins the accessor +
31067        // validate-gate composition: any future silent detour that had
31068        // the accessor return a fresh `1` on the zero arm (a
31069        // `.max_failures().max(1)` collapse) would silently absorb the
31070        // `PolicyBreakerZeroFailures` refusal at the accessor boundary
31071        // and the validate gate would accept a struct-literal
31072        // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
31073        // catches that at caixa-core build time.
31074        //
31075        // Peer of the sibling per-`:politicas`
31076        // [`MeshPolicy::mtls_required`] (c0110f1) /
31077        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
31078        // (7073d0f) accessor-composition pins on the sibling optional-
31079        // scalar axes — same "the validate / shape-gate predicate must
31080        // route through the substrate-primitive typed dispatch"
31081        // discipline extended onto the peer per-`CircuitBreaker`
31082        // required-scalar composition axis.
31083        let mut spec = three_member_spec();
31084        spec.politicas = MeshPolicy {
31085            circuit_breaker: Some(CircuitBreaker {
31086                max_failures: 0,
31087                window: Duration::from_secs(60),
31088            }),
31089            ..MeshPolicy::default()
31090        };
31091        assert!(
31092            matches!(
31093                spec.validate(),
31094                Err(AplicacaoError::PolicyBreakerZeroFailures)
31095            ),
31096            "validate_politicas must reject max_failures == 0 with \
31097             PolicyBreakerZeroFailures — the accessor and the validate \
31098             gate must route through the same substrate-primitive typed \
31099             dispatch on the :max-failures zero-floor arm",
31100        );
31101        spec.politicas = MeshPolicy {
31102            circuit_breaker: Some(CircuitBreaker {
31103                max_failures: 1,
31104                window: Duration::from_secs(60),
31105            }),
31106            ..MeshPolicy::default()
31107        };
31108        assert!(
31109            spec.validate().is_ok(),
31110            "validate_politicas must accept max_failures == 1 (the \
31111             lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
31112             accept-set)",
31113        );
31114    }
31115
31116    #[test]
31117    fn circuit_breaker_max_failures_projects_u32_by_copy() {
31118        // The by-copy pin: [`CircuitBreaker::max_failures`] returns
31119        // `u32` by copy — `u32` is `Copy` and the accessor must return
31120        // by value, not by reference. Peer of the sibling
31121        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
31122        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
31123        // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
31124        // optional-scalar axes, extended onto the peer
31125        // per-`CircuitBreaker` required-`u32` copy-invariant shape —
31126        // the accessor's returned `u32` must outlive `&self` (multiple
31127        // calls must return equal values from a dropped-`&self` copy,
31128        // since the returned scalar carries no borrow), and calling
31129        // the accessor twice on the same CircuitBreaker must yield the
31130        // same `u32` verbatim (idempotent, no side effects on `&self`).
31131        //
31132        // Pins against a future silent detour that returned `&u32`
31133        // (which would type-check but silently break every downstream
31134        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
31135        // first parameter is `u32`, and `&u32` would fold to a detached
31136        // copy at the call site with a `*` deref the sibling accessors
31137        // don't need), an accidental `.max_failures.wrapping_add(0)`
31138        // detour that returned a fresh copy through an arithmetic
31139        // no-op (breaking a future `const fn` regression), or a
31140        // one-arm-only accessor that returned a saturating value on
31141        // some sentinel input (breaking the pass-through invariant the
31142        // sibling required-scalar accessors carry).
31143        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
31144            let cb = CircuitBreaker {
31145                max_failures,
31146                window: Duration::from_secs(60),
31147            };
31148            let first = cb.max_failures();
31149            let second = cb.max_failures();
31150            assert_eq!(
31151                first, second,
31152                "CircuitBreaker::max_failures must be idempotent — two \
31153                 successive calls on the same &self must return the \
31154                 same u32",
31155            );
31156            assert_eq!(
31157                first, max_failures,
31158                "CircuitBreaker::max_failures must return :politicas \
31159                 :circuit-breaker :max-failures verbatim by copy — \
31160                 got {first}, expected {max_failures}",
31161            );
31162        }
31163    }
31164
31165    #[test]
31166    fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
31167        // The canonical per-`:politicas :circuit-breaker` `:window`
31168        // Envoy-outlier-detection rolling-observation-interval scalar
31169        // pin: [`CircuitBreaker::window`] must return the
31170        // `:politicas :circuit-breaker :window` typed `Duration`
31171        // verbatim, byte-equal to the raw field access across every
31172        // representative value in the accept-set — `Duration::from_millis(1)`
31173        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
31174        // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
31175        // gate carves out on the sibling `PolicyBreakerZeroWindow`
31176        // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
31177        // same gate carves out on the sibling
31178        // `PolicyBreakerWindowExceedsCap` refusal),
31179        // `Duration::ZERO` (a past-the-guard sentinel that pins the
31180        // accessor doesn't perform a silent bounds-collapse into
31181        // `Duration::from_millis(1)` on the zero arm — validate rejects
31182        // zero but the accessor must ship the raw slot verbatim so a
31183        // validate-time gate regression surfaces at the emit boundary
31184        // rather than being silently absorbed),
31185        // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
31186        // far above the 1h cap — that pins the accessor doesn't perform
31187        // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
31188        // at the return path).
31189        //
31190        // Second sub-struct required-scalar accessor pin on the M3
31191        // mesh-slot family — sibling in shape to the just-landed
31192        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
31193        // (3a74062) required-`u32` accessor pin on the peer
31194        // per-`CircuitBreaker` required-axis, extended onto the
31195        // per-sub-struct required-`Duration` axis. Pins against a
31196        // future silent detour that re-derived the observation window
31197        // from a peer axis (an accidental
31198        // `Duration::from_secs(self.max_failures as u64)` collapse that
31199        // read the breaker's trip count as an observation-interval
31200        // duration), a `Duration::ZERO → Duration::from_millis(1)`
31201        // cluster-default projection (which would silently absorb the
31202        // `PolicyBreakerZeroWindow` refusal case at the accessor
31203        // boundary), or a bounds-collapsing accessor that clamped the
31204        // return through `POLICY_BREAKER_WINDOW_MAX` (the
31205        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
31206        // must ship the raw slot verbatim).
31207        for window in [
31208            Duration::from_millis(1),
31209            POLICY_BREAKER_WINDOW_MAX,
31210            Duration::ZERO,
31211            Duration::from_secs(86_400),
31212        ] {
31213            let cb = CircuitBreaker {
31214                max_failures: 5,
31215                window,
31216            };
31217            assert_eq!(
31218                cb.window(),
31219                window,
31220                "CircuitBreaker::window must return :politicas \
31221                 :circuit-breaker :window verbatim (got {:?}, \
31222                 expected {window:?})",
31223                cb.window(),
31224            );
31225            assert_eq!(
31226                cb.window(),
31227                cb.window,
31228                "CircuitBreaker::window must byte-equal the raw \
31229                 .window field access across every value in the \
31230                 Duration accept-set",
31231            );
31232        }
31233    }
31234
31235    #[test]
31236    fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
31237        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
31238        // `:circuit-breaker :window` zero-floor arm must key off
31239        // [`CircuitBreaker::window`], not the raw `.window` field
31240        // access. Structurally: a `CircuitBreaker { window:
31241        // Duration::ZERO, .. }` embedded in a
31242        // `:politicas :circuit-breaker` slot must surface the
31243        // `PolicyBreakerZeroWindow` refusal exactly, and a
31244        // `CircuitBreaker { window: Duration::from_millis(1), .. }`
31245        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
31246        // accept-set) must pass validate. The pair jointly pins the
31247        // accessor + validate-gate composition: any future silent
31248        // detour that had the accessor return a fresh
31249        // `Duration::from_millis(1)` on the zero arm (a
31250        // `.window().max(Duration::from_millis(1))` collapse) would
31251        // silently absorb the `PolicyBreakerZeroWindow` refusal at the
31252        // accessor boundary and the validate gate would accept a
31253        // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
31254        // — the composition pin catches that at caixa-core build time.
31255        //
31256        // Peer of the sibling per-`CircuitBreaker`
31257        // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
31258        // pin on the peer required-scalar `:max-failures` axis — same
31259        // "the validate / shape-gate predicate must route through the
31260        // substrate-primitive typed dispatch" discipline extended onto
31261        // the peer per-`CircuitBreaker` required-`Duration` composition
31262        // axis.
31263        let mut spec = three_member_spec();
31264        spec.politicas = MeshPolicy {
31265            circuit_breaker: Some(CircuitBreaker {
31266                max_failures: 5,
31267                window: Duration::ZERO,
31268            }),
31269            ..MeshPolicy::default()
31270        };
31271        assert!(
31272            matches!(
31273                spec.validate(),
31274                Err(AplicacaoError::PolicyBreakerZeroWindow)
31275            ),
31276            "validate_politicas must reject window == Duration::ZERO \
31277             with PolicyBreakerZeroWindow — the accessor and the \
31278             validate gate must route through the same substrate-\
31279             primitive typed dispatch on the :window zero-floor arm",
31280        );
31281        spec.politicas = MeshPolicy {
31282            circuit_breaker: Some(CircuitBreaker {
31283                max_failures: 5,
31284                window: Duration::from_millis(1),
31285            }),
31286            ..MeshPolicy::default()
31287        };
31288        assert!(
31289            spec.validate().is_ok(),
31290            "validate_politicas must accept window == \
31291             Duration::from_millis(1) (the lower boundary of the \
31292             1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
31293        );
31294    }
31295
31296    #[test]
31297    fn circuit_breaker_window_projects_duration_by_copy() {
31298        // The by-copy pin: [`CircuitBreaker::window`] returns
31299        // `Duration` by copy — `Duration` is `Copy` and the accessor
31300        // must return by value, not by reference. Peer of the sibling
31301        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
31302        // (3a74062) by-copy pin on the peer required-scalar
31303        // `:max-failures` axis, extended onto the peer
31304        // per-`CircuitBreaker` required-`Duration` copy-invariant shape
31305        // — the accessor's returned `Duration` must outlive `&self`
31306        // (multiple calls must return equal values from a
31307        // dropped-`&self` copy, since the returned scalar carries no
31308        // borrow), and calling the accessor twice on the same
31309        // CircuitBreaker must yield the same `Duration` verbatim
31310        // (idempotent, no side effects on `&self`).
31311        //
31312        // Pins against a future silent detour that returned
31313        // `&Duration` (which would type-check but silently break every
31314        // downstream `Duration`-by-value consumer —
31315        // [`crate::render::require_positive_canonical_bounded_duration`]'s
31316        // first parameter is `Duration`, and `&Duration` would fold to
31317        // a detached copy at the call site with a `*` deref the sibling
31318        // accessors don't need), an accidental `.window + Duration::ZERO`
31319        // detour that returned a fresh copy through an arithmetic
31320        // no-op (breaking a future `const fn` regression), or a
31321        // one-arm-only accessor that returned a saturating value on
31322        // some sentinel input (breaking the pass-through invariant the
31323        // sibling required-scalar accessors carry).
31324        for window in [
31325            Duration::from_millis(1),
31326            POLICY_BREAKER_WINDOW_MAX,
31327            Duration::ZERO,
31328            Duration::from_secs(86_400),
31329        ] {
31330            let cb = CircuitBreaker {
31331                max_failures: 5,
31332                window,
31333            };
31334            let first = cb.window();
31335            let second = cb.window();
31336            assert_eq!(
31337                first, second,
31338                "CircuitBreaker::window must be idempotent — two \
31339                 successive calls on the same &self must return the \
31340                 same Duration",
31341            );
31342            assert_eq!(
31343                first, window,
31344                "CircuitBreaker::window must return :politicas \
31345                 :circuit-breaker :window verbatim by copy — \
31346                 got {first:?}, expected {window:?}",
31347            );
31348        }
31349    }
31350
31351    #[test]
31352    fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
31353        // Apex-identity pair-invariant pin composing both substrate-
31354        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
31355        // and [`WitContract::destination`] — at the emit-side call shape
31356        // every per-`(:de, :para)` CNP L4 port reader now takes. The
31357        // invariant, evaluated per-edge:
31358        //
31359        //   spec.port_for_destination(c.destination()) == expected_port
31360        //
31361        // where `expected_port` is `entrada.port` when
31362        // `c.destination() == entrada.destination()` and
31363        // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
31364        // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
31365        // pin on the per-`:entrada` axis — that pin encodes the apex
31366        // ingress L4 identity via `entrada.destination()`; this pin
31367        // encodes the per-edge L4 identity via `c.destination()`, and
31368        // both compose on the same substrate-primitive resolver so a
31369        // future refactor that silently split either accessor's apex
31370        // behavior surfaces at caixa-core build time.
31371        let mut spec = three_member_spec();
31372        if let Some(e) = spec.entrada.as_mut() {
31373            e.para = "cart".into();
31374            e.port = 8443;
31375        }
31376        let apex_contract = WitContract {
31377            de: "checkout".into(),
31378            para: "cart".into(),
31379            wit: "wasi:http/proxy".into(),
31380            endpoint: Some("/hello".into()),
31381            subject: None,
31382            slot: None,
31383        };
31384        assert_eq!(
31385            spec.port_for_destination(apex_contract.destination()),
31386            8443,
31387            "`spec.port_for_destination(c.destination())` must equal \
31388             `entrada.port` when the contract callee names the ingress \
31389             apex — the CNP per-edge L4 port and the HTTPRoute apex \
31390             backendRef port share this substrate-primitive resolver.",
31391        );
31392        let non_apex_contract = WitContract {
31393            de: "cart".into(),
31394            para: "payment".into(),
31395            wit: "wasi:http/proxy".into(),
31396            endpoint: Some("/charge".into()),
31397            subject: None,
31398            slot: None,
31399        };
31400        assert_eq!(
31401            spec.port_for_destination(non_apex_contract.destination()),
31402            DEFAULT_SERVICO_PORT,
31403            "`spec.port_for_destination(c.destination())` must fall back \
31404             to the substrate-canonical port floor when the contract \
31405             callee is not the ingress apex — the resolver's non-apex \
31406             arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
31407        );
31408    }
31409
31410    #[test]
31411    fn membro_key_consts_are_lower_camel_case_shape() {
31412        // Shape-pin: every `MEMBRO_KEY_*` const must be a
31413        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
31414        // `kebab-case` hyphens, no leading colon, no `PascalCase`
31415        // leading capital, no whitespace / dots) — the canonical shape
31416        // the `#[serde(rename_all = "camelCase")]` derive produces on
31417        // [`Membro`]. A future flip to a non-camelCase attribute at
31418        // the derive surfaces both here (this test fails on the
31419        // stale-constant shape) and at
31420        // `membro_serde_keys_match_lifted_membro_key_consts` (that test
31421        // fails on the mismatch between const and derive). Peer with
31422        // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
31423        // on the sibling `SupervisorSpec` top-level axis.
31424        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
31425            assert!(
31426                !key.is_empty(),
31427                "MEMBRO_KEY_* must be non-empty (got {key:?})"
31428            );
31429            let first = key.chars().next().unwrap();
31430            assert!(
31431                first.is_ascii_lowercase(),
31432                "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
31433                 (got {key:?}, leads with {first:?})",
31434            );
31435            assert!(
31436                key.chars().all(|c| c.is_ascii_alphanumeric()),
31437                "MEMBRO_KEY_* must be ASCII-alphanumeric only \
31438                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
31439            );
31440        }
31441    }
31442
31443    // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
31444
31445    #[test]
31446    fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
31447        // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
31448        // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
31449        // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
31450        // keys the `#[serde(rename_all = "camelCase")]` attribute on
31451        // [`WitContract`] emits for the required-triad. The three
31452        // sibling payload-arm keys already pin under
31453        // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
31454        // `STORE_FIELD_NAME` — pin all six alongside so a future
31455        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
31456        // verbatim-field-name flip at the derive attribute (any of which
31457        // would silently break every downstream JSON consumer that
31458        // reaches for one of the six via `Value::get(...)`) surfaces
31459        // here as a build-time test failure at `aplicacao.rs`, not as an
31460        // apply-time `.get(<stale-canonical-const>)` returning `None`
31461        // far from the derive-attr drift's commit. Peer with the sibling
31462        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
31463        // pin on the M3 `:membros` per-entry axis — same discipline the
31464        // `Membro` per-entry lift established, extended here to the
31465        // sibling M3 `WitContract` per-`:contratos` entry axis, the last
31466        // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
31467        // axis on the Aplicacao surface without a lifted serde-key peer.
31468        let c = WitContract {
31469            de: "cart".into(),
31470            para: "catalog".into(),
31471            wit: "wasi:http/proxy".into(),
31472            endpoint: Some("/lookup".into()),
31473            subject: None,
31474            slot: None,
31475        };
31476        let json = serde_json::to_string(&c).unwrap();
31477        for key in [
31478            crate::CONTRATO_KEY_DE,
31479            crate::CONTRATO_KEY_PARA,
31480            crate::CONTRATO_KEY_WIT,
31481            WitTarget::HTTP_FIELD_NAME,
31482        ] {
31483            let quoted = format!("\"{key}\"");
31484            assert!(
31485                json.contains(&quoted),
31486                "serialized WitContract must carry the lifted \
31487                 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
31488                 {quoted} verbatim in the JSON emission (got: {json})",
31489            );
31490        }
31491
31492        // Pin the two remaining payload-arm keys by round-tripping a
31493        // `WitContract` under each payload-shape (pub-sub, store) — the
31494        // required-triad appears on every emission but the payload arms
31495        // only surface when their `Option<String>` field is `Some`.
31496        let pubsub = WitContract {
31497            de: "cart".into(),
31498            para: "events".into(),
31499            wit: "nats:pub-sub".into(),
31500            endpoint: None,
31501            subject: Some("orders.placed".into()),
31502            slot: None,
31503        };
31504        let pubsub_json = serde_json::to_string(&pubsub).unwrap();
31505        let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
31506        assert!(
31507            pubsub_json.contains(&pubsub_quoted),
31508            "serialized pub-sub WitContract must carry the lifted \
31509             WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
31510             verbatim in the JSON emission (got: {pubsub_json})",
31511        );
31512        let store = WitContract {
31513            de: "cart".into(),
31514            para: "sessions".into(),
31515            wit: "wasi:keyvalue/store".into(),
31516            endpoint: None,
31517            subject: None,
31518            slot: Some("cart/$id".into()),
31519        };
31520        let store_json = serde_json::to_string(&store).unwrap();
31521        let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
31522        assert!(
31523            store_json.contains(&store_quoted),
31524            "serialized store WitContract must carry the lifted \
31525             WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
31526             verbatim in the JSON emission (got: {store_json})",
31527        );
31528    }
31529
31530    #[test]
31531    fn contrato_key_consts_are_pairwise_distinct() {
31532        // Cross-axis drift-detection pin: a future collapse of the six
31533        // canonical [`WitContract`] per-entry byte-strings onto the same
31534        // value (e.g. an accidental copy-paste flip of
31535        // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
31536        // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
31537        // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
31538        // every downstream probe on one axis onto the sibling axis's
31539        // overlay entry and pass every propagation-probe test that
31540        // expected only the stale axis's value. Peer of the sibling
31541        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
31542        // widened here to the six-way axis the `WitContract`
31543        // required-triad + `WitTarget` payload-triad jointly cover.
31544        let all = [
31545            crate::CONTRATO_KEY_DE,
31546            crate::CONTRATO_KEY_PARA,
31547            crate::CONTRATO_KEY_WIT,
31548            WitTarget::HTTP_FIELD_NAME,
31549            WitTarget::PUBSUB_FIELD_NAME,
31550            WitTarget::STORE_FIELD_NAME,
31551        ];
31552        for (i, a) in all.iter().enumerate() {
31553            for b in all.iter().skip(i + 1) {
31554                assert_ne!(
31555                    a, b,
31556                    "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
31557                     must be pairwise-distinct canonical byte-sequences \
31558                     — got `{a}` == `{b}`",
31559                );
31560            }
31561        }
31562    }
31563
31564    #[test]
31565    fn contrato_key_consts_are_lower_camel_case_shape() {
31566        // Shape-pin: every `CONTRATO_KEY_*` (and every peer
31567        // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
31568        // byte-sequence (no `snake_case` underscores, no `kebab-case`
31569        // hyphens, no leading colon, no `PascalCase` leading capital, no
31570        // whitespace / dots) — the canonical shape the
31571        // `#[serde(rename_all = "camelCase")]` derive produces on
31572        // [`WitContract`]. A future flip to a non-camelCase attribute at
31573        // the derive surfaces both here (this test fails on the
31574        // stale-constant shape) and at
31575        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
31576        // (that test fails on the mismatch between const and derive).
31577        // Peer with `membro_key_consts_are_lower_camel_case_shape`
31578        // (ce80ca0) on the sibling `Membro` per-entry axis.
31579        for key in [
31580            crate::CONTRATO_KEY_DE,
31581            crate::CONTRATO_KEY_PARA,
31582            crate::CONTRATO_KEY_WIT,
31583            WitTarget::HTTP_FIELD_NAME,
31584            WitTarget::PUBSUB_FIELD_NAME,
31585            WitTarget::STORE_FIELD_NAME,
31586        ] {
31587            assert!(
31588                !key.is_empty(),
31589                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
31590                 non-empty (got {key:?})"
31591            );
31592            let first = key.chars().next().unwrap();
31593            assert!(
31594                first.is_ascii_lowercase(),
31595                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
31596                 with an ASCII-lowercase byte (got {key:?}, leads with \
31597                 {first:?})",
31598            );
31599            assert!(
31600                key.chars().all(|c| c.is_ascii_alphanumeric()),
31601                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
31602                 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
31603                 whitespace (got {key:?})",
31604            );
31605        }
31606    }
31607
31608    // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
31609
31610    #[test]
31611    fn entrada_serde_keys_match_lifted_entrada_key_consts() {
31612        // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
31613        // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
31614        // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
31615        // name the exact camelCase JSON keys the
31616        // `#[serde(rename_all = "camelCase")]` attribute on
31617        // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
31618        // pin that each canonical byte-sequence appears verbatim in the
31619        // JSON — a future accidental `rename_all = "snake_case"` /
31620        // `"kebab-case"` / verbatim-field-name flip at the derive
31621        // attribute (any of which would silently break every downstream
31622        // JSON consumer that reaches for one of the four consts via
31623        // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
31624        // emitter's per-Aplicacao hostname/paths/port projection, the
31625        // future `app-operator` reconciler's per-Aplicacao ingress
31626        // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
31627        // materializer's admission-time cross-check) surfaces here as
31628        // a build-time test failure at `aplicacao.rs`, not as an
31629        // apply-time `.get(<stale-canonical-const>)` returning `None`
31630        // far from the derive-attr drift's commit. Peer with the
31631        // sibling
31632        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
31633        // (ca463a4) and
31634        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
31635        // pins on the M3 collection-slot atom axes — same discipline
31636        // both collection-slot lifts established, extended here to the
31637        // singleton `:entrada` mesh-slot atom axis, the last M3
31638        // typed-struct top-level `#[serde(rename_all = "camelCase")]`
31639        // axis on the Aplicacao surface without a lifted serde-key
31640        // peer.
31641        let e = Entrada {
31642            host: "checkout.quero.cloud".into(),
31643            para: "cart".into(),
31644            paths: vec!["/cart".into()],
31645            port: 8080,
31646        };
31647        let json = serde_json::to_string(&e).unwrap();
31648        for key in [
31649            crate::ENTRADA_KEY_HOST,
31650            crate::ENTRADA_KEY_PARA,
31651            crate::ENTRADA_KEY_PATHS,
31652            crate::ENTRADA_KEY_PORT,
31653        ] {
31654            let quoted = format!("\"{key}\"");
31655            assert!(
31656                json.contains(&quoted),
31657                "serialized Entrada must carry the lifted ENTRADA_KEY_* \
31658                 byte-sequence {quoted} verbatim in the JSON emission \
31659                 (got: {json})",
31660            );
31661        }
31662    }
31663
31664    #[test]
31665    fn entrada_key_consts_are_pairwise_distinct() {
31666        // Cross-axis drift-detection pin: a future collapse of the four
31667        // canonical [`Entrada`] singleton byte-strings onto the same
31668        // value (e.g. an accidental copy-paste flip of
31669        // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
31670        // silently reroute every downstream probe on one axis onto the
31671        // sibling axis's overlay entry and pass every propagation-probe
31672        // test that expected only the stale axis's value — the
31673        // Gateway/HTTPRoute emitter would read the hostname string
31674        // where the destination-Servico name was expected (or vice
31675        // versa), the admission-webhook cross-check would compare the
31676        // wrong pair of values, and the resulting Gateway resource
31677        // would either be admitted with garbage or rejected at the
31678        // controller far from the rebrand commit's source. Peer of the
31679        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
31680        // tetrad (40cc4e5), the two-way distinct pin on the
31681        // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
31682        // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
31683        // triad (ca463a4).
31684        let all = [
31685            crate::ENTRADA_KEY_HOST,
31686            crate::ENTRADA_KEY_PARA,
31687            crate::ENTRADA_KEY_PATHS,
31688            crate::ENTRADA_KEY_PORT,
31689        ];
31690        for (i, a) in all.iter().enumerate() {
31691            for b in all.iter().skip(i + 1) {
31692                assert_ne!(
31693                    a, b,
31694                    "ENTRADA_KEY_* consts must be pairwise-distinct \
31695                     canonical byte-sequences — got `{a}` == `{b}`",
31696                );
31697            }
31698        }
31699    }
31700
31701    #[test]
31702    fn entrada_key_consts_are_lower_camel_case_shape() {
31703        // Shape-pin: every `ENTRADA_KEY_*` const must be a
31704        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
31705        // `kebab-case` hyphens, no leading colon, no `PascalCase`
31706        // leading capital, no whitespace / dots) — the canonical shape
31707        // the `#[serde(rename_all = "camelCase")]` derive produces on
31708        // [`Entrada`]. A future flip to a non-camelCase attribute at
31709        // the derive surfaces both here (this test fails on the
31710        // stale-constant shape) and at
31711        // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
31712        // test fails on the mismatch between const and derive). Peer
31713        // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
31714        // and `contrato_key_consts_are_lower_camel_case_shape`
31715        // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
31716        // entry axes.
31717        for key in [
31718            crate::ENTRADA_KEY_HOST,
31719            crate::ENTRADA_KEY_PARA,
31720            crate::ENTRADA_KEY_PATHS,
31721            crate::ENTRADA_KEY_PORT,
31722        ] {
31723            assert!(
31724                !key.is_empty(),
31725                "ENTRADA_KEY_* must be non-empty (got {key:?})"
31726            );
31727            let first = key.chars().next().unwrap();
31728            assert!(
31729                first.is_ascii_lowercase(),
31730                "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
31731                 (got {key:?}, leads with {first:?})",
31732            );
31733            assert!(
31734                key.chars().all(|c| c.is_ascii_alphanumeric()),
31735                "ENTRADA_KEY_* must be ASCII-alphanumeric only \
31736                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
31737            );
31738        }
31739    }
31740
31741    // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
31742
31743    #[test]
31744    fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
31745        // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
31746        // ([`crate::POLITICAS_KEY_TIMEOUT`] /
31747        // [`crate::POLITICAS_KEY_RETRIES`] /
31748        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
31749        // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
31750        // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
31751        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
31752        // on [`MeshPolicy`] emits. Three of the five axes
31753        // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
31754        // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
31755        // camelCase transforms — the derive-attribute is load-bearing
31756        // on those, unlike the sibling `Entrada` / `Membro` /
31757        // `WitContract` structs whose fields are all lowercase-single-
31758        // word and where the derive is a no-op on every axis.
31759        // Serialize a fully-populated [`MeshPolicy`] (every axis
31760        // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
31761        // on none of the five slots) and pin that each canonical
31762        // byte-sequence appears verbatim in the JSON — a future
31763        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
31764        // verbatim-field-name flip at the derive attribute (any of
31765        // which would silently break every downstream JSON consumer
31766        // that reaches for one of the five consts via
31767        // `Value::get(...)` — the future M4 per-edge `:politicas`
31768        // overlay projection onto Cilium `L7Rules` and Gateway API
31769        // `HTTPRoute` backend timeouts, the future
31770        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
31771        // admission-time mesh-policy cross-check, the future
31772        // `feira lint` per-`:politicas` bound-check gate) surfaces here
31773        // as a build-time test failure at `aplicacao.rs`, not as an
31774        // apply-time `.get(<stale-canonical-const>)` returning `None`
31775        // far from the derive-attr drift's commit. Peer with the
31776        // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
31777        // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
31778        // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
31779        // (ce80ca0) pins on the M3 collection-slot / singleton-slot
31780        // atom axes — same discipline every M3 sibling lift
31781        // established, extended here to the singleton `:politicas`
31782        // mesh-slot atom axis, closing the last M3 typed-struct
31783        // top-level `#[serde(rename_all = "camelCase")]` axis on the
31784        // Aplicacao surface without a lifted serde-key peer.
31785        let p = MeshPolicy {
31786            timeout: Some(Duration::from_secs(30)),
31787            retries: Some(3),
31788            circuit_breaker: Some(CircuitBreaker {
31789                max_failures: 5,
31790                window: Duration::from_secs(60),
31791            }),
31792            mtls_required: Some(true),
31793            rate_limit: Some(RateLimit {
31794                rate: 100,
31795                window: Duration::from_secs(1),
31796            }),
31797        };
31798        let json = serde_json::to_string(&p).unwrap();
31799        for key in [
31800            crate::POLITICAS_KEY_TIMEOUT,
31801            crate::POLITICAS_KEY_RETRIES,
31802            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
31803            crate::POLITICAS_KEY_MTLS_REQUIRED,
31804            crate::POLITICAS_KEY_RATE_LIMIT,
31805        ] {
31806            let quoted = format!("\"{key}\"");
31807            assert!(
31808                json.contains(&quoted),
31809                "serialized MeshPolicy must carry the lifted \
31810                 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
31811                 JSON emission (got: {json})",
31812            );
31813        }
31814    }
31815
31816    #[test]
31817    fn politicas_key_consts_are_pairwise_distinct() {
31818        // Cross-axis drift-detection pin: a future collapse of the five
31819        // canonical [`MeshPolicy`] singleton byte-strings onto the same
31820        // value (e.g. an accidental copy-paste flip of
31821        // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
31822        // would silently reroute every downstream probe on one axis
31823        // onto the sibling axis's overlay entry and pass every
31824        // propagation-probe test that expected only the stale axis's
31825        // value — the M4 per-edge `:politicas` overlay projection would
31826        // read the retry-count string where the timeout duration was
31827        // expected (or vice versa), the CR materializer's admission
31828        // cross-check would compare the wrong pair of values, and the
31829        // resulting mesh reconciler would either bind the wrong axis
31830        // or reject the resource at reconcile far from the rebrand
31831        // commit's source. Peer of the sibling four-way distinct pin
31832        // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
31833        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
31834        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
31835        // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
31836        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
31837        let all = [
31838            crate::POLITICAS_KEY_TIMEOUT,
31839            crate::POLITICAS_KEY_RETRIES,
31840            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
31841            crate::POLITICAS_KEY_MTLS_REQUIRED,
31842            crate::POLITICAS_KEY_RATE_LIMIT,
31843        ];
31844        for (i, a) in all.iter().enumerate() {
31845            for b in all.iter().skip(i + 1) {
31846                assert_ne!(
31847                    a, b,
31848                    "POLITICAS_KEY_* consts must be pairwise-distinct \
31849                     canonical byte-sequences — got `{a}` == `{b}`",
31850                );
31851            }
31852        }
31853    }
31854
31855    #[test]
31856    fn politicas_key_consts_are_lower_camel_case_shape() {
31857        // Shape-pin: every `POLITICAS_KEY_*` const must be a
31858        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
31859        // `kebab-case` hyphens, no leading colon, no `PascalCase`
31860        // leading capital, no whitespace / dots) — the canonical shape
31861        // the `#[serde(rename_all = "camelCase")]` derive produces on
31862        // [`MeshPolicy`]. A future flip to a non-camelCase attribute
31863        // at the derive surfaces both here (this test fails on the
31864        // stale-constant shape) and at
31865        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
31866        // (that test fails on the mismatch between const and derive).
31867        // Peer with `entrada_key_consts_are_lower_camel_case_shape`
31868        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
31869        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
31870        // (ca463a4) on the sibling M3 typed-struct axes.
31871        for key in [
31872            crate::POLITICAS_KEY_TIMEOUT,
31873            crate::POLITICAS_KEY_RETRIES,
31874            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
31875            crate::POLITICAS_KEY_MTLS_REQUIRED,
31876            crate::POLITICAS_KEY_RATE_LIMIT,
31877        ] {
31878            assert!(
31879                !key.is_empty(),
31880                "POLITICAS_KEY_* must be non-empty (got {key:?})"
31881            );
31882            let first = key.chars().next().unwrap();
31883            assert!(
31884                first.is_ascii_lowercase(),
31885                "POLITICAS_KEY_* must lead with an ASCII-lowercase \
31886                 byte (got {key:?}, leads with {first:?})",
31887            );
31888            assert!(
31889                key.chars().all(|c| c.is_ascii_alphanumeric()),
31890                "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
31891                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
31892            );
31893        }
31894    }
31895
31896    // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
31897
31898    #[test]
31899    fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
31900        // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
31901        // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
31902        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
31903        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
31904        // [`CircuitBreaker`] emits inside the
31905        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
31906        // two axes (`max_failures` → `maxFailures`) is a non-trivial
31907        // camelCase transform — the derive-attribute is load-bearing on
31908        // that axis, unlike the sibling `window` field where the derive
31909        // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
31910        // pin that each canonical byte-sequence appears verbatim in the
31911        // JSON — a future accidental `rename_all = "snake_case"` /
31912        // `"kebab-case"` / verbatim-field-name flip at the derive
31913        // attribute (any of which would silently break every downstream
31914        // JSON consumer that reaches for one of the two consts via
31915        // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
31916        // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
31917        // per-edge `:politicas` overlay projection onto the mesh's
31918        // per-backend consecutive-failure-counter tripping threshold, the
31919        // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
31920        // admission-time breaker cross-check, the future `feira lint`
31921        // per-`:politicas :circuit-breaker` bound-check gate) surfaces
31922        // here as a build-time test failure at `aplicacao.rs`, not as an
31923        // apply-time `.get(<stale-canonical-const>)` returning `None`
31924        // far from the derive-attr drift's commit. Peer with the sibling
31925        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
31926        // (b55cca7) parent-axis pin — that test pins the outer
31927        // sub-block key the derive on [`MeshPolicy`] emits, this test
31928        // pins the inner keys the derive on the payload type emits, so
31929        // the two together lock the whole [`MeshPolicy`] breaker-tuning
31930        // shape end-to-end at build time.
31931        let cb = CircuitBreaker {
31932            max_failures: 5,
31933            window: Duration::from_secs(60),
31934        };
31935        let json = serde_json::to_string(&cb).unwrap();
31936        for key in [
31937            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
31938            crate::CIRCUIT_BREAKER_KEY_WINDOW,
31939        ] {
31940            let quoted = format!("\"{key}\"");
31941            assert!(
31942                json.contains(&quoted),
31943                "serialized CircuitBreaker must carry the lifted \
31944                 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
31945                 in the JSON emission (got: {json})",
31946            );
31947        }
31948    }
31949
31950    #[test]
31951    fn circuit_breaker_key_consts_are_pairwise_distinct() {
31952        // Cross-axis drift-detection pin: a future collapse of the two
31953        // canonical [`CircuitBreaker`] sub-block byte-strings onto the
31954        // same value (e.g. an accidental copy-paste flip of
31955        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
31956        // `"maxFailures"`) would silently reroute every downstream
31957        // probe on one axis onto the sibling axis's overlay entry and
31958        // pass every propagation-probe test that expected only the
31959        // stale axis's value — the M4 per-edge `:politicas` overlay
31960        // projection would read the failure-count where the window
31961        // duration was expected (or vice versa), the CR materializer's
31962        // admission cross-check would compare the wrong pair of values,
31963        // and the resulting mesh reconciler would either bind the wrong
31964        // axis or reject the resource at reconcile far from the rebrand
31965        // commit's source. Peer of the sibling five-way distinct pin on
31966        // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
31967        // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
31968        // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
31969        // six-way distinct pin on the `CONTRATO_KEY_*` triad +
31970        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
31971        let all = [
31972            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
31973            crate::CIRCUIT_BREAKER_KEY_WINDOW,
31974        ];
31975        for (i, a) in all.iter().enumerate() {
31976            for b in all.iter().skip(i + 1) {
31977                assert_ne!(
31978                    a, b,
31979                    "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
31980                     canonical byte-sequences — got `{a}` == `{b}`",
31981                );
31982            }
31983        }
31984    }
31985
31986    #[test]
31987    fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
31988        // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
31989        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
31990        // `kebab-case` hyphens, no leading colon, no `PascalCase`
31991        // leading capital, no whitespace / dots) — the canonical shape
31992        // the `#[serde(rename_all = "camelCase")]` derive produces on
31993        // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
31994        // at the derive surfaces both here (this test fails on the
31995        // stale-constant shape) and at
31996        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
31997        // (that test fails on the mismatch between const and derive).
31998        // Peer with `politicas_key_consts_are_lower_camel_case_shape`
31999        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
32000        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
32001        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
32002        // (ca463a4) on the sibling M3 typed-struct axes.
32003        for key in [
32004            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
32005            crate::CIRCUIT_BREAKER_KEY_WINDOW,
32006        ] {
32007            assert!(
32008                !key.is_empty(),
32009                "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
32010            );
32011            let first = key.chars().next().unwrap();
32012            assert!(
32013                first.is_ascii_lowercase(),
32014                "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
32015                 byte (got {key:?}, leads with {first:?})",
32016            );
32017            assert!(
32018                key.chars().all(|c| c.is_ascii_alphanumeric()),
32019                "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
32020                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
32021            );
32022        }
32023    }
32024
32025    // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
32026
32027    #[test]
32028    fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
32029        // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
32030        // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
32031        // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
32032        // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
32033        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
32034        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
32035        // [`Placement`] emits. One of the four axes (`shard_key` →
32036        // `shardKey`) is a non-trivial camelCase transform — the
32037        // derive-attribute is load-bearing on that axis, unlike the
32038        // sibling `estrategia` / `clusters` / `affinity` axes whose
32039        // source-side field names carry no `_` and where the derive is a
32040        // no-op. Serialize a fully-populated [`Placement`] (both
32041        // `Option`-carrying axes `Some(_)` so
32042        // `skip_serializing_if = "Option::is_none"` fires on neither of
32043        // the two optional slots) and pin that each canonical
32044        // byte-sequence appears verbatim in the JSON — a future
32045        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
32046        // verbatim-field-name flip at the derive attribute (any of which
32047        // would silently break every downstream consumer that reaches
32048        // for one of the four consts via
32049        // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
32050        // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
32051        // aggregator's per-cluster fanout filter keying off
32052        // `placement.clusters`, the M3 shard-pool dispatch materializer
32053        // keying off `placement.shardKey`, the M3 Adaptive compression
32054        // pass weighting off `placement.affinity`, every downstream
32055        // dispatcher branching on `placement.estrategia`, the future
32056        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
32057        // admission-time placement cross-check, the future `feira lint`
32058        // per-`:placement` bound-check gate) surfaces here as a
32059        // build-time test failure at `aplicacao.rs`, not as an
32060        // apply-time `.get(<stale-canonical-const>)` returning `None`
32061        // far from the derive-attr drift's commit. Peer with the sibling
32062        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
32063        // (b55cca7),
32064        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
32065        // (468e959),
32066        // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
32067        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
32068        // (ca463a4), and
32069        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
32070        // pins on the M3 collection-slot / singleton-slot atom axes —
32071        // closes the last M3 typed-struct top-level
32072        // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
32073        // surface without a drift-detection pin.
32074        let p = Placement {
32075            estrategia: PlacementStrategy::Sharded,
32076            clusters: vec!["rio".into(), "mar".into()],
32077            affinity: Some("data-locality".into()),
32078            shard_key: Some("$tenantId".into()),
32079        };
32080        let json = serde_json::to_string(&p).unwrap();
32081        for key in [
32082            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
32083            crate::M3_PLACEMENT_KEY_CLUSTERS,
32084            crate::M3_PLACEMENT_KEY_AFFINITY,
32085            crate::M3_PLACEMENT_KEY_SHARD_KEY,
32086        ] {
32087            let quoted = format!("\"{key}\"");
32088            assert!(
32089                json.contains(&quoted),
32090                "serialized Placement must carry the lifted \
32091                 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
32092                 the JSON emission (got: {json})",
32093            );
32094        }
32095    }
32096
32097    #[test]
32098    fn m3_placement_key_consts_are_pairwise_distinct() {
32099        // Cross-axis drift-detection pin: a future collapse of the four
32100        // canonical [`Placement`] sub-block byte-strings onto the same
32101        // value (e.g. an accidental copy-paste flip of
32102        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
32103        // `"affinity"`) would silently reroute every downstream probe on
32104        // one axis onto the sibling axis's overlay entry and pass every
32105        // propagation-probe test that expected only the stale axis's
32106        // value — the M3 shard-pool dispatch materializer would read the
32107        // affinity placement-hint where the shard-selection template was
32108        // expected (or vice versa), the M3 Adaptive compression pass's
32109        // cross-check would compare the wrong pair of values, and the
32110        // resulting placement engine would either bind the wrong axis or
32111        // reject the resource at reconcile far from the rebrand commit's
32112        // source. Peer of the sibling two-way distinct pin on the
32113        // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
32114        // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
32115        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
32116        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
32117        // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
32118        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
32119        let all = [
32120            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
32121            crate::M3_PLACEMENT_KEY_CLUSTERS,
32122            crate::M3_PLACEMENT_KEY_AFFINITY,
32123            crate::M3_PLACEMENT_KEY_SHARD_KEY,
32124        ];
32125        for (i, a) in all.iter().enumerate() {
32126            for b in all.iter().skip(i + 1) {
32127                assert_ne!(
32128                    a, b,
32129                    "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
32130                     canonical byte-sequences — got `{a}` == `{b}`",
32131                );
32132            }
32133        }
32134    }
32135
32136    #[test]
32137    fn m3_placement_key_consts_are_lower_camel_case_shape() {
32138        // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
32139        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
32140        // `kebab-case` hyphens, no leading colon, no `PascalCase`
32141        // leading capital, no whitespace / dots) — the canonical shape
32142        // the `#[serde(rename_all = "camelCase")]` derive produces on
32143        // [`Placement`]. A future flip to a non-camelCase attribute at
32144        // the derive surfaces both here (this test fails on the stale-
32145        // constant shape) and at
32146        // `placement_serde_keys_match_lifted_m3_placement_key_consts`
32147        // (that test fails on the mismatch between const and derive).
32148        // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
32149        // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
32150        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
32151        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
32152        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
32153        // (ca463a4) on the sibling M3 typed-struct axes.
32154        for key in [
32155            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
32156            crate::M3_PLACEMENT_KEY_CLUSTERS,
32157            crate::M3_PLACEMENT_KEY_AFFINITY,
32158            crate::M3_PLACEMENT_KEY_SHARD_KEY,
32159        ] {
32160            assert!(
32161                !key.is_empty(),
32162                "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
32163            );
32164            let first = key.chars().next().unwrap();
32165            assert!(
32166                first.is_ascii_lowercase(),
32167                "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
32168                 byte (got {key:?}, leads with {first:?})",
32169            );
32170            assert!(
32171                key.chars().all(|c| c.is_ascii_alphanumeric()),
32172                "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
32173                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
32174            );
32175        }
32176    }
32177
32178    // ── AplicacaoSpec::port_for_destination — the substrate-canonical
32179    //    destination-facing L4 port resolver every per-Aplicacao renderer
32180    //    reaching for a per-destination Servico TCP port axis routes
32181    //    through. The four pin tests below fix the four-way accept-set
32182    //    the resolver must always honor: (:entrada-para-matches,
32183    //    :entrada-para-mismatches, :entrada-none-so-fallback,
32184    //    :entrada-port-non-default-honored) — drift on any arm surfaces
32185    //    at caixa-core build time rather than at cluster-apply time.
32186
32187    #[test]
32188    fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
32189        // The typed `:entrada` block's `:para "cart"` matches the
32190        // queried destination, so the resolver returns the author-
32191        // declared `:port` scalar verbatim — the canonical "the
32192        // destination Servico IS the ingress apex, honor the typed
32193        // listener port" arm of the port-resolution dispatch.
32194        let mut spec = three_member_spec();
32195        if let Some(e) = spec.entrada.as_mut() {
32196            e.para = "cart".into();
32197            e.port = 9090;
32198        }
32199        assert_eq!(
32200            spec.port_for_destination("cart"),
32201            9090,
32202            "port_for_destination(entrada.para) must return entrada.port \
32203             verbatim, not the DEFAULT_SERVICO_PORT fallback"
32204        );
32205    }
32206
32207    #[test]
32208    fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
32209        // The typed `:entrada` block names `:para "cart"`, but the
32210        // queried destination is `"payment"` — a Servico that
32211        // participates in the mesh graph but is not the ingress apex.
32212        // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
32213        // canonical port floor, closing the "non-apex destination reads
32214        // the substrate default" arm. Same fixture the peer
32215        // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
32216        // pin at caixa-mesh exercises through the CNP emit-side path;
32217        // this pin exercises the shared underlying resolver directly.
32218        let spec = three_member_spec();
32219        assert_eq!(
32220            spec.port_for_destination("payment"),
32221            DEFAULT_SERVICO_PORT,
32222            "port_for_destination(non-apex-destination) must route \
32223             through the lifted DEFAULT_SERVICO_PORT canonical port floor"
32224        );
32225    }
32226
32227    #[test]
32228    fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
32229        // Internal-only Aplicacao — no `:entrada` block declared. Every
32230        // per-destination port query falls back to the lifted
32231        // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
32232        // the Aplicacao surface admits `:entrada None` (internal mesh
32233        // with no external gateway); every downstream renderer's per-
32234        // destination port axis must still resolve to a well-defined
32235        // scalar even without an ingress apex.
32236        let mut spec = three_member_spec();
32237        spec.entrada = None;
32238        assert_eq!(
32239            spec.port_for_destination("cart"),
32240            DEFAULT_SERVICO_PORT,
32241            "port_for_destination on an internal-only Aplicacao must \
32242             fall back to the lifted DEFAULT_SERVICO_PORT floor for \
32243             every destination"
32244        );
32245        assert_eq!(
32246            spec.port_for_destination("payment"),
32247            DEFAULT_SERVICO_PORT,
32248            "port_for_destination on an internal-only Aplicacao must \
32249             fall back uniformly across every destination — the fallback \
32250             is not entrada-shape-conditional"
32251        );
32252    }
32253
32254    #[test]
32255    fn port_for_destination_honors_non_default_entrada_port_verbatim() {
32256        // Structural pin against a hypothetical future refactor that
32257        // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
32258        // the resolver (a "normalize to the default when the author's
32259        // port matches the substrate default" collapse) — that would
32260        // break renderer sites that carry meaning on the emitted port
32261        // value beyond bare equality (a future per-cluster listener-
32262        // audit that keys off the author-declared port, not the
32263        // resolved-with-fallback port). Pin that a non-default
32264        // entrada.port is returned verbatim so drift here surfaces at
32265        // caixa-core build time.
32266        let mut spec = three_member_spec();
32267        if let Some(e) = spec.entrada.as_mut() {
32268            e.para = "cart".into();
32269            e.port = 8443;
32270        }
32271        assert_ne!(
32272            8443, DEFAULT_SERVICO_PORT,
32273            "test fixture must probe a port distinct from \
32274             DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
32275        );
32276        assert_eq!(
32277            spec.port_for_destination("cart"),
32278            8443,
32279            "port_for_destination(entrada.para) must return entrada.port \
32280             verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
32281        );
32282    }
32283
32284    #[test]
32285    fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
32286        // Apex-identity pair-invariant pin composing both substrate-
32287        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
32288        // and [`Entrada::destination`] — at the emit-side call shape
32289        // every per-Aplicacao renderer's ingress-apex L4 port reader
32290        // now takes. The invariant:
32291        //
32292        //   spec.port_for_destination(entrada.destination()) == entrada.port
32293        //
32294        // holds by construction under today's single-destination
32295        // `:entrada` slot (`destination()` returns `entrada.para`, and
32296        // the resolver's apex arm matches `para == destination` and
32297        // returns `entrada.port`), and every downstream consumer that
32298        // composes the two accessors at the ingress apex — the
32299        // `caixa_mesh::gateway_routes` HTTPRoute per-rule
32300        // `backendRefs[0].port` emit-site path, the peer future M4 CR
32301        // materializer's admission-webhook that promotes the scalar to
32302        // a per-CR override overlay, every future per-Aplicacao snapshot
32303        // renderer's apex-facing L4 port reader — reaches through the
32304        // same composition. Pin the identity across four permutations
32305        // (`:para` × `:port` including a non-default port to exercise
32306        // the honor-verbatim arm and a non-cart `:para` to exercise
32307        // destination-agnostic identity) so a future refactor that
32308        // silently split either accessor's apex behavior surfaces at
32309        // caixa-core build time — a subtle `destination()` renaming
32310        // that returned `entrada.host.as_str()` instead of
32311        // `entrada.para.as_str()` would blow this pin loudly, closing
32312        // the last quiet failure mode the two lifts admit in composition.
32313        //
32314        // Peer discipline with the sibling caixa-mesh cross-crate pin
32315        // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
32316        // on the two-renderer pair-invariant axis; this pin encodes the
32317        // same two-consumer coherence rule at the substrate-primitive
32318        // level so the invariant survives even if every renderer is
32319        // deleted.
32320        for (para, port) in [
32321            ("cart", DEFAULT_SERVICO_PORT),
32322            ("cart", 8443u16),
32323            ("payment", 9090u16),
32324            ("catalog", 443u16),
32325        ] {
32326            let mut spec = three_member_spec();
32327            if let Some(e) = spec.entrada.as_mut() {
32328                e.para = para.into();
32329                e.port = port;
32330            }
32331            let expected_port = spec
32332                .entrada()
32333                .expect("three_member_spec carries a typed `:entrada` block")
32334                .port();
32335            let composed_port = {
32336                let entrada = spec.entrada().expect("entrada present");
32337                spec.port_for_destination(entrada.destination())
32338            };
32339            assert_eq!(
32340                composed_port, expected_port,
32341                "`spec.port_for_destination(entrada.destination())` must \
32342                 equal `entrada.port` under today's single-destination \
32343                 `:entrada` slot — this is the apex-identity contract \
32344                 every downstream ingress-apex L4 port reader relies on. \
32345                 Input :entrada :para: {para:?}, :entrada :port: {port}"
32346            );
32347        }
32348    }
32349
32350    #[test]
32351    fn port_for_destination_apex_arm_routes_through_destination_accessor() {
32352        // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
32353        // per-`:entrada` apex-arm membership probe must key off
32354        // [`Entrada::destination`], not the raw `.para` field access.
32355        // Structurally: setting ONLY the `:entrada :para` field to a
32356        // fresh non-cart destination on an otherwise-well-formed
32357        // Aplicacao must (1) leave `e.destination()` byte-equal to
32358        // `e.para.as_str()` (the accessor is byte-projective by
32359        // definition), and (2) cause the resolver's apex arm to fire
32360        // and return `entrada.port` at exactly that new destination
32361        // while every other destination string falls through to
32362        // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
32363        // membership check. Pins against a future silent detour that
32364        // (a) re-derived the apex-arm membership probe off
32365        // `e.para == destination` in `port_for_destination` instead of
32366        // `e.destination() == destination`, silently disagreeing with
32367        // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
32368        // consumers (`entrada.destination()` at
32369        // caixa-mesh/src/lib.rs:3173, `c.destination()` at
32370        // caixa-mesh/src/lib.rs:2739) that already reach through the
32371        // accessor, (b) accessor-side introduced a per-tenant alias
32372        // arm the caller was unaware of, silently rewriting an
32373        // author-declared `:para "cart"` value to a canary-aliased
32374        // form — the raw-field-access resolver would fall through to
32375        // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
32376        // while the peer emit-site consumers landed on the aliased
32377        // destination, splitting the ingress-apex L4 port at
32378        // cluster-apply time.
32379        //
32380        // Peer of the sibling
32381        // [`validate_membros_empty_gate_routes_through_nome_accessor`]
32382        // (d0de220) composition pin on the per-`:membros` refusal-arm
32383        // axis — same "the shape-gate predicate must route through the
32384        // substrate-primitive typed dispatch" discipline extended onto
32385        // the per-`:entrada` apex-arm membership-probe axis. Closes
32386        // the last unlifted `.para` production-code read site on
32387        // `Entrada` in `caixa-core` — after this converge every
32388        // `caixa-core` `.para` field access outside the accessor's own
32389        // body and outside the `WitContract` per-`:contratos` sibling
32390        // axis is either a test-side field-setter or a doc-comment
32391        // reference.
32392        for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
32393            let mut spec = three_member_spec();
32394            if let Some(e) = spec.entrada.as_mut() {
32395                e.para = para.into();
32396                e.port = port;
32397            }
32398            let e = spec
32399                .entrada
32400                .as_ref()
32401                .expect("three_member_spec carries a typed `:entrada` block");
32402            assert_eq!(
32403                e.destination(),
32404                e.para.as_str(),
32405                "Entrada::destination must byte-equal the .para field \
32406                 access — an accessor-side detour that no longer \
32407                 projects the raw field would silently split this \
32408                 drift-detection test from the port_for_destination \
32409                 apex-arm membership probe",
32410            );
32411            assert_eq!(
32412                spec.port_for_destination(para),
32413                port,
32414                "port_for_destination must key off the accessor-projected \
32415                 destination and return `entrada.port` on the apex arm — \
32416                 input :entrada :para: {para:?}, :entrada :port: {port}",
32417            );
32418            assert_eq!(
32419                spec.port_for_destination("ghost-destination-never-a-member"),
32420                DEFAULT_SERVICO_PORT,
32421                "port_for_destination must fall through to \
32422                 DEFAULT_SERVICO_PORT on a non-matching destination \
32423                 under the accessor-projected membership check — input \
32424                 :entrada :para: {para:?}, :entrada :port: {port}",
32425            );
32426        }
32427    }
32428
32429    #[test]
32430    fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
32431        // The canonical per-`:politicas :rate-limit` `:rate`
32432        // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
32433        // [`RateLimit::rate`] must return the `:politicas :rate-limit`
32434        // typed `u32` verbatim, byte-equal to the raw field access
32435        // across every representative value in the accept-set — `1` (the
32436        // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
32437        // the surrounding [`AplicacaoSpec::validate_politicas`] gate
32438        // carves out on the sibling `PolicyRateLimitZero` refusal),
32439        // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
32440        // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
32441        // `0` (a past-the-guard sentinel that pins the accessor doesn't
32442        // perform a silent bounds-collapse into `1` on the zero arm —
32443        // validate rejects zero but the accessor must ship the raw slot
32444        // verbatim so a validate-time gate regression surfaces at the
32445        // emit boundary rather than being silently absorbed), `u32::MAX`
32446        // (a past-the-guard sentinel that pins the accessor doesn't
32447        // perform a silent bounds-collapse through
32448        // `POLICY_RATE_LIMIT_MAX` at the return path).
32449        //
32450        // First sub-struct required-scalar accessor pin on the
32451        // `RateLimit` axis — sibling in shape to the peer
32452        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
32453        // required-`u32` accessor pin on the peer per-sub-struct
32454        // required-axis. Pins against a future silent detour that
32455        // re-derived the token capacity from a peer axis (an accidental
32456        // `self.window.as_secs() as u32` collapse that read the
32457        // rate-limit window duration as a token count), a `0 → 1`
32458        // cluster-default projection (which would silently absorb the
32459        // `PolicyRateLimitZero` refusal case at the accessor boundary),
32460        // or a bounds-collapsing accessor that clamped the return
32461        // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
32462        // gate owns the bounds; the accessor must ship the raw slot
32463        // verbatim).
32464        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
32465            let rl = RateLimit {
32466                rate,
32467                window: Duration::from_secs(1),
32468            };
32469            assert_eq!(
32470                rl.rate(),
32471                rate,
32472                "RateLimit::rate must return :politicas :rate-limit :rate \
32473                 verbatim (got {}, expected {rate})",
32474                rl.rate(),
32475            );
32476            assert_eq!(
32477                rl.rate(),
32478                rl.rate,
32479                "RateLimit::rate must byte-equal the raw .rate field \
32480                 access across every value in the u32 accept-set",
32481            );
32482        }
32483    }
32484
32485    #[test]
32486    fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
32487        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
32488        // `:rate-limit :rate` zero-floor arm must key off
32489        // [`RateLimit::rate`], not the raw `.rate` field access.
32490        // Structurally: a `RateLimit { rate: 0, window:
32491        // Duration::from_secs(1) }` embedded in a `:politicas
32492        // :rate-limit` slot must surface the `PolicyRateLimitZero`
32493        // refusal exactly, and a `RateLimit { rate: 1, window:
32494        // Duration::from_secs(1) }` (the lower boundary of the
32495        // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
32496        // The pair jointly pins the accessor + validate-gate composition:
32497        // any future silent detour that had the accessor return a fresh
32498        // `1` on the zero arm (a `.rate().max(1)` collapse) would
32499        // silently absorb the `PolicyRateLimitZero` refusal at the
32500        // accessor boundary and the validate gate would accept a
32501        // struct-literal `RateLimit { rate: 0, .. }` — the composition
32502        // pin catches that at caixa-core build time.
32503        //
32504        // Peer of the sibling per-`CircuitBreaker`
32505        // [`CircuitBreaker::max_failures`] (3a74062) /
32506        // [`CircuitBreaker::window`] (373957f) accessor-composition
32507        // pins on the peer required-scalar axes — same "the validate /
32508        // shape-gate predicate must route through the substrate-primitive
32509        // typed dispatch" discipline extended onto the peer
32510        // per-`RateLimit` required-`u32` composition axis.
32511        let mut spec = three_member_spec();
32512        spec.politicas = MeshPolicy {
32513            rate_limit: Some(RateLimit {
32514                rate: 0,
32515                window: Duration::from_secs(1),
32516            }),
32517            ..MeshPolicy::default()
32518        };
32519        assert!(
32520            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
32521            "validate_politicas must reject rate == 0 with \
32522             PolicyRateLimitZero — the accessor and the validate gate \
32523             must route through the same substrate-primitive typed \
32524             dispatch on the :rate zero-floor arm",
32525        );
32526        spec.politicas = MeshPolicy {
32527            rate_limit: Some(RateLimit {
32528                rate: 1,
32529                window: Duration::from_secs(1),
32530            }),
32531            ..MeshPolicy::default()
32532        };
32533        assert!(
32534            spec.validate().is_ok(),
32535            "validate_politicas must accept rate == 1 (the lower \
32536             boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
32537        );
32538    }
32539
32540    #[test]
32541    fn rate_limit_rate_projects_u32_by_copy() {
32542        // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
32543        // `u32` is `Copy` and the accessor must return by value, not by
32544        // reference. Peer of the sibling per-`CircuitBreaker`
32545        // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
32546        // peer required-scalar `:max-failures` axis, extended onto the
32547        // peer per-`RateLimit` required-`u32` copy-invariant shape —
32548        // the accessor's returned `u32` must outlive `&self` (multiple
32549        // calls must return equal values from a dropped-`&self` copy,
32550        // since the returned scalar carries no borrow), and calling the
32551        // accessor twice on the same RateLimit must yield the same
32552        // `u32` verbatim (idempotent, no side effects on `&self`).
32553        //
32554        // Pins against a future silent detour that returned `&u32`
32555        // (which would type-check but silently break every downstream
32556        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
32557        // first parameter is `u32`, and `&u32` would fold to a detached
32558        // copy at the call site with a `*` deref the sibling accessors
32559        // don't need), an accidental `.rate.wrapping_add(0)` detour that
32560        // returned a fresh copy through an arithmetic no-op (breaking a
32561        // future `const fn` regression), or a one-arm-only accessor
32562        // that returned a saturating value on some sentinel input
32563        // (breaking the pass-through invariant the sibling required-
32564        // scalar accessors carry).
32565        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
32566            let rl = RateLimit {
32567                rate,
32568                window: Duration::from_secs(1),
32569            };
32570            let first = rl.rate();
32571            let second = rl.rate();
32572            assert_eq!(
32573                first, second,
32574                "RateLimit::rate must be idempotent — two successive \
32575                 calls on the same &self must return the same u32",
32576            );
32577            assert_eq!(
32578                first, rate,
32579                "RateLimit::rate must return :politicas :rate-limit :rate \
32580                 verbatim by copy — got {first}, expected {rate}",
32581            );
32582        }
32583    }
32584
32585    #[test]
32586    fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
32587        // The canonical per-`:politicas :rate-limit` `:window`
32588        // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
32589        // pin: [`RateLimit::window`] must return the
32590        // `:politicas :rate-limit :window` typed `Duration` verbatim,
32591        // byte-equal to the raw field access across every
32592        // representative value in the accept-set — `Duration::from_secs(1)`
32593        // (the `"s"` canonical window, the lower row of
32594        // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
32595        // [`AplicacaoSpec::validate_politicas`] gate accepts via
32596        // [`is_canonical_rate_limit_window`]),
32597        // `Duration::from_secs(60)` (the `"m"` canonical window, the
32598        // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
32599        // window, the upper row), `Duration::ZERO` (a past-the-guard
32600        // sentinel that pins the accessor doesn't perform a silent
32601        // bounds-collapse into `Duration::from_secs(1)` on the zero
32602        // arm — validate rejects an off-set window through
32603        // `PolicyRateLimitWindowNotCanonical` but the accessor must
32604        // ship the raw slot verbatim so a validate-time gate
32605        // regression surfaces at the emit boundary rather than being
32606        // silently absorbed), `Duration::from_millis(500)` (a
32607        // sub-canonical past-the-guard sentinel that pins the accessor
32608        // doesn't silently normalize a non-canonical fractional
32609        // magnitude onto the nearest canonical row).
32610        //
32611        // Second sub-struct required-scalar accessor pin on the
32612        // `RateLimit` axis — sibling in shape to the just-landed
32613        // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
32614        // accessor pin on the peer per-sub-struct required-axis,
32615        // extended onto the per-`RateLimit` required-`Duration` axis.
32616        // Pins against a future silent detour that re-derived the
32617        // refill period from a peer axis (an accidental
32618        // `Duration::from_secs(self.rate as u64)` collapse that read
32619        // the rate-limit token capacity as a refill-interval
32620        // duration), a `Duration::ZERO → Duration::from_secs(1)`
32621        // canonical-default projection (which would silently absorb
32622        // the `PolicyRateLimitWindowNotCanonical` refusal case at the
32623        // accessor boundary), or a canonical-set-collapsing accessor
32624        // that clamped the return through [`rate_limit_window_unit`]
32625        // (the `AplicacaoSpec::validate` gate owns the canonical-set
32626        // membership; the accessor must ship the raw slot verbatim).
32627        for window in [
32628            Duration::from_secs(1),
32629            Duration::from_secs(60),
32630            Duration::from_secs(3600),
32631            Duration::ZERO,
32632            Duration::from_millis(500),
32633        ] {
32634            let rl = RateLimit { rate: 100, window };
32635            assert_eq!(
32636                rl.window(),
32637                window,
32638                "RateLimit::window must return :politicas :rate-limit :window \
32639                 verbatim (got {:?}, expected {window:?})",
32640                rl.window(),
32641            );
32642            assert_eq!(
32643                rl.window(),
32644                rl.window,
32645                "RateLimit::window must byte-equal the raw .window field \
32646                 access across every value in the Duration accept-set",
32647            );
32648        }
32649    }
32650
32651    #[test]
32652    fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
32653        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
32654        // `:rate-limit :window` canonical-set arm must key off
32655        // [`RateLimit::window`], not the raw `.window` field access.
32656        // Structurally: a `RateLimit { window: Duration::from_millis(500),
32657        // .. }` embedded in a `:politicas :rate-limit` slot must
32658        // surface the `PolicyRateLimitWindowNotCanonical` refusal
32659        // exactly (with the sub-canonical `Duration::from_millis(500)`
32660        // magnitude carried through verbatim), and a `RateLimit
32661        // { window: Duration::from_secs(1), .. }` (the lower row of
32662        // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
32663        // The pair jointly pins the accessor + validate-gate
32664        // composition: any future silent detour that had the accessor
32665        // normalize the off-set window to the nearest canonical row
32666        // (a `.window().max(Duration::from_secs(1))` collapse, or a
32667        // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
32668        // collapse) would silently absorb the
32669        // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
32670        // boundary — including a drift in the error's `window` payload
32671        // (the emit-side diagnostic reader keys off the offending
32672        // magnitude verbatim, so a normalization at the accessor
32673        // boundary would silently pin the wrong magnitude in the
32674        // refusal). The composition pin catches that at caixa-core
32675        // build time.
32676        //
32677        // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
32678        // (7f81a60) accessor-composition pin on the peer required-
32679        // scalar `:rate` axis — same "the validate / shape-gate
32680        // predicate must route through the substrate-primitive typed
32681        // dispatch, and the error payload must project through the
32682        // same accessor" discipline extended onto the peer
32683        // per-`RateLimit` required-`Duration` composition axis.
32684        let mut spec = three_member_spec();
32685        spec.politicas = MeshPolicy {
32686            rate_limit: Some(RateLimit {
32687                rate: 100,
32688                window: Duration::from_millis(500),
32689            }),
32690            ..MeshPolicy::default()
32691        };
32692        match spec.validate() {
32693            Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
32694                assert_eq!(
32695                    window,
32696                    Duration::from_millis(500),
32697                    "PolicyRateLimitWindowNotCanonical must carry the \
32698                     offending :window magnitude verbatim through the \
32699                     accessor — got {window:?}, expected 500ms",
32700                );
32701            }
32702            other => panic!(
32703                "validate_politicas must reject non-canonical :window \
32704                 with PolicyRateLimitWindowNotCanonical — the accessor \
32705                 and the validate gate must route through the same \
32706                 substrate-primitive typed dispatch on the :window \
32707                 canonical-set arm; got {other:?}",
32708            ),
32709        }
32710        spec.politicas = MeshPolicy {
32711            rate_limit: Some(RateLimit {
32712                rate: 100,
32713                window: Duration::from_secs(1),
32714            }),
32715            ..MeshPolicy::default()
32716        };
32717        assert!(
32718            spec.validate().is_ok(),
32719            "validate_politicas must accept window == Duration::from_secs(1) \
32720             (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
32721        );
32722    }
32723
32724    #[test]
32725    fn rate_limit_window_projects_duration_by_copy() {
32726        // The by-copy pin: [`RateLimit::window`] returns `Duration`
32727        // by copy — `Duration` is `Copy` and the accessor must return
32728        // by value, not by reference. Peer of the sibling per-`RateLimit`
32729        // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
32730        // required-scalar `:rate` axis, extended onto the peer
32731        // per-`RateLimit` required-`Duration` copy-invariant shape —
32732        // the accessor's returned `Duration` must outlive `&self`
32733        // (multiple calls must return equal values from a
32734        // dropped-`&self` copy, since the returned scalar carries no
32735        // borrow), and calling the accessor twice on the same
32736        // RateLimit must yield the same `Duration` verbatim
32737        // (idempotent, no side effects on `&self`).
32738        //
32739        // Pins against a future silent detour that returned
32740        // `&Duration` (which would type-check but silently break every
32741        // downstream `Duration`-by-value consumer —
32742        // [`is_canonical_rate_limit_window`]'s first parameter is
32743        // `Duration`, and `&Duration` would fold to a detached copy at
32744        // the call site with a `*` deref the sibling accessors don't
32745        // need), an accidental `.window + Duration::ZERO` detour that
32746        // returned a fresh copy through an arithmetic no-op (breaking
32747        // a future `const fn` regression), or a one-arm-only accessor
32748        // that returned a canonical fallback on some sentinel input
32749        // (breaking the pass-through invariant the sibling required-
32750        // scalar accessors carry).
32751        for window in [
32752            Duration::from_secs(1),
32753            Duration::from_secs(60),
32754            Duration::from_secs(3600),
32755            Duration::ZERO,
32756            Duration::from_millis(500),
32757        ] {
32758            let rl = RateLimit { rate: 100, window };
32759            let first = rl.window();
32760            let second = rl.window();
32761            assert_eq!(
32762                first, second,
32763                "RateLimit::window must be idempotent — two successive \
32764                 calls on the same &self must return the same Duration",
32765            );
32766            assert_eq!(
32767                first, window,
32768                "RateLimit::window must return :politicas :rate-limit :window \
32769                 verbatim by copy — got {first:?}, expected {window:?}",
32770            );
32771        }
32772    }
32773
32774    #[test]
32775    fn placement_estrategia_default_pins_m3_canonical_value() {
32776        // Pin [`PLACEMENT_ESTRATEGIA_DEFAULT`] at
32777        // [`PlacementStrategy::Replicated`] — MESH-COMPOSITION §II.2's
32778        // active-active-across-every-named-cluster arm, the closest
32779        // canonical M3 production reference the substrate carries and
32780        // the arm the caixa-mesh `programs.yaml` fan-out already keys off
32781        // for every un-`:placement`-declared Aplicacao. Pinning the arm
32782        // here surfaces a future rebrand of the M3-canonical
32783        // distribution default (a widening to `Sharded` once the
32784        // substrate discovers hash-keyed distribution as the more
32785        // common production shape, a tightening to `SingleNode` for
32786        // stateful Erlang/OTP distributed-app-takeover semantics
32787        // MESH-COMPOSITION §II.1 names, a per-cluster overlay the
32788        // operator pins through a future `:placement-overrides` slot)
32789        // as a deliberate test edit, not a silent contract migration.
32790        // Peer of the sibling M2 per-supervisor value pins
32791        // [`crate::supervisor::tests::supervisor_estrategia_default_pins_otp_canonical_value`]
32792        // /
32793        // [`crate::supervisor::tests::supervisor_child_restart_default_pins_otp_canonical_value`]
32794        // extended onto the M3 mesh-primitive-defining `:placement
32795        // :estrategia` axis.
32796        assert_eq!(PLACEMENT_ESTRATEGIA_DEFAULT, PlacementStrategy::Replicated);
32797    }
32798
32799    #[test]
32800    fn placement_strategy_default_routes_through_lifted_default() {
32801        // Composition pin: the [`Default for PlacementStrategy`] impl's
32802        // return arm must route through the substrate-canonical
32803        // [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
32804        // a raw `Self::Replicated` arm. Prior to the lift the impl
32805        // carried an inline `Self::Replicated` arm with no compile-time
32806        // link back to the shared M3-canonical `Replicated` arm the
32807        // paired [`Default for Placement`] impl's struct-literal
32808        // `estrategia` field, the serde-side `#[serde(default)]` on
32809        // [`Placement::estrategia`] that resolves an author-omitted
32810        // wire-form `:placement :estrategia` scalar through the impl,
32811        // and the [`crate::manifest::Caixa::aplicacao_view`] fold's
32812        // `.unwrap_or_default()` `Option<Placement>` collapse arm (which
32813        // routes through [`Placement::default`] which routes through the
32814        // strategy default) all key off — so a future rebrand of the
32815        // M3-canonical distribution default would have had to be threaded
32816        // through the `Default` impl and the three peer routes in
32817        // lockstep or the four consumers would silently split. Byte-
32818        // parity against the lifted constant closes the split. Peer of
32819        // the sibling
32820        // [`crate::supervisor::tests::restart_strategy_default_routes_through_lifted_default`]
32821        // /
32822        // [`crate::supervisor::tests::restart_policy_default_routes_through_lifted_default`]
32823        // composition pins on the M2 per-supervisor axes.
32824        assert_eq!(PlacementStrategy::default(), PLACEMENT_ESTRATEGIA_DEFAULT);
32825    }
32826
32827    #[test]
32828    fn placement_default_estrategia_routes_through_lifted_default() {
32829        // Composition pin: the [`Default for Placement`] impl's
32830        // struct-literal `estrategia` field must route through the
32831        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
32832        // `pub const` (either directly, or via the [`PlacementStrategy::default`]
32833        // impl that the sibling
32834        // `placement_strategy_default_routes_through_lifted_default` pin
32835        // already routes onto the constant). Structurally: every
32836        // `Placement::default()` call must yield an `estrategia` field
32837        // byte-equal to the lifted constant so the two paired defaults —
32838        // the [`Default for PlacementStrategy`] impl arm and the
32839        // struct-literal default arm here — cannot silently split on any
32840        // future M3-canonical distribution-default rebrand. Peer of the
32841        // sibling M2
32842        // [`crate::supervisor::tests::supervisor_spec_default_estrategia_routes_through_lifted_default`]
32843        // byte-parity pin on the [`Default for SupervisorSpec`]
32844        // struct-literal `estrategia` field extended onto the M3
32845        // mesh-primitive-defining slot family.
32846        assert_eq!(
32847            Placement::default().estrategia,
32848            PLACEMENT_ESTRATEGIA_DEFAULT,
32849        );
32850    }
32851
32852    #[test]
32853    fn placement_serde_default_estrategia_routes_through_lifted_default() {
32854        // Composition pin: the serde-side `#[serde(default)]` on
32855        // [`Placement::estrategia`] — the wire-format author-omitted
32856        // `:placement :estrategia` arm — must resolve onto the substrate-
32857        // canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const`
32858        // (via the [`Default for PlacementStrategy`] impl the sibling
32859        // `placement_strategy_default_routes_through_lifted_default` pin
32860        // already routes onto the constant). Structurally: a `Placement`
32861        // deserialized from a payload that omits the `estrategia` key
32862        // must yield an `estrategia` field byte-equal to the lifted
32863        // constant, so the wire-format author-omitted arm and the
32864        // [`PlacementStrategy::default`] impl arm cannot silently split
32865        // on any future M3-canonical distribution-default rebrand. Peer
32866        // of the sibling M2
32867        // [`crate::supervisor::tests::child_spec_serde_default_restart_routes_through_lifted_default`]
32868        // byte-parity pin on the wire-format author-omitted `:children
32869        // :restart` scalar extended onto the M3 mesh-primitive-defining
32870        // slot family.
32871        let omitted: Placement = serde_json::from_str("{}")
32872            .expect("Placement must deserialize with the estrategia key omitted");
32873        assert_eq!(
32874            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
32875            "an author-omitted :placement :estrategia slot must degrade onto \
32876             the PLACEMENT_ESTRATEGIA_DEFAULT typed pub const (got \
32877             {:?}, expected {:?})",
32878            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
32879        );
32880    }
32881
32882    // ── contrato_target_ctors! fold pins ────────────────────────────────
32883    //
32884    // Fixture edge triple + payload-field-name label pair for every
32885    // `contrato_target_ctors!`-generated ctor pin below. Kept as
32886    // non-default `("cart", "catalog", "wasi:http/proxy")` +
32887    // `WitTarget::HTTP_FIELD_NAME` so a byte-equality mistake against
32888    // the fixture default doesn't silently pass. Peer of the sibling
32889    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
32890    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
32891    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
32892    // `missing_entry_ctor_matches_struct_literal_wrap` /
32893    // `<slot>_ctor_matches_tuple_literal_wrap` equivalence pins on the
32894    // four `LayoutError` constructor families each closed on their
32895    // sibling envelopes.
32896    fn contrato_target_ctor_fixture() -> (String, String, String, &'static str) {
32897        (
32898            "cart".to_string(),
32899            "catalog".to_string(),
32900            "wasi:http/proxy".to_string(),
32901            WitTarget::HTTP_FIELD_NAME,
32902        )
32903    }
32904
32905    #[test]
32906    fn contrato_wrong_target_ctor_matches_struct_literal_wrap() {
32907        // Equivalence pin: the ctor produces byte-equal
32908        // `AplicacaoError::ContratoWrongTarget` to the pre-lift open-
32909        // coded struct-literal on the same edge fixture, so the fold
32910        // cannot silently drift on any future field-addition /
32911        // reordering / string-conversion tweak on the variant. Peer of
32912        // the sibling `entrada_host_invalid_ctor_matches_struct_literal_wrap`
32913        // (17dd504) / the four `LayoutError` family equivalence pins.
32914        let (de, para, wit, expected) = contrato_target_ctor_fixture();
32915        let lifted = AplicacaoError::contrato_wrong_target(
32916            (de.clone(), para.clone(), wit.clone()),
32917            expected,
32918        );
32919        let struct_literal = AplicacaoError::ContratoWrongTarget {
32920            de,
32921            para,
32922            wit,
32923            expected,
32924        };
32925        assert_eq!(lifted, struct_literal);
32926    }
32927
32928    #[test]
32929    fn contrato_missing_target_ctor_matches_struct_literal_wrap() {
32930        // Equivalence pin peer of the sibling
32931        // `contrato_wrong_target_ctor_matches_struct_literal_wrap` above
32932        // on the paired `ContratoMissingTarget` variant of the same
32933        // four-slot envelope shape the `contrato_target_ctors!` macro
32934        // closes.
32935        let (de, para, wit, expected) = contrato_target_ctor_fixture();
32936        let lifted = AplicacaoError::contrato_missing_target(
32937            (de.clone(), para.clone(), wit.clone()),
32938            expected,
32939        );
32940        let struct_literal = AplicacaoError::ContratoMissingTarget {
32941            de,
32942            para,
32943            wit,
32944            expected,
32945        };
32946        assert_eq!(lifted, struct_literal);
32947    }
32948
32949    #[test]
32950    fn contrato_target_ctors_route_edge_triple_through_verbatim() {
32951        // Routing pin: the `(de, para, wit)` triple threads verbatim
32952        // onto same-named fields on both generated ctors, no wrapper-
32953        // side lowercase / trim / re-order. Sweeps a non-default triple
32954        // (`"cart-svc" → "catalog-v2"`, `"nats:pub-sub"`) so any
32955        // wrapper-side transformation surfaces here rather than at a
32956        // downstream diagnostic-shape drift. Sibling of
32957        // `entrada_host_invalid_ctor_routes_host_through_to_string`
32958        // (17dd504) on the paired triple-carrying envelope.
32959        let edge = (
32960            "cart-svc".to_string(),
32961            "catalog-v2".to_string(),
32962            "nats:pub-sub".to_string(),
32963        );
32964        let wrong =
32965            AplicacaoError::contrato_wrong_target(edge.clone(), WitTarget::PUBSUB_FIELD_NAME);
32966        let missing = AplicacaoError::contrato_missing_target(edge, WitTarget::PUBSUB_FIELD_NAME);
32967        let AplicacaoError::ContratoWrongTarget {
32968            de: wde,
32969            para: wpara,
32970            wit: wwit,
32971            ..
32972        } = wrong
32973        else {
32974            panic!("contrato_wrong_target must construct the ContratoWrongTarget variant");
32975        };
32976        let AplicacaoError::ContratoMissingTarget {
32977            de: mde,
32978            para: mpara,
32979            wit: mwit,
32980            ..
32981        } = missing
32982        else {
32983            panic!("contrato_missing_target must construct the ContratoMissingTarget variant");
32984        };
32985        assert_eq!(wde, "cart-svc");
32986        assert_eq!(wpara, "catalog-v2");
32987        assert_eq!(wwit, "nats:pub-sub");
32988        assert_eq!(mde, "cart-svc");
32989        assert_eq!(mpara, "catalog-v2");
32990        assert_eq!(mwit, "nats:pub-sub");
32991    }
32992
32993    #[test]
32994    fn contrato_target_ctors_route_expected_through_verbatim() {
32995        // Routing pin: the `expected: &'static str` label threads
32996        // verbatim (identity, not copy-and-transform) onto the
32997        // `expected` field of both variants, so the four canonical
32998        // labels [`WitTarget::HTTP_FIELD_NAME`] /
32999        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
33000        // / [`WitTarget::CAPABILITY_EXPECTED`] survive the fold as
33001        // pointer-equal (not merely value-equal) references — a wrapper-
33002        // side `.to_string()` / `Cow::Owned` promotion would break the
33003        // `&'static str` contract downstream consumers depend on.
33004        for label in [
33005            WitTarget::HTTP_FIELD_NAME,
33006            WitTarget::PUBSUB_FIELD_NAME,
33007            WitTarget::STORE_FIELD_NAME,
33008            WitTarget::CAPABILITY_EXPECTED,
33009        ] {
33010            let (de, para, wit, _) = contrato_target_ctor_fixture();
33011            let wrong = AplicacaoError::contrato_wrong_target(
33012                (de.clone(), para.clone(), wit.clone()),
33013                label,
33014            );
33015            let missing = AplicacaoError::contrato_missing_target((de, para, wit), label);
33016            match wrong {
33017                AplicacaoError::ContratoWrongTarget { expected, .. } => {
33018                    assert!(
33019                        std::ptr::eq(expected.as_ptr(), label.as_ptr())
33020                            && expected.len() == label.len(),
33021                        "contrato_wrong_target must thread the &'static str \
33022                         label pointer-equal onto the `expected` field \
33023                         (label = {label:?})",
33024                    );
33025                }
33026                other => panic!("expected ContratoWrongTarget, got {other:?}"),
33027            }
33028            match missing {
33029                AplicacaoError::ContratoMissingTarget { expected, .. } => {
33030                    assert!(
33031                        std::ptr::eq(expected.as_ptr(), label.as_ptr())
33032                            && expected.len() == label.len(),
33033                        "contrato_missing_target must thread the &'static \
33034                         str label pointer-equal onto the `expected` field \
33035                         (label = {label:?})",
33036                    );
33037                }
33038                other => panic!("expected ContratoMissingTarget, got {other:?}"),
33039            }
33040        }
33041    }
33042
33043    // ── contrato_empty_pair_ctors! fold pins ────────────────────────────
33044    //
33045    // Fixture edge pair for every `contrato_empty_pair_ctors!`-generated
33046    // ctor pin below. Kept as non-default `("cart", "catalog")` so a
33047    // byte-equality mistake against the fixture default doesn't silently
33048    // pass. Peer of the sibling `contrato_target_ctor_fixture` (14b81d5,
33049    // triple + expected-label envelope on
33050    // `contrato_target_ctors!`) / `entrada_host_invalid_ctor_matches_
33051    // struct_literal_wrap` (17dd504, host + reason envelope on
33052    // `entrada_host_invalid`) / the four `LayoutError` family
33053    // equivalence pins.
33054    fn contrato_empty_pair_ctor_fixture() -> (String, String) {
33055        ("cart".to_string(), "catalog".to_string())
33056    }
33057
33058    #[test]
33059    fn empty_wit_ctor_matches_struct_literal_wrap() {
33060        // Equivalence pin: the ctor produces byte-equal
33061        // `AplicacaoError::EmptyWit` to the pre-lift open-coded
33062        // struct-literal on the same edge pair, so the fold cannot
33063        // silently drift on any future field-addition / reordering /
33064        // string-conversion tweak on the variant. Peer of the sibling
33065        // `contrato_wrong_target_ctor_matches_struct_literal_wrap`
33066        // (14b81d5) / `entrada_host_invalid_ctor_matches_struct_literal_wrap`
33067        // (17dd504) / the four `LayoutError` family equivalence pins.
33068        let (de, para) = contrato_empty_pair_ctor_fixture();
33069        let lifted = AplicacaoError::empty_wit((de.clone(), para.clone()));
33070        let struct_literal = AplicacaoError::EmptyWit { de, para };
33071        assert_eq!(lifted, struct_literal);
33072    }
33073
33074    #[test]
33075    fn contrato_endpoint_empty_ctor_matches_struct_literal_wrap() {
33076        // Equivalence pin peer of the sibling
33077        // `empty_wit_ctor_matches_struct_literal_wrap` above on the
33078        // paired `ContratoEndpointEmpty` variant of the same two-slot
33079        // envelope shape the `contrato_empty_pair_ctors!` macro closes.
33080        let (de, para) = contrato_empty_pair_ctor_fixture();
33081        let lifted = AplicacaoError::contrato_endpoint_empty((de.clone(), para.clone()));
33082        let struct_literal = AplicacaoError::ContratoEndpointEmpty { de, para };
33083        assert_eq!(lifted, struct_literal);
33084    }
33085
33086    #[test]
33087    fn contrato_subject_empty_ctor_matches_struct_literal_wrap() {
33088        // Equivalence pin peer of the sibling
33089        // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
33090        // above on the paired `ContratoSubjectEmpty` variant of the
33091        // same two-slot envelope shape.
33092        let (de, para) = contrato_empty_pair_ctor_fixture();
33093        let lifted = AplicacaoError::contrato_subject_empty((de.clone(), para.clone()));
33094        let struct_literal = AplicacaoError::ContratoSubjectEmpty { de, para };
33095        assert_eq!(lifted, struct_literal);
33096    }
33097
33098    #[test]
33099    fn contrato_slot_empty_ctor_matches_struct_literal_wrap() {
33100        // Equivalence pin peer of the sibling
33101        // `contrato_subject_empty_ctor_matches_struct_literal_wrap`
33102        // above on the paired `ContratoSlotEmpty` variant of the same
33103        // two-slot envelope shape.
33104        let (de, para) = contrato_empty_pair_ctor_fixture();
33105        let lifted = AplicacaoError::contrato_slot_empty((de.clone(), para.clone()));
33106        let struct_literal = AplicacaoError::ContratoSlotEmpty { de, para };
33107        assert_eq!(lifted, struct_literal);
33108    }
33109
33110    #[test]
33111    fn contrato_empty_pair_ctors_route_edge_pair_through_verbatim() {
33112        // Routing pin: the `(de, para)` pair threads verbatim onto
33113        // same-named fields on all four generated ctors, no wrapper-
33114        // side lowercase / trim / re-order. Sweeps a non-default pair
33115        // (`"cart-svc" → "catalog-v2"`) so any wrapper-side
33116        // transformation surfaces here rather than at a downstream
33117        // diagnostic-shape drift. Sibling of
33118        // `contrato_target_ctors_route_edge_triple_through_verbatim`
33119        // (14b81d5) on the paired triple-carrying envelope and of
33120        // `entrada_host_invalid_ctor_routes_host_through_to_string`
33121        // (17dd504) on the sibling `{ host, reason }` envelope.
33122        let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
33123        let variants: [(AplicacaoError, &'static str); 4] = [
33124            (AplicacaoError::empty_wit(edge.clone()), "EmptyWit"),
33125            (
33126                AplicacaoError::contrato_endpoint_empty(edge.clone()),
33127                "ContratoEndpointEmpty",
33128            ),
33129            (
33130                AplicacaoError::contrato_subject_empty(edge.clone()),
33131                "ContratoSubjectEmpty",
33132            ),
33133            (
33134                AplicacaoError::contrato_slot_empty(edge.clone()),
33135                "ContratoSlotEmpty",
33136            ),
33137        ];
33138        for (built, label) in variants {
33139            let (de, para) = match built {
33140                AplicacaoError::EmptyWit { de, para }
33141                | AplicacaoError::ContratoEndpointEmpty { de, para }
33142                | AplicacaoError::ContratoSubjectEmpty { de, para }
33143                | AplicacaoError::ContratoSlotEmpty { de, para } => (de, para),
33144                other => panic!("expected {label} pair variant, got {other:?}"),
33145            };
33146            assert_eq!(de, "cart-svc", "de field on {label} must thread verbatim");
33147            assert_eq!(
33148                para, "catalog-v2",
33149                "para field on {label} must thread verbatim",
33150            );
33151        }
33152    }
33153
33154    // ── contrato_pair_value_reason_ctors! fold pins ─────────────────────
33155    //
33156    // Fixture edge pair + value + reason for every
33157    // `contrato_pair_value_reason_ctors!`-generated ctor pin below. Kept
33158    // as non-default `("cart", "catalog")` on the `(de, para)` pair and
33159    // fixed per-axis `<val>` / reason so a byte-equality mistake against
33160    // the fixture default doesn't silently pass. Peer of the sibling
33161    // `contrato_empty_pair_ctor_fixture` (8580068, pair-only envelope on
33162    // `contrato_empty_pair_ctors!`) / `contrato_target_ctor_fixture`
33163    // (14b81d5, triple + expected-label envelope on
33164    // `contrato_target_ctors!`) / `entrada_host_invalid_ctor_matches_
33165    // struct_literal_wrap` (17dd504, host + reason envelope on
33166    // `entrada_host_invalid`).
33167    fn contrato_pair_value_reason_ctor_fixture() -> (String, String) {
33168        ("cart".to_string(), "catalog".to_string())
33169    }
33170
33171    #[test]
33172    fn contrato_endpoint_invalid_ctor_matches_struct_literal_wrap() {
33173        // Equivalence pin: the ctor produces byte-equal
33174        // `AplicacaoError::ContratoEndpointInvalid` to the pre-lift
33175        // open-coded struct-literal on the same
33176        // `(edge_pair, endpoint, reason)` triple, so the fold cannot
33177        // silently drift on any future field-addition / reordering /
33178        // string-conversion tweak on the variant. Peer of the sibling
33179        // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
33180        // (8580068) on the paired two-slot envelope of the same
33181        // `{ de, para, ... }` prefix, and of
33182        // `entrada_host_invalid_ctor_matches_struct_literal_wrap`
33183        // (17dd504) on the sibling `{ <field>: String, reason: String }`
33184        // two-slot envelope.
33185        let (de, para) = contrato_pair_value_reason_ctor_fixture();
33186        let endpoint = "/charge";
33187        let reason = "sample reason text";
33188        let lifted =
33189            AplicacaoError::contrato_endpoint_invalid((de.clone(), para.clone()), endpoint, reason);
33190        let struct_literal = AplicacaoError::ContratoEndpointInvalid {
33191            de,
33192            para,
33193            endpoint: endpoint.to_string(),
33194            reason: reason.to_string(),
33195        };
33196        assert_eq!(lifted, struct_literal);
33197    }
33198
33199    #[test]
33200    fn contrato_subject_invalid_ctor_matches_struct_literal_wrap() {
33201        // Equivalence pin peer of the sibling
33202        // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap`
33203        // above on the paired `ContratoSubjectInvalid` variant of the
33204        // same four-slot envelope shape the
33205        // `contrato_pair_value_reason_ctors!` macro closes.
33206        let (de, para) = contrato_pair_value_reason_ctor_fixture();
33207        let subject = "checkout.events.charge.failed";
33208        let reason = "sample reason text";
33209        let lifted =
33210            AplicacaoError::contrato_subject_invalid((de.clone(), para.clone()), subject, reason);
33211        let struct_literal = AplicacaoError::ContratoSubjectInvalid {
33212            de,
33213            para,
33214            subject: subject.to_string(),
33215            reason: reason.to_string(),
33216        };
33217        assert_eq!(lifted, struct_literal);
33218    }
33219
33220    #[test]
33221    fn contrato_slot_invalid_ctor_matches_struct_literal_wrap() {
33222        // Equivalence pin peer of the sibling
33223        // `contrato_subject_invalid_ctor_matches_struct_literal_wrap`
33224        // above on the paired `ContratoSlotInvalid` variant of the same
33225        // four-slot envelope shape.
33226        let (de, para) = contrato_pair_value_reason_ctor_fixture();
33227        let slot = "checkout/$orderId";
33228        let reason = "sample reason text";
33229        let lifted =
33230            AplicacaoError::contrato_slot_invalid((de.clone(), para.clone()), slot, reason);
33231        let struct_literal = AplicacaoError::ContratoSlotInvalid {
33232            de,
33233            para,
33234            slot: slot.to_string(),
33235            reason: reason.to_string(),
33236        };
33237        assert_eq!(lifted, struct_literal);
33238    }
33239
33240    #[test]
33241    fn contrato_wit_invalid_ctor_matches_struct_literal_wrap() {
33242        // Equivalence pin peer of the sibling
33243        // `contrato_slot_invalid_ctor_matches_struct_literal_wrap` above
33244        // on the paired `ContratoWitInvalid` variant of the same four-
33245        // slot envelope shape the `contrato_pair_value_reason_ctors!`
33246        // macro closes. Fold pinned this test lands with the last
33247        // `{ de, para, <field>: String, reason: String }` open-coded
33248        // struct-literal inside [`WitContract::target`] rewritten to
33249        // route through the macro-generated
33250        // [`AplicacaoError::contrato_wit_invalid`] ctor — a byte-mismatch
33251        // between the ctor and the pre-lift struct-literal trips this
33252        // pin ahead of any downstream diagnostic-shape drift on the
33253        // `:contratos :wit` axis.
33254        let (de, para) = contrato_pair_value_reason_ctor_fixture();
33255        let wit = "wasi-http/proxy";
33256        let reason = "sample reason text";
33257        let lifted = AplicacaoError::contrato_wit_invalid((de.clone(), para.clone()), wit, reason);
33258        let struct_literal = AplicacaoError::ContratoWitInvalid {
33259            de,
33260            para,
33261            wit: wit.to_string(),
33262            reason: reason.to_string(),
33263        };
33264        assert_eq!(lifted, struct_literal);
33265    }
33266
33267    #[test]
33268    fn contrato_pair_value_reason_ctors_route_edge_pair_through_verbatim() {
33269        // Routing pin: the `(de, para)` pair threads verbatim onto
33270        // same-named fields on all four generated ctors, no wrapper-
33271        // side lowercase / trim / re-order. Sweeps a non-default pair
33272        // (`"cart-svc" → "catalog-v2"`) so any wrapper-side
33273        // transformation surfaces here rather than at a downstream
33274        // diagnostic-shape drift. Sibling of
33275        // `contrato_empty_pair_ctors_route_edge_pair_through_verbatim`
33276        // (8580068) on the paired two-slot envelope and of
33277        // `contrato_target_ctors_route_edge_triple_through_verbatim`
33278        // (14b81d5) on the paired triple-carrying envelope.
33279        let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
33280        let variants: [(AplicacaoError, &'static str); 4] = [
33281            (
33282                AplicacaoError::contrato_endpoint_invalid(edge.clone(), "/x", "r"),
33283                "ContratoEndpointInvalid",
33284            ),
33285            (
33286                AplicacaoError::contrato_subject_invalid(edge.clone(), "x.y", "r"),
33287                "ContratoSubjectInvalid",
33288            ),
33289            (
33290                AplicacaoError::contrato_slot_invalid(edge.clone(), "x/y", "r"),
33291                "ContratoSlotInvalid",
33292            ),
33293            (
33294                AplicacaoError::contrato_wit_invalid(edge.clone(), "wasi:http/proxy", "r"),
33295                "ContratoWitInvalid",
33296            ),
33297        ];
33298        for (built, label) in variants {
33299            let (de, para) = match built {
33300                AplicacaoError::ContratoEndpointInvalid { de, para, .. }
33301                | AplicacaoError::ContratoSubjectInvalid { de, para, .. }
33302                | AplicacaoError::ContratoSlotInvalid { de, para, .. }
33303                | AplicacaoError::ContratoWitInvalid { de, para, .. } => (de, para),
33304                other => panic!("expected {label} pair variant, got {other:?}"),
33305            };
33306            assert_eq!(de, "cart-svc", "de field on {label} must thread verbatim");
33307            assert_eq!(
33308                para, "catalog-v2",
33309                "para field on {label} must thread verbatim",
33310            );
33311        }
33312    }
33313
33314    #[test]
33315    fn contrato_pair_value_reason_ctors_route_reason_through_into_uniformly() {
33316        // Cross-arm invariance pin — the four ctors all route
33317        // `reason: impl Into<String>` verbatim onto their respective
33318        // typed variants through the shared
33319        // [`contrato_pair_value_reason_ctors!`] macro. Sweeps a fixture
33320        // pair (`&str` literal, `format!` output) against every ctor to
33321        // pin that no per-arm wrapper transformation drifted in against
33322        // the uniform macro-generated body. Peer of
33323        // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
33324        // (981060b) on the sibling two-slot envelope's cross-arm sweep.
33325        let edge = || ("cart".to_string(), "catalog".to_string());
33326        let via_literal = "literal reason text";
33327        let via_format = format!("{} reason text", "literal");
33328        assert_eq!(
33329            AplicacaoError::contrato_endpoint_invalid(edge(), "/e", via_literal),
33330            AplicacaoError::contrato_endpoint_invalid(edge(), "/e", via_format.clone()),
33331        );
33332        assert_eq!(
33333            AplicacaoError::contrato_subject_invalid(edge(), "s.t", via_literal),
33334            AplicacaoError::contrato_subject_invalid(edge(), "s.t", via_format.clone()),
33335        );
33336        assert_eq!(
33337            AplicacaoError::contrato_slot_invalid(edge(), "k/v", via_literal),
33338            AplicacaoError::contrato_slot_invalid(edge(), "k/v", via_format.clone()),
33339        );
33340        assert_eq!(
33341            AplicacaoError::contrato_wit_invalid(edge(), "wasi:http/proxy", via_literal),
33342            AplicacaoError::contrato_wit_invalid(edge(), "wasi:http/proxy", via_format),
33343        );
33344    }
33345
33346    // ── contrato_endpoint_not_absolute standalone ctor pins ─────────────
33347    //
33348    // Fail-before-pass-after pins for the standalone
33349    // [`AplicacaoError::contrato_endpoint_not_absolute`] inherent ctor
33350    // (see the paired doc-block above the ctor definition) — the fold of
33351    // the last open-coded three-slot `{ de, para, endpoint: <val>
33352    // .to_string() }` struct-literal inside [`WitContract::target`]'s
33353    // HTTP-arm leading-slash gate onto one substrate primitive on the
33354    // envelope. A byte-mismatched ctor body would trip the equivalence
33355    // pin first, ahead of any downstream diagnostic-shape drift.
33356    //
33357    // Peer of the sibling standalone-ctor equivalence pins on the peer
33358    // one-off variants across caixa-core:
33359    // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap` +
33360    // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap` above
33361    // on the paired two-slot and four-slot per-`:contratos :endpoint`
33362    // envelopes; `child_caixa_invalid_ctor_matches_struct_literal_wrap`
33363    // and `child_versao_invalid_ctor_matches_struct_literal_wrap`
33364    // (d2ef2ec) on the sibling `SupervisorError` `{ caixa, [versao,]
33365    // reason }` two- and three-slot envelopes; the
33366    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` (17dd504)
33367    // pin on the sibling standalone `{ host, reason }` two-slot ctor.
33368    fn contrato_endpoint_not_absolute_ctor_fixture() -> (String, String) {
33369        ("cart".to_string(), "catalog".to_string())
33370    }
33371
33372    #[test]
33373    fn contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap() {
33374        // Equivalence pin: the ctor produces byte-equal
33375        // `AplicacaoError::ContratoEndpointNotAbsolute` to the pre-lift
33376        // open-coded struct-literal on the same `(edge_pair, endpoint)`
33377        // pair, so the fold cannot silently drift on any future
33378        // field-addition / reordering / string-conversion tweak on the
33379        // variant. Same equivalence-pin shape as the sibling
33380        // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
33381        // (8580068) on the paired two-slot envelope and
33382        // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap`
33383        // (14e13f1) on the paired four-slot envelope of the same
33384        // `{ de, para, ... }`-prefix `:endpoint` axis.
33385        let (de, para) = contrato_endpoint_not_absolute_ctor_fixture();
33386        let endpoint = "charge";
33387        let lifted =
33388            AplicacaoError::contrato_endpoint_not_absolute((de.clone(), para.clone()), endpoint);
33389        let struct_literal = AplicacaoError::ContratoEndpointNotAbsolute {
33390            de,
33391            para,
33392            endpoint: endpoint.to_string(),
33393        };
33394        assert_eq!(lifted, struct_literal);
33395    }
33396
33397    #[test]
33398    fn contrato_endpoint_not_absolute_ctor_routes_edge_pair_through_verbatim() {
33399        // Routing pin on the `(de, para)` axis: sweep a non-default
33400        // pair (`"cart-svc" → "catalog-v2"`) so any wrapper-side
33401        // lowercase / trim / re-order surfaces here rather than at a
33402        // downstream diagnostic-shape drift. Peer of
33403        // `contrato_empty_pair_ctors_route_edge_pair_through_verbatim`
33404        // (8580068) on the paired two-slot envelope and
33405        // `contrato_pair_value_reason_ctors_route_edge_pair_through_verbatim`
33406        // (14e13f1) on the paired four-slot envelope of the same
33407        // `{ de, para, ... }`-prefix `:contratos` axis.
33408        let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
33409        let built = AplicacaoError::contrato_endpoint_not_absolute(edge, "charge");
33410        match built {
33411            AplicacaoError::ContratoEndpointNotAbsolute { de, para, .. } => {
33412                assert_eq!(de, "cart-svc", "de field must thread verbatim");
33413                assert_eq!(para, "catalog-v2", "para field must thread verbatim");
33414            }
33415            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
33416        }
33417    }
33418
33419    #[test]
33420    fn contrato_endpoint_not_absolute_ctor_routes_endpoint_through_to_string() {
33421        // Routing pin on the `endpoint: &str` axis: sweep a non-default
33422        // value (`"charge"` — no leading `/`, the exact shape the
33423        // [`WitContract::target`] HTTP-arm leading-slash gate rejects)
33424        // through the sole payload-carrier constructor axis so any
33425        // wrapper-side transformation on the `endpoint.to_string()`
33426        // one-field construction surfaces here rather than at a
33427        // downstream diagnostic-shape mismatch. Sibling of
33428        // `contrato_pair_value_reason_ctors_route_reason_through_into_uniformly`
33429        // (14e13f1) on the sibling four-slot envelope's payload-carrier
33430        // routing pin.
33431        let edge = || ("cart".to_string(), "catalog".to_string());
33432        let via_literal = "charge";
33433        let via_string = String::from("charge");
33434        assert_eq!(
33435            AplicacaoError::contrato_endpoint_not_absolute(edge(), via_literal),
33436            AplicacaoError::contrato_endpoint_not_absolute(edge(), via_string.as_str()),
33437        );
33438    }
33439
33440    // ── contrato_self_loop standalone ctor pins ─────────────────────────
33441    //
33442    // Fail-before-pass-after pins for the standalone
33443    // [`AplicacaoError::contrato_self_loop`] inherent ctor (see the paired
33444    // doc-block above the ctor definition) — the fold of the last
33445    // open-coded two-slot `{ caixa: <ct>.source().to_string(), wit:
33446    // <ct>.world_ref().to_string() }` struct-literal inside
33447    // [`AplicacaoSpec::validate_contratos`]'s per-`:contratos` self-edge
33448    // arm onto one substrate primitive on the [`AplicacaoError`]
33449    // envelope, projecting through the paired [`WitContract::source`] /
33450    // [`WitContract::world_ref`] scalar accessors on the substrate
33451    // primitive. A byte-mismatched ctor body would trip the equivalence
33452    // pin first, ahead of any downstream diagnostic-shape drift.
33453    //
33454    // Peer of the sibling standalone-ctor equivalence pins on the peer
33455    // one-off variants across caixa-core:
33456    // `contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap`
33457    // (cdf1a2c) above on the paired three-slot `{ de, para, endpoint }`
33458    // envelope, the sibling
33459    // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap` +
33460    // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap` on
33461    // the paired two-slot and four-slot per-`:contratos :endpoint`
33462    // envelopes, and the sibling
33463    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` (17dd504)
33464    // pin on the sibling standalone `{ host, reason }` two-slot ctor.
33465    fn contrato_self_loop_ctor_fixture() -> WitContract {
33466        WitContract {
33467            de: "cart".to_string(),
33468            para: "cart".to_string(),
33469            wit: "wasi:http/proxy".to_string(),
33470            endpoint: Some("/self".to_string()),
33471            subject: None,
33472            slot: None,
33473        }
33474    }
33475
33476    #[test]
33477    fn contrato_self_loop_ctor_matches_struct_literal_wrap() {
33478        // Equivalence pin: the ctor produces byte-equal
33479        // `AplicacaoError::ContratoSelfLoop` to the pre-lift open-coded
33480        // struct-literal that read the same two fields through
33481        // [`WitContract::source`] and [`WitContract::world_ref`]. Guards
33482        // any future field-addition / reordering / string-conversion
33483        // tweak on the variant. Same equivalence-pin shape as the
33484        // sibling `contrato_endpoint_not_absolute_ctor_matches_
33485        // struct_literal_wrap` (cdf1a2c) on the paired three-slot
33486        // per-`:contratos :endpoint` envelope.
33487        let contract = contrato_self_loop_ctor_fixture();
33488        let lifted = AplicacaoError::contrato_self_loop(&contract);
33489        let struct_literal = AplicacaoError::ContratoSelfLoop {
33490            caixa: contract.source().to_string(),
33491            wit: contract.world_ref().to_string(),
33492        };
33493        assert_eq!(lifted, struct_literal);
33494    }
33495
33496    #[test]
33497    fn contrato_self_loop_ctor_routes_source_and_world_ref_through_verbatim() {
33498        // Routing pin sweeping non-default `caixa` and `:wit` values
33499        // (`"catalog-v2"` / `"nats:pub-sub"`) through the paired
33500        // [`WitContract::source`] / [`WitContract::world_ref`] accessor
33501        // axes so any wrapper-side lowercase / trim / re-order surfaces
33502        // here rather than at a downstream diagnostic-shape drift.
33503        // Peer of the sibling
33504        // `contrato_endpoint_not_absolute_ctor_routes_edge_pair_through_verbatim`
33505        // (cdf1a2c) routing pin on the sibling three-slot envelope.
33506        let contract = WitContract {
33507            de: "catalog-v2".to_string(),
33508            para: "catalog-v2".to_string(),
33509            wit: "nats:pub-sub".to_string(),
33510            endpoint: None,
33511            subject: Some("orders.>".to_string()),
33512            slot: None,
33513        };
33514        let built = AplicacaoError::contrato_self_loop(&contract);
33515        match built {
33516            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
33517                assert_eq!(
33518                    caixa, "catalog-v2",
33519                    "caixa slot must thread WitContract::source() verbatim"
33520                );
33521                assert_eq!(
33522                    wit, "nats:pub-sub",
33523                    "wit slot must thread WitContract::world_ref() verbatim"
33524                );
33525            }
33526            other => panic!("expected ContratoSelfLoop, got {other:?}"),
33527        }
33528    }
33529
33530    #[test]
33531    fn contrato_self_loop_ctor_projects_source_field_not_destination() {
33532        // Accessor-fidelity pin: the ctor's `caixa` slot keys off the
33533        // [`WitContract::source`] accessor (matching the pre-lift open-
33534        // coded body's field selection), not [`WitContract::destination`].
33535        // Under today's `WitContract::is_self_loop()`-gated call site
33536        // the two are equal by that predicate's own contract, but a
33537        // future consumer that constructs the ctor against a not-yet-
33538        // gated candidate contract — an M4
33539        // `mesh.pleme.io/v1alpha1/Aplicacao` CR admission webhook re-
33540        // checking a per-`(:de, :para)`-patched candidate before the
33541        // self-loop gate re-fires, a per-tenant per-Aplicacao overlay
33542        // resolver rejecting a self-edge introduced by a cluster-local
33543        // `:contratos` override — needs the pre-lift field selection
33544        // pinned so a silent `.destination()` swap at the ctor body
33545        // surfaces here rather than at a downstream diagnostic mis-
33546        // attribution far from the self-loop diagnostic's owner
33547        // (the `caller` side per MESH-COMPOSITION §III.1's typed edge
33548        // direction).
33549        //
33550        // Deliberately constructs a non-self-loop pair (`"cart" →
33551        // "catalog"`) so the two accessors yield distinct bytes on the
33552        // fixture — a `.destination()` swap at the ctor body would land
33553        // `"catalog"` in the `caixa` slot instead of `"cart"` and trip
33554        // the assertion here.
33555        let contract = WitContract {
33556            de: "cart".to_string(),
33557            para: "catalog".to_string(),
33558            wit: "wasi:http/proxy".to_string(),
33559            endpoint: Some("/charge".to_string()),
33560            subject: None,
33561            slot: None,
33562        };
33563        let built = AplicacaoError::contrato_self_loop(&contract);
33564        match built {
33565            AplicacaoError::ContratoSelfLoop { caixa, .. } => {
33566                assert_eq!(
33567                    caixa, "cart",
33568                    "caixa slot must project WitContract::source() (not destination)"
33569                );
33570            }
33571            other => panic!("expected ContratoSelfLoop, got {other:?}"),
33572        }
33573    }
33574
33575    // Per-variant equivalence pins for the [`aplicacao_caixa_only_ctors!`]
33576    // macro definition (see the paired doc-block above the macro definition)
33577    // — every generated `<ctor>(caixa: &str) -> Self` constructor folds the
33578    // uniform `Self::<Variant> { caixa: caixa.to_string() }` one-field
33579    // struct-literal onto one substrate primitive. The four per-variant
33580    // equivalence pins below (fail-before-pass-after by construction — a
33581    // byte-mismatched macro arm would trip its equivalence pin first) lock
33582    // each generated constructor to its struct-literal peer under
33583    // `PartialEq`, so every wire-up in [`WitContract::require_endpoints_in`],
33584    // [`AplicacaoSpec::validate_membros`], and
33585    // [`validate_no_self_membership`] on that variant produces a byte-equal
33586    // `AplicacaoError` to the pre-lift open-coded struct-literal. The
33587    // cross-axis pin that follows (non-default caixa name) routes the sole
33588    // constructor input axis through `.to_string()`, so the fold does not
33589    // silently collapse onto a fixed name.
33590    //
33591    // Peer of the sibling per-variant `<ctor>_matches_struct_literal_wrap`
33592    // and cross-axis `<macro>_route_caixa_through_to_string` pins on the
33593    // sibling `SupervisorError` `{ caixa: String }` envelope (db09650,
33594    // `supervisor_caixa_only_ctors!`), sibling of the peer per-variant +
33595    // cross-axis pins on the peer three `AplicacaoError` sub-family folds
33596    // (14b81d5 / 8580068 / 981060b / 14e13f1), sibling of the peer four
33597    // `LayoutError` families (131ca0d / 0419438 / 1b09f9d / 3fe3dd7), sibling
33598    // of the peer M2 `:behavior` envelope fold (67c31ec,
33599    // `behavior_slot_path_ctors!` `{ slot, path }`), sibling of the peer M2
33600    // `:upgrade-from` envelope folds (8e67041 / 7468ca9), and sibling of the
33601    // peer `DepError` envelope folds (792aa92 / f85f145 / 0e35793).
33602
33603    #[test]
33604    fn contrato_member_missing_ctor_matches_struct_literal_wrap() {
33605        assert_eq!(
33606            AplicacaoError::contrato_member_missing("cart"),
33607            AplicacaoError::ContratoMemberMissing {
33608                caixa: "cart".to_string(),
33609            },
33610            "generated contrato_member_missing ctor must produce byte-equal \
33611             AplicacaoError to the open-coded struct-literal wrap on the \
33612             same &str fixture",
33613        );
33614    }
33615
33616    #[test]
33617    fn membro_versao_empty_ctor_matches_struct_literal_wrap() {
33618        assert_eq!(
33619            AplicacaoError::membro_versao_empty("cart"),
33620            AplicacaoError::MembroVersaoEmpty {
33621                caixa: "cart".to_string(),
33622            },
33623            "generated membro_versao_empty ctor must produce byte-equal \
33624             AplicacaoError to the open-coded struct-literal wrap on the \
33625             same &str fixture",
33626        );
33627    }
33628
33629    #[test]
33630    fn membro_duplicate_ctor_matches_struct_literal_wrap() {
33631        assert_eq!(
33632            AplicacaoError::membro_duplicate("cart"),
33633            AplicacaoError::MembroDuplicate {
33634                caixa: "cart".to_string(),
33635            },
33636            "generated membro_duplicate ctor must produce byte-equal \
33637             AplicacaoError to the open-coded struct-literal wrap on the \
33638             same &str fixture",
33639        );
33640    }
33641
33642    #[test]
33643    fn membro_is_self_aplicacao_ctor_matches_struct_literal_wrap() {
33644        assert_eq!(
33645            AplicacaoError::membro_is_self_aplicacao("checkout"),
33646            AplicacaoError::MembroIsSelfAplicacao {
33647                caixa: "checkout".to_string(),
33648            },
33649            "generated membro_is_self_aplicacao ctor must produce byte-equal \
33650             AplicacaoError to the open-coded struct-literal wrap on the \
33651             same &str fixture",
33652        );
33653    }
33654
33655    #[test]
33656    fn aplicacao_caixa_only_ctors_route_caixa_through_to_string() {
33657        // Cross-axis pin: sweep the sole constructor input axis (`caixa:
33658        // &str`) through a non-default fixture name against every generated
33659        // arm in the [`aplicacao_caixa_only_ctors!`] macro, so any
33660        // wrapper-side lowercase / trim / truncate / re-order on the
33661        // `caixa.to_string()` sole-field construction surfaces here rather
33662        // than at a downstream diagnostic-shape mismatch. Peer of the
33663        // sibling `supervisor_caixa_only_ctors_route_caixa_through_to_string`
33664        // cross-axis pin on the sibling `SupervisorError` `{ caixa: String }`
33665        // envelope (db09650), extended here onto the peer `AplicacaoError`
33666        // `{ caixa: String }` envelope so every substrate-primitive ctor
33667        // family in caixa-core carrying a single-slot `{ caixa: String }`
33668        // shape guarantees the sole-field construction routes the caller's
33669        // `&str` through `.to_string()` verbatim.
33670        let name = "cache-v2";
33671        assert_eq!(
33672            AplicacaoError::contrato_member_missing(name),
33673            AplicacaoError::ContratoMemberMissing {
33674                caixa: name.to_string(),
33675            },
33676        );
33677        assert_eq!(
33678            AplicacaoError::membro_versao_empty(name),
33679            AplicacaoError::MembroVersaoEmpty {
33680                caixa: name.to_string(),
33681            },
33682        );
33683        assert_eq!(
33684            AplicacaoError::membro_duplicate(name),
33685            AplicacaoError::MembroDuplicate {
33686                caixa: name.to_string(),
33687            },
33688        );
33689        assert_eq!(
33690            AplicacaoError::membro_is_self_aplicacao(name),
33691            AplicacaoError::MembroIsSelfAplicacao {
33692                caixa: name.to_string(),
33693            },
33694        );
33695    }
33696
33697    #[test]
33698    fn entrada_path_not_absolute_ctor_matches_struct_literal_wrap() {
33699        assert_eq!(
33700            AplicacaoError::entrada_path_not_absolute("api/cart"),
33701            AplicacaoError::EntradaPathNotAbsolute {
33702                path: "api/cart".to_string(),
33703            },
33704            "generated entrada_path_not_absolute ctor must produce byte-equal \
33705             AplicacaoError to the open-coded struct-literal wrap on the \
33706             same &str fixture",
33707        );
33708    }
33709
33710    #[test]
33711    fn entrada_path_duplicate_ctor_matches_struct_literal_wrap() {
33712        assert_eq!(
33713            AplicacaoError::entrada_path_duplicate("/api/cart"),
33714            AplicacaoError::EntradaPathDuplicate {
33715                path: "/api/cart".to_string(),
33716            },
33717            "generated entrada_path_duplicate ctor must produce byte-equal \
33718             AplicacaoError to the open-coded struct-literal wrap on the \
33719             same &str fixture",
33720        );
33721    }
33722
33723    // ── membro_versao_invalid ctor pins ────────────────────────────────
33724    //
33725    // Per-variant byte-equality + cross-axis routing pins guaranteeing the
33726    // lifted [`AplicacaoError::membro_versao_invalid`] inherent constructor
33727    // produces an `AplicacaoError` structurally identical to the pre-lift
33728    // `Self::MembroVersaoInvalid { caixa: caixa.to_string(), versao:
33729    // versao.to_string(), reason: reason.into() }` open-coded three-slot
33730    // struct-literal on the same `(&str, &str, reason)` fixture. Peer of
33731    // the sibling `child_versao_invalid_ctor_matches_struct_literal_wrap` +
33732    // `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
33733    // pins on the peer `SupervisorError` `{ caixa: String, versao: String,
33734    // reason: String }` envelope's per-`:children :versao` axis (d2ef2ec),
33735    // extended here onto the paired per-`:membros :versao` axis on the
33736    // sibling `AplicacaoError` envelope so both three-slot `{ caixa,
33737    // versao, reason }` per-caixa-versao-invalidation ctors on caixa-core's
33738    // typed-error surface guarantee the shared three-field construction
33739    // routes through one substrate primitive per envelope.
33740
33741    #[test]
33742    fn membro_versao_invalid_ctor_matches_struct_literal_wrap() {
33743        let caixa = "cart";
33744        let versao = "not-a-req";
33745        let reason = "sample reason text";
33746        assert_eq!(
33747            AplicacaoError::membro_versao_invalid(caixa, versao, reason),
33748            AplicacaoError::MembroVersaoInvalid {
33749                caixa: caixa.to_string(),
33750                versao: versao.to_string(),
33751                reason: reason.to_string(),
33752            },
33753            "lifted membro_versao_invalid ctor must produce byte-equal \
33754             AplicacaoError to the open-coded struct-literal wrap on the \
33755             same (&str, &str, reason) fixture",
33756        );
33757    }
33758
33759    #[test]
33760    fn membro_versao_invalid_ctor_routes_caixa_and_versao_through_to_string() {
33761        // Cross-axis pin: sweep the two `&str`-shaped constructor input
33762        // axes (`caixa`, `versao`) through non-default fixtures so any
33763        // wrapper-side lowercase / trim / truncate / re-order on either
33764        // `.to_string()` field construction surfaces here rather than at
33765        // a downstream diagnostic-shape mismatch. Peer of the sibling
33766        // `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
33767        // routing pin on the peer `SupervisorError` envelope.
33768        let caixa = "Cart-V2";
33769        let versao = "0.1.0-alpha+build.42";
33770        let reason = "constructed reason";
33771        let err = AplicacaoError::membro_versao_invalid(caixa, versao, reason);
33772        let AplicacaoError::MembroVersaoInvalid {
33773            caixa: got_caixa,
33774            versao: got_versao,
33775            reason: got_reason,
33776        } = err
33777        else {
33778            panic!("membro_versao_invalid must construct MembroVersaoInvalid variant");
33779        };
33780        assert_eq!(got_caixa, caixa.to_string());
33781        assert_eq!(got_versao, versao.to_string());
33782        assert_eq!(got_reason, reason.to_string());
33783    }
33784
33785    #[test]
33786    fn membro_versao_invalid_ctor_routes_reason_through_into() {
33787        // Route pin: the `reason: impl Into<String>` bound accepts both
33788        // `&str` literals and `format!(…)` / `String` outputs verbatim,
33789        // matching the sibling
33790        // `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
33791        // routing pin on the peer `SupervisorError::child_versao_invalid`.
33792        // Pins the sole `AplicacaoSpec::validate_membros` wire-up's
33793        // `require_valid_versao_requirement`-delivered `reason` closure
33794        // parameter (typed `String`) picks the ctor up without a per-arm
33795        // wrapper transformation, and every future consumer that
33796        // constructs the variant from a `format!(…)` reason surfaces
33797        // byte-equal to the `&str`-literal path.
33798        let caixa = "cart";
33799        let versao = "not-a-req";
33800        let from_literal = AplicacaoError::membro_versao_invalid(caixa, versao, "literal reason");
33801        let from_format =
33802            AplicacaoError::membro_versao_invalid(caixa, versao, format!("{} reason", "literal"));
33803        let from_string =
33804            AplicacaoError::membro_versao_invalid(caixa, versao, "literal reason".to_string());
33805        assert_eq!(from_literal, from_format);
33806        assert_eq!(from_literal, from_string);
33807    }
33808
33809    #[test]
33810    fn aplicacao_path_only_ctors_route_path_through_to_string() {
33811        // Cross-axis pin: sweep the sole constructor input axis (`path:
33812        // &str`) through a non-default fixture path against every generated
33813        // arm in the [`aplicacao_path_only_ctors!`] macro, so any
33814        // wrapper-side lowercase / trim / truncate / re-order on the
33815        // `path.to_string()` sole-field construction surfaces here rather
33816        // than at a downstream diagnostic-shape mismatch. Peer of the
33817        // sibling `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
33818        // cross-axis pin on the peer `AplicacaoError` `{ caixa: String }`
33819        // envelope (d9f6867), extended here onto the sibling
33820        // `AplicacaoError` `{ path: String }` envelope so every substrate-
33821        // primitive ctor family in caixa-core carrying a single-slot
33822        // `{ <slot>: String }` shape guarantees the sole-field construction
33823        // routes the caller's `&str` through `.to_string()` verbatim.
33824        let path = "/api/v2/checkout";
33825        assert_eq!(
33826            AplicacaoError::entrada_path_not_absolute(path),
33827            AplicacaoError::EntradaPathNotAbsolute {
33828                path: path.to_string(),
33829            },
33830        );
33831        assert_eq!(
33832            AplicacaoError::entrada_path_duplicate(path),
33833            AplicacaoError::EntradaPathDuplicate {
33834                path: path.to_string(),
33835            },
33836        );
33837    }
33838
33839    // ── aplicacao_policy_scalar_ctors! per-variant + cross-axis pins ────────
33840    //
33841    // Per-variant byte-equality pins guaranteeing every generated ctor arm in
33842    // the [`aplicacao_policy_scalar_ctors!`] macro produces an `AplicacaoError`
33843    // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
33844    // one-line struct-literal on the same `Copy`-`Duration | u32` fixture, plus
33845    // one cross-axis sweep that routes each per-variant `<field>: <ty>` scalar
33846    // through the sole `$field:ident: $ty:ty` axis the macro exposes so any
33847    // wrapper-side truncation / re-order / silent `.into()` / silent constant-
33848    // substitution on any one variant surfaces here rather than at a downstream
33849    // per-`:politicas` diagnostic-shape drift. Peer of the sibling per-variant
33850    // pins on `aplicacao_field_reason_ctors!` (981060b),
33851    // `aplicacao_caixa_only_ctors!` (d9f6867), `aplicacao_path_only_ctors!`
33852    // (3ba8de6), `contrato_pair_value_reason_ctors!` (14e13f1),
33853    // `contrato_empty_pair_ctors!` (8580068), `contrato_target_ctors!`
33854    // (14b81d5), plus the sibling `DepError` / `SupervisorError` /
33855    // `LayoutError` / `LimitsError` / `BehaviorError` / `UpgradeError`
33856    // per-envelope ctor-macro pins.
33857
33858    #[test]
33859    fn policy_timeout_not_canonical_ctor_matches_struct_literal_wrap() {
33860        let timeout = Duration::from_micros(1_500);
33861        assert_eq!(
33862            AplicacaoError::policy_timeout_not_canonical(timeout),
33863            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
33864            "generated policy_timeout_not_canonical ctor must produce byte-equal \
33865             `AplicacaoError::PolicyTimeoutNotCanonical` to the pre-lift \
33866             struct-literal wrap on the same `Copy`-`Duration` fixture",
33867        );
33868    }
33869
33870    #[test]
33871    fn policy_timeout_exceeds_cap_ctor_matches_struct_literal_wrap() {
33872        let timeout = Duration::from_secs(3_601);
33873        assert_eq!(
33874            AplicacaoError::policy_timeout_exceeds_cap(timeout),
33875            AplicacaoError::PolicyTimeoutExceedsCap { timeout },
33876            "generated policy_timeout_exceeds_cap ctor must produce byte-equal \
33877             `AplicacaoError::PolicyTimeoutExceedsCap` to the pre-lift \
33878             struct-literal wrap on the same `Copy`-`Duration` fixture",
33879        );
33880    }
33881
33882    #[test]
33883    fn policy_retries_exceeds_cap_ctor_matches_struct_literal_wrap() {
33884        let retries = 47_u32;
33885        assert_eq!(
33886            AplicacaoError::policy_retries_exceeds_cap(retries),
33887            AplicacaoError::PolicyRetriesExceedsCap { retries },
33888            "generated policy_retries_exceeds_cap ctor must produce byte-equal \
33889             `AplicacaoError::PolicyRetriesExceedsCap` to the pre-lift \
33890             struct-literal wrap on the same `Copy`-`u32` fixture",
33891        );
33892    }
33893
33894    #[test]
33895    fn policy_breaker_max_failures_exceeds_cap_ctor_matches_struct_literal_wrap() {
33896        let max_failures = 1_337_u32;
33897        assert_eq!(
33898            AplicacaoError::policy_breaker_max_failures_exceeds_cap(max_failures),
33899            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
33900            "generated policy_breaker_max_failures_exceeds_cap ctor must produce \
33901             byte-equal `AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` to \
33902             the pre-lift struct-literal wrap on the same `Copy`-`u32` fixture",
33903        );
33904    }
33905
33906    #[test]
33907    fn policy_breaker_window_not_canonical_ctor_matches_struct_literal_wrap() {
33908        let window = Duration::from_micros(500);
33909        assert_eq!(
33910            AplicacaoError::policy_breaker_window_not_canonical(window),
33911            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
33912            "generated policy_breaker_window_not_canonical ctor must produce \
33913             byte-equal `AplicacaoError::PolicyBreakerWindowNotCanonical` to the \
33914             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
33915        );
33916    }
33917
33918    #[test]
33919    fn policy_breaker_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
33920        let window = Duration::from_secs(3_700);
33921        assert_eq!(
33922            AplicacaoError::policy_breaker_window_exceeds_cap(window),
33923            AplicacaoError::PolicyBreakerWindowExceedsCap { window },
33924            "generated policy_breaker_window_exceeds_cap ctor must produce \
33925             byte-equal `AplicacaoError::PolicyBreakerWindowExceedsCap` to the \
33926             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
33927        );
33928    }
33929
33930    #[test]
33931    fn policy_rate_limit_exceeds_cap_ctor_matches_struct_literal_wrap() {
33932        let rate = 1_000_001_u32;
33933        assert_eq!(
33934            AplicacaoError::policy_rate_limit_exceeds_cap(rate),
33935            AplicacaoError::PolicyRateLimitExceedsCap { rate },
33936            "generated policy_rate_limit_exceeds_cap ctor must produce byte-equal \
33937             `AplicacaoError::PolicyRateLimitExceedsCap` to the pre-lift \
33938             struct-literal wrap on the same `Copy`-`u32` fixture",
33939        );
33940    }
33941
33942    #[test]
33943    fn policy_rate_limit_window_not_canonical_ctor_matches_struct_literal_wrap() {
33944        let window = Duration::from_secs(15);
33945        assert_eq!(
33946            AplicacaoError::policy_rate_limit_window_not_canonical(window),
33947            AplicacaoError::PolicyRateLimitWindowNotCanonical { window },
33948            "generated policy_rate_limit_window_not_canonical ctor must produce \
33949             byte-equal `AplicacaoError::PolicyRateLimitWindowNotCanonical` to \
33950             the pre-lift struct-literal wrap on the same `Copy`-`Duration` \
33951             fixture",
33952        );
33953    }
33954
33955    #[test]
33956    fn aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly() {
33957        // Cross-axis routing pin: sweep each generated `<field>: <ty>`
33958        // constructor input axis through a non-default `Copy` fixture against
33959        // every arm in the [`aplicacao_policy_scalar_ctors!`] macro, so any
33960        // wrapper-side silent `.into()` / silent constant-substitution / silent
33961        // field re-name away from the canonical `timeout | retries |
33962        // max_failures | window | rate` axes on any one variant, or a
33963        // `Duration | u32` axis silently rerouted through some other `Copy`
33964        // coercion, surfaces here rather than at a downstream per-`:politicas`
33965        // diagnostic-shape drift. Peer of the sibling
33966        // `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
33967        // (d9f6867), `aplicacao_path_only_ctors_route_path_through_to_string`
33968        // (3ba8de6), `dep_nome_list_ctors_route_nome_and_list_through_uniformly`
33969        // (6f5e0cd), and `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
33970        // (d2ef2ec) cross-axis routing pins on the peer per-envelope ctor
33971        // families, extended here onto the last M3 per-`:politicas` per-axis
33972        // `AplicacaoError` variant family folded onto a substrate primitive.
33973        //
33974        // Fixtures picked out of each variant's accept-set boundary rather
33975        // than the default value so a silent constant-substitution to `0` /
33976        // `Duration::ZERO` / any per-variant sentinel surfaces here on the
33977        // structural-equality assertion. The two `Duration` fixtures pick the
33978        // sub-millisecond and above-cap ends respectively; the three `u32`
33979        // fixtures pick above-cap magnitudes for `retries` / `max_failures` /
33980        // `rate` respectively (each variant's cap sits well below the fixture
33981        // so the pre-lift struct-literal wrap the fixture is compared against
33982        // is the same shape the pre-lift wire-up produced).
33983        let sub_ms = Duration::from_micros(1_500);
33984        let above_hour = Duration::from_secs(3_700);
33985        let non_canonical_rl_window = Duration::from_secs(15);
33986        assert_eq!(
33987            AplicacaoError::policy_timeout_not_canonical(sub_ms),
33988            AplicacaoError::PolicyTimeoutNotCanonical { timeout: sub_ms },
33989        );
33990        assert_eq!(
33991            AplicacaoError::policy_timeout_exceeds_cap(above_hour),
33992            AplicacaoError::PolicyTimeoutExceedsCap {
33993                timeout: above_hour,
33994            },
33995        );
33996        assert_eq!(
33997            AplicacaoError::policy_retries_exceeds_cap(47),
33998            AplicacaoError::PolicyRetriesExceedsCap { retries: 47 },
33999        );
34000        assert_eq!(
34001            AplicacaoError::policy_breaker_max_failures_exceeds_cap(1_337),
34002            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
34003                max_failures: 1_337,
34004            },
34005        );
34006        assert_eq!(
34007            AplicacaoError::policy_breaker_window_not_canonical(sub_ms),
34008            AplicacaoError::PolicyBreakerWindowNotCanonical { window: sub_ms },
34009        );
34010        assert_eq!(
34011            AplicacaoError::policy_breaker_window_exceeds_cap(above_hour),
34012            AplicacaoError::PolicyBreakerWindowExceedsCap { window: above_hour },
34013        );
34014        assert_eq!(
34015            AplicacaoError::policy_rate_limit_exceeds_cap(1_000_001),
34016            AplicacaoError::PolicyRateLimitExceedsCap { rate: 1_000_001 },
34017        );
34018        assert_eq!(
34019            AplicacaoError::policy_rate_limit_window_not_canonical(non_canonical_rl_window),
34020            AplicacaoError::PolicyRateLimitWindowNotCanonical {
34021                window: non_canonical_rl_window,
34022            },
34023        );
34024    }
34025
34026    #[test]
34027    fn aplicacao_policy_scalar_ctors_are_const_zero_runtime_work() {
34028        // Const-eval pin: the [`aplicacao_policy_scalar_ctors!`] macro spells
34029        // every generated ctor `const fn` so a caller can pin an
34030        // `AplicacaoError` at compile time — the same zero-runtime-work
34031        // property the pre-lift `|<slot>| AplicacaoError::<Variant> { <slot> }`
34032        // closure carried on its `Copy`-pass-through construction path (no
34033        // `.to_string()` / `.into()` allocation, no branching). If any future
34034        // edit silently drops the `const` qualifier from the macro body the
34035        // per-arm `const` bindings below fail to compile, which surfaces the
34036        // regression at the substrate-primitive definition rather than at
34037        // some downstream consumer that had come to rely on the `const`-
34038        // constructibility. Peer of the sibling per-variant
34039        // `_ctor_matches_struct_literal_wrap` pins above on the runtime-
34040        // equality axis; this pin closes the compile-time-const axis on the
34041        // same generated family.
34042        const TIMEOUT_NC: AplicacaoError =
34043            AplicacaoError::policy_timeout_not_canonical(Duration::from_micros(1));
34044        const TIMEOUT_CAP: AplicacaoError =
34045            AplicacaoError::policy_timeout_exceeds_cap(Duration::from_secs(3_601));
34046        const RETRIES_CAP: AplicacaoError = AplicacaoError::policy_retries_exceeds_cap(11);
34047        const MAX_FAIL_CAP: AplicacaoError =
34048            AplicacaoError::policy_breaker_max_failures_exceeds_cap(1_001);
34049        const CB_WIN_NC: AplicacaoError =
34050            AplicacaoError::policy_breaker_window_not_canonical(Duration::from_micros(1));
34051        const CB_WIN_CAP: AplicacaoError =
34052            AplicacaoError::policy_breaker_window_exceeds_cap(Duration::from_secs(3_601));
34053        const RATE_CAP: AplicacaoError = AplicacaoError::policy_rate_limit_exceeds_cap(1_000_001);
34054        const RL_WIN_NC: AplicacaoError =
34055            AplicacaoError::policy_rate_limit_window_not_canonical(Duration::from_secs(15));
34056        assert!(matches!(
34057            TIMEOUT_NC,
34058            AplicacaoError::PolicyTimeoutNotCanonical { .. }
34059        ));
34060        assert!(matches!(
34061            TIMEOUT_CAP,
34062            AplicacaoError::PolicyTimeoutExceedsCap { .. }
34063        ));
34064        assert!(matches!(
34065            RETRIES_CAP,
34066            AplicacaoError::PolicyRetriesExceedsCap { .. }
34067        ));
34068        assert!(matches!(
34069            MAX_FAIL_CAP,
34070            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { .. }
34071        ));
34072        assert!(matches!(
34073            CB_WIN_NC,
34074            AplicacaoError::PolicyBreakerWindowNotCanonical { .. }
34075        ));
34076        assert!(matches!(
34077            CB_WIN_CAP,
34078            AplicacaoError::PolicyBreakerWindowExceedsCap { .. }
34079        ));
34080        assert!(matches!(
34081            RATE_CAP,
34082            AplicacaoError::PolicyRateLimitExceedsCap { .. }
34083        ));
34084        assert!(matches!(
34085            RL_WIN_NC,
34086            AplicacaoError::PolicyRateLimitWindowNotCanonical { .. }
34087        ));
34088    }
34089
34090    // Per-variant equivalence + routing pins for the
34091    // [`AplicacaoError::placement_cluster_duplicate`] standalone ctor
34092    // (see the paired doc-block above the ctor definition) — the
34093    // generated `pub fn placement_cluster_duplicate(cluster: &str) ->
34094    // Self` inherent constructor folds the uniform
34095    // `Self::PlacementClusterDuplicate { cluster: cluster.to_string() }`
34096    // one-field struct-literal onto one substrate primitive. Same
34097    // shape as the sibling
34098    // `contrato_self_loop_ctor_matches_struct_literal_wrap` (b30edfe) /
34099    // `contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap`
34100    // (cdf1a2c) equivalence pins on the paired standalone `AplicacaoError`
34101    // ctors — extended here onto the single-slot per-`:placement
34102    // :clusters` dedup-envelope.
34103
34104    #[test]
34105    fn placement_cluster_duplicate_ctor_matches_struct_literal_wrap() {
34106        // Equivalence pin: the ctor produces byte-equal
34107        // `AplicacaoError::PlacementClusterDuplicate` to the pre-lift
34108        // open-coded struct-literal that read the same field through
34109        // `c.clone()` at the caller site inside
34110        // [`AplicacaoSpec::validate_placement_shape`]. Guards any future
34111        // field-addition / reordering / string-conversion tweak on the
34112        // variant.
34113        let cluster = "rio";
34114        let lifted = AplicacaoError::placement_cluster_duplicate(cluster);
34115        let struct_literal = AplicacaoError::PlacementClusterDuplicate {
34116            cluster: cluster.to_string(),
34117        };
34118        assert_eq!(lifted, struct_literal);
34119    }
34120
34121    #[test]
34122    fn placement_cluster_duplicate_ctor_routes_cluster_through_to_string() {
34123        // Routing pin: sweep the sole constructor input axis
34124        // (`cluster: &str`) through a non-default fixture name so any
34125        // wrapper-side lowercase / trim / truncate / re-order on the
34126        // `cluster.to_string()` sole-field construction surfaces here
34127        // rather than at a downstream diagnostic-shape mismatch. Peer of
34128        // the sibling
34129        // `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
34130        // (d9f6867) cross-axis pin on the sibling one-slot
34131        // `{ caixa: String }` envelope — extended here onto the sibling
34132        // `{ cluster: String }` envelope so the sole `String`-slot
34133        // construction routes the caller's `&str` through `.to_string()`
34134        // verbatim.
34135        let cluster = "sao-paulo-2";
34136        let built = AplicacaoError::placement_cluster_duplicate(cluster);
34137        match built {
34138            AplicacaoError::PlacementClusterDuplicate { cluster: c } => {
34139                assert_eq!(
34140                    c, cluster,
34141                    "cluster slot must thread the caller's `&str` verbatim through .to_string()"
34142                );
34143            }
34144            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
34145        }
34146    }
34147
34148    // Per-variant equivalence + routing pins for the
34149    // [`AplicacaoError::placement_without_clusters`] standalone ctor
34150    // (see the paired doc-block above the ctor definition) — the
34151    // generated `pub const fn placement_without_clusters(placement:
34152    // &Placement) -> Self` inherent constructor folds the uniform
34153    // `Self::PlacementWithoutClusters { estrategia: placement.estrategia()
34154    // }` one-field `Copy`-pass-through struct-literal onto one substrate
34155    // primitive. Same shape as the sibling
34156    // `placement_cluster_duplicate_ctor_matches_struct_literal_wrap`
34157    // (92b1c92) / `contrato_self_loop_ctor_matches_struct_literal_wrap`
34158    // (b30edfe) equivalence pins on the paired standalone `AplicacaoError`
34159    // ctors — extended here onto the one-slot per-`:placement`
34160    // empty-clusters envelope.
34161
34162    #[test]
34163    fn placement_without_clusters_ctor_matches_struct_literal_wrap() {
34164        // Equivalence pin: the ctor produces byte-equal
34165        // `AplicacaoError::PlacementWithoutClusters` to the pre-lift
34166        // open-coded struct-literal that read the same field through
34167        // `p.estrategia()` at the caller site inside
34168        // [`AplicacaoSpec::validate_placement`]. Guards any future
34169        // field-addition / reordering / accessor-return tweak on the
34170        // variant.
34171        let placement = Placement {
34172            estrategia: PlacementStrategy::Replicated,
34173            clusters: vec![],
34174            affinity: None,
34175            shard_key: None,
34176        };
34177        let lifted = AplicacaoError::placement_without_clusters(&placement);
34178        let struct_literal = AplicacaoError::PlacementWithoutClusters {
34179            estrategia: placement.estrategia(),
34180        };
34181        assert_eq!(lifted, struct_literal);
34182    }
34183
34184    #[test]
34185    fn placement_without_clusters_ctor_routes_estrategia_through_accessor() {
34186        // Routing pin: sweep the sole constructor input axis
34187        // (`placement: &Placement`) through every variant in the closed
34188        // [`PlacementStrategy::ALL`] accept-set so any wrapper-side
34189        // re-derivation / off-by-one arm-swap / stale-field read on the
34190        // `placement.estrategia()` sole-field projection surfaces here
34191        // rather than at a downstream diagnostic-shape mismatch. Peer of
34192        // the sibling
34193        // `validate_placement_reads_through_lifted_estrategia_accessor`
34194        // three-consumer coherence pin — extended here onto the ctor
34195        // itself so the accessor-projection posture is byte-witnessed at
34196        // the substrate primitive rather than only at the caller-site
34197        // fan-out. Sweeps all three [`PlacementStrategy`] variants so any
34198        // future addition to the closed accept-set surfaces as an
34199        // exhaustiveness gap on this iteration list.
34200        for estrategia in [
34201            PlacementStrategy::SingleNode,
34202            PlacementStrategy::Replicated,
34203            PlacementStrategy::Sharded,
34204        ] {
34205            let placement = Placement {
34206                estrategia,
34207                clusters: vec![],
34208                affinity: None,
34209                shard_key: None,
34210            };
34211            let built = AplicacaoError::placement_without_clusters(&placement);
34212            match built {
34213                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
34214                    assert_eq!(
34215                        e,
34216                        placement.estrategia(),
34217                        "estrategia slot must thread the caller's `Placement` verbatim \
34218                         through Placement::estrategia() — the ctor reads through the \
34219                         lifted accessor",
34220                    );
34221                    assert_eq!(
34222                        e, estrategia,
34223                        "estrategia slot must byte-equal the fixture-declared variant",
34224                    );
34225                }
34226                other => panic!("expected PlacementWithoutClusters, got {other:?}"),
34227            }
34228        }
34229    }
34230
34231    #[test]
34232    fn placement_without_clusters_ctor_is_const_fn() {
34233        // Fail-before-pass-after pin on
34234        // [`AplicacaoError::placement_without_clusters`]'s `const`-eval-
34235        // surface posture. The ctor threads the paired
34236        // [`Placement::estrategia`] `const fn` `Copy`-scalar accessor's
34237        // return through one `const fn` construction — any future
34238        // accidental downgrade to non-`const` (a `.clone()` on the
34239        // `Copy`-scalar `estrategia:` field expression, an owned-`String`
34240        // materialization on the sibling non-`estrategia:` axis) fails
34241        // `placement_without_clusters_via_const_fn` at caixa-core build
34242        // time with E0015 (`cannot call non-const method`), strictly
34243        // stronger than a runtime `assert!`. Sibling of the peer
34244        // [`aplicacao_policy_scalar_ctors!`] (7ef425e) family's `const fn`
34245        // posture on the sibling per-`:politicas` cap-scalar envelopes
34246        // and the peer [`Placement::estrategia`] const-fn accessor pin at
34247        // [`placement_estrategia_accessor_is_const_fn`] on the paired
34248        // substrate primitive.
34249        const fn placement_without_clusters_via_const_fn(p: &Placement) -> AplicacaoError {
34250            AplicacaoError::placement_without_clusters(p)
34251        }
34252        let placement = Placement {
34253            estrategia: PlacementStrategy::Sharded,
34254            clusters: vec![],
34255            affinity: None,
34256            shard_key: Some("tenantId".into()),
34257        };
34258        assert_eq!(
34259            placement_without_clusters_via_const_fn(&placement),
34260            AplicacaoError::placement_without_clusters(&placement),
34261        );
34262    }
34263
34264    #[test]
34265    fn entrada_member_missing_ctor_matches_struct_literal_wrap() {
34266        // Equivalence pin: the ctor produces byte-equal
34267        // `AplicacaoError::EntradaMemberMissing` to the pre-lift
34268        // open-coded struct-literal that read the same `:para` value
34269        // through `e.destination().to_string()` at the caller site
34270        // inside [`AplicacaoSpec::validate_entrada`]. Guards any future
34271        // field-addition / reordering / accessor-return tweak on the
34272        // variant. Sibling of the peer
34273        // `placement_without_clusters_ctor_matches_struct_literal_wrap`
34274        // and `shard_key_on_non_sharded_ctor_matches_struct_literal_wrap`
34275        // pins on the sibling per-`:placement` envelope, and sibling of
34276        // the peer `contrato_member_missing_ctor_matches_struct_literal_wrap`
34277        // pin on the sibling per-`:membros :caixa` envelope.
34278        let entrada = Entrada {
34279            host: "checkout.quero.cloud".into(),
34280            para: "phantom-shim".into(),
34281            paths: vec!["/api".into()],
34282            port: 8080,
34283        };
34284        let via_ctor = AplicacaoError::entrada_member_missing(&entrada);
34285        let via_literal = AplicacaoError::EntradaMemberMissing {
34286            para: entrada.destination().to_string(),
34287        };
34288        assert_eq!(
34289            via_ctor, via_literal,
34290            "entrada_member_missing(&entrada) must byte-equal the open-coded \
34291             EntradaMemberMissing struct-literal on the same &Entrada fixture"
34292        );
34293        assert_eq!(
34294            via_ctor.to_string(),
34295            via_literal.to_string(),
34296            "Display byte-string must byte-equal the open-coded struct-literal"
34297        );
34298    }
34299
34300    #[test]
34301    fn entrada_member_missing_ctor_routes_para_through_entrada_accessor() {
34302        // Boundary-sweep pin on the ctor's substrate-primitive
34303        // projection: the `para` slot is stored verbatim from
34304        // [`Entrada::destination`] across a representative set of
34305        // `:entrada :para` byte-strings, so any wrapper-side silent
34306        // normalization, `.into()` divergence, accidental field
34307        // rebrand, or per-arm ctor divergence on the sole-field
34308        // projection surfaces at caixa-core build time rather than at
34309        // a downstream diagnostic consumer that reads `err.para` back
34310        // and gets a different value than the one it stored. Peer of
34311        // the sibling
34312        // `shard_key_on_non_sharded_routes_estrategia_through_placement_accessor`
34313        // boundary-sweep pin on the sibling per-`:placement :shard-key`
34314        // envelope and the peer `placement_without_clusters_ctor_routes_estrategia_through_accessor`
34315        // sweep on the sibling per-`:placement` empty-clusters envelope
34316        // — extended here onto the [`Entrada`]-borrow-projected sole
34317        // `para` slot on the sibling per-`:entrada :para` envelope. The
34318        // sweep list carries a mixed set (well-shaped phantom, hyphen-
34319        // digit tail, single-character floor, and the digit-start form
34320        // the peer `accepts_canonical_entrada_para_forms` positive-
34321        // control test also sweeps) so a future silent per-input
34322        // normalization surfaces on the arm that diverges.
34323        for para in [
34324            "phantom-shim",
34325            "cart-v2",
34326            "a",
34327            "c0",
34328            "3rd-party-shim",
34329            "x-1-2-3-4",
34330        ] {
34331            let entrada = Entrada {
34332                host: "checkout.quero.cloud".into(),
34333                para: para.into(),
34334                paths: vec!["/api".into()],
34335                port: 8080,
34336            };
34337            let err = AplicacaoError::entrada_member_missing(&entrada);
34338            let AplicacaoError::EntradaMemberMissing { para: stored_para } = err else {
34339                panic!("entrada_member_missing must construct EntradaMemberMissing for {para:?}");
34340            };
34341            assert_eq!(
34342                stored_para,
34343                entrada.destination(),
34344                "para slot must round-trip verbatim through Entrada::destination() \
34345                 for {para:?}"
34346            );
34347            assert_eq!(
34348                stored_para, para,
34349                "para slot must byte-equal the fixture-declared value for {para:?}"
34350            );
34351        }
34352    }
34353
34354    #[test]
34355    fn validate_entrada_phantom_arm_routes_through_entrada_member_missing_ctor() {
34356        // End-to-end pin: the sole in-crate wire-up site
34357        // (`AplicacaoSpec::validate_entrada`'s membership-lookup arm)
34358        // routes through [`AplicacaoError::entrada_member_missing`] and
34359        // the observed `Err` byte-equals the ctor's output on the same
34360        // well-shaped-phantom `:para` fixture. A future silent de-lift
34361        // of the wire-up back to the open-coded struct-literal trips
34362        // this test at caixa-core build time rather than at a
34363        // downstream diagnostic consumer far from the wire-up commit.
34364        // Sibling of the peer
34365        // `validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor`
34366        // end-to-end pin on the sibling per-`:placement :shard-key`
34367        // envelope, and sibling of the peer
34368        // `entrada_para_well_shaped_phantom_still_raises_member_missing`
34369        // pattern-match pin on the same wire-up — extended here from a
34370        // `matches!` shape check to a byte-identity + Display parity
34371        // route through the ctor.
34372        let mut s = three_member_spec();
34373        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
34374        let observed = s.validate().unwrap_err();
34375        let expected = AplicacaoError::entrada_member_missing(s.entrada.as_ref().unwrap());
34376        assert_eq!(
34377            observed, expected,
34378            "validate_entrada's phantom-reference-arm Err must byte-equal \
34379             entrada_member_missing(&entrada)"
34380        );
34381        assert_eq!(
34382            observed.to_string(),
34383            expected.to_string(),
34384            "Display byte-string parity"
34385        );
34386    }
34387
34388    #[test]
34389    fn contrato_cycle_ctor_matches_struct_literal_wrap() {
34390        // Equivalence pin: the ctor produces byte-equal
34391        // `AplicacaoError::ContratoCycle` to the pre-lift open-coded
34392        // struct-literal that stored the caller-side reconstructed
34393        // cycle path verbatim at the gray-arm cycle-close return inside
34394        // [`AplicacaoSpec::detect_sync_cycles`]. Guards any future
34395        // field-addition / reordering / re-collect divergence on the
34396        // variant. Sibling of the peer
34397        // `entrada_member_missing_ctor_matches_struct_literal_wrap`
34398        // (deeae5c) pin on the sibling per-`:entrada :para`
34399        // phantom-reference envelope, and sibling of the peer
34400        // `placement_without_clusters_ctor_matches_struct_literal_wrap`
34401        // pin on the sibling per-`:placement` empty-clusters envelope.
34402        let cycle = vec![
34403            "cart".to_string(),
34404            "catalog".to_string(),
34405            "cart".to_string(),
34406        ];
34407        let via_ctor = AplicacaoError::contrato_cycle(cycle.clone());
34408        let via_literal = AplicacaoError::ContratoCycle {
34409            cycle: cycle.clone(),
34410        };
34411        assert_eq!(
34412            via_ctor, via_literal,
34413            "contrato_cycle(cycle) must byte-equal the open-coded \
34414             ContratoCycle struct-literal on the same Vec<String> fixture"
34415        );
34416        assert_eq!(
34417            via_ctor.to_string(),
34418            via_literal.to_string(),
34419            "Display byte-string must byte-equal the open-coded struct-literal"
34420        );
34421    }
34422
34423    #[test]
34424    fn contrato_cycle_ctor_routes_path_verbatim() {
34425        // Boundary-sweep pin on the ctor's substrate-primitive
34426        // pass-through: the `cycle` slot is stored verbatim across a
34427        // representative set of reconstructed cycle paths (two-node
34428        // closed loop; three-node loop; long chain with repeated
34429        // interior nodes; a fixture whose first/last coincide by the
34430        // gray-arm's own append-target-once-more discipline), so any
34431        // wrapper-side silent normalization, dedup, sort, `.into()`
34432        // divergence, accidental field rebrand, or re-collect on the
34433        // sole-field pass-through surfaces at caixa-core build time
34434        // rather than at a downstream diagnostic consumer that reads
34435        // `err.cycle` back and gets a different value than the one it
34436        // stored. Peer of the sibling
34437        // `entrada_member_missing_ctor_routes_para_through_entrada_accessor`
34438        // (deeae5c) boundary-sweep pin on the sibling per-`:entrada
34439        // :para` envelope — extended here onto the owned-[`Vec<String>`]
34440        // pass-through on the sibling per-`:contratos` cycle envelope.
34441        for cycle in [
34442            vec![
34443                "cart".to_string(),
34444                "catalog".to_string(),
34445                "cart".to_string(),
34446            ],
34447            vec![
34448                "cart".to_string(),
34449                "catalog".to_string(),
34450                "payment".to_string(),
34451                "cart".to_string(),
34452            ],
34453            vec![
34454                "a".to_string(),
34455                "b".to_string(),
34456                "c".to_string(),
34457                "d".to_string(),
34458                "b".to_string(),
34459            ],
34460            vec!["only".to_string(), "only".to_string()],
34461        ] {
34462            let err = AplicacaoError::contrato_cycle(cycle.clone());
34463            let AplicacaoError::ContratoCycle { cycle: stored } = err else {
34464                panic!("contrato_cycle must construct ContratoCycle for {cycle:?}");
34465            };
34466            assert_eq!(
34467                stored, cycle,
34468                "cycle slot must round-trip the caller-side Vec<String> verbatim \
34469                 for {cycle:?}"
34470            );
34471        }
34472    }
34473
34474    #[test]
34475    fn detect_sync_cycles_arm_routes_through_contrato_cycle_ctor() {
34476        // End-to-end pin: the sole in-crate wire-up site
34477        // (`AplicacaoSpec::detect_sync_cycles`'s gray-arm cycle-close
34478        // return) routes through [`AplicacaoError::contrato_cycle`] and
34479        // the observed `Err` byte-equals the ctor's output on the same
34480        // reconstructed cycle path. A future silent de-lift of the
34481        // wire-up back to the open-coded `AplicacaoError::ContratoCycle
34482        // { cycle }` struct-literal trips this test at caixa-core build
34483        // time rather than at a downstream diagnostic consumer far from
34484        // the wire-up commit. Sibling of the peer
34485        // `validate_entrada_phantom_arm_routes_through_entrada_member_missing_ctor`
34486        // (deeae5c) end-to-end pin on the sibling per-`:entrada :para`
34487        // envelope, and sibling of the peer
34488        // `validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor`
34489        // (14bafca) end-to-end pin on the sibling per-`:placement
34490        // :shard-key` envelope — extended here from a bare
34491        // `matches!(err, AplicacaoError::ContratoCycle { .. })` shape
34492        // check to a byte-identity route through the ctor.
34493        let mut s = three_member_spec();
34494        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
34495        s.contratos = vec![
34496            contract_http("catalog", "cart", "/x"),
34497            contract_http("cart", "payment", "/y"),
34498            contract_http("payment", "catalog", "/z"),
34499        ];
34500        let observed = s.validate().unwrap_err();
34501        let AplicacaoError::ContratoCycle { ref cycle } = observed else {
34502            panic!("expected ContratoCycle from the sync-cycle detector, got {observed:?}");
34503        };
34504        let expected = AplicacaoError::contrato_cycle(cycle.clone());
34505        assert_eq!(
34506            observed, expected,
34507            "detect_sync_cycles's gray-arm Err must byte-equal \
34508             contrato_cycle(cycle) on the reconstructed cycle path"
34509        );
34510        assert_eq!(
34511            observed.to_string(),
34512            expected.to_string(),
34513            "Display byte-string parity"
34514        );
34515    }
34516}