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::EntradaMemberMissing {
7971                    para: e.destination().to_string(),
7972                });
7973            }
7974            // Route the per-`:entrada :host` byte-string reads through
7975            // the lifted [`Entrada::hostname`] accessor rather than
7976            // the raw `e.host` field access — the emptiness gate and
7977            // the shape-gate `validate_entrada_host` arg now key off
7978            // exactly one typed dispatch on the substrate primitive,
7979            // closing the last unlifted per-`:entrada :host` raw-
7980            // field-access axis on the M3 mesh-slot validator. Peer
7981            // of the sibling per-`:entrada :para` convergence above
7982            // and pinned by the existing
7983            // `hostname_returns_entrada_host_byte_equal` +
7984            // `hostnames_returns_singleton_of_hostname_accessor`
7985            // accessor tests, so any future
7986            // Gateway-API-shaped host renormalization (a wildcard-
7987            // label lift, a trailing-`.` FQDN substitution, an IDNA
7988            // Punycode round-trip the SNI fan-out overlay authors)
7989            // flows through the accessor's one body without a
7990            // coordinated per-consumer rewrite across the M3 mesh
7991            // validator.
7992            if e.hostname().is_empty() {
7993                return Err(AplicacaoError::EmptyEntradaHost);
7994            }
7995            // The `:host` lands verbatim as a K8s Gateway API v1
7996            // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
7997            // both apiserver-validated against the same restrictive
7998            // pattern: lowercase RFC 1123 DNS subdomain, optional
7999            // single leading wildcard label (`*.`), max length 253,
8000            // per-label max length 63, no IP literals, no scheme,
8001            // no port. Until this gate landed `validate()` only
8002            // refused the empty string (`EmptyEntradaHost`); a
8003            // structurally invalid hostname (`"https://example.com"`,
8004            // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
8005            // `"_underscored.example.com"`, `"FOO.example.com"`,
8006            // `"checkout.quero.cloud."`) silently passed validate
8007            // and the apiserver `field is invalid` error surfaced at
8008            // `kubectl apply` time, far from the source caixa.lisp.
8009            // Lifting the gate to caixa-build time mirrors the
8010            // `:entrada :paths` value-shape trajectory (eb3456d) and
8011            // closes the last unstructured `:entrada` axis.
8012            validate_entrada_host(e.hostname())?;
8013            // Structural-floor gate on `:entrada :port`: every
8014            // validated `Entrada::port` past this gate lies in
8015            // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
8016            // type-inferred ceiling closes the top edge, so no companion
8017            // upper-cap arm is needed here — unlike the peer capped-
8018            // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
8019            // `require_positive_bounded_u32` bracket covers both edges).
8020            // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
8021            // accept-set-floor const rather than the prior inline
8022            // `if e.port == 0` byte-check so a future rebrand of the
8023            // accept-set floor (a hypothetical unprivileged-only
8024            // migration lifting the floor to `1024`, a per-cluster
8025            // scoping the operator pins through a future
8026            // `:placement :port-floor` slot as the M4 typed-slot
8027            // trajectory adds it, the future
8028            // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
8029            // per-Aplicacao gateway resolver reaching for the same
8030            // floor) is a one-line edit on the canonical
8031            // [`SERVICO_PORT_MIN`] declaration, not a coordinated
8032            // rewrite across the emit site + the pin test + every
8033            // future per-target renderer the substrate adds.
8034            if e.port() < SERVICO_PORT_MIN {
8035                return Err(AplicacaoError::EntradaPortZero);
8036            }
8037            // Each `:entrada :paths` entry becomes a K8s Gateway API
8038            // HTTPRoute `matches[].path.value`. The Gateway API rejects
8039            // values that don't start with `/` for `type: PathPrefix`,
8040            // and an empty value is meaningless. Surface those as build
8041            // errors (MESH-COMPOSITION §III.3) rather than apply-time
8042            // failures. Empty `:paths` itself is fine — caixa-mesh
8043            // falls back to a single `/` catch-all.
8044            let mut seen = std::collections::HashSet::new();
8045            // Route the per-entry value-shape gate's traversal head
8046            // through the lifted [`Entrada::paths`] slice accessor
8047            // rather than the raw `&e.paths` field access — the
8048            // per-Aplicacao `:entrada :paths` validate loop now keys
8049            // off the canonical raw-slot surface every downstream
8050            // per-`:entrada` path-list consumer (the sibling
8051            // [`Entrada::resolved_paths`] fallback-applying resolver
8052            // internal reads, `feira app graph`'s per-Aplicacao entrada
8053            // summary line's `{:?}` Debug print) routes through, so any
8054            // future rebrand on the typed slot's raw-slot reader lands
8055            // at exactly one place. Same convergence discipline as the
8056            // sibling [`Placement::clusters`] (a6e18d7) reader-site
8057            // convergences on the peer M3 mesh-slot `Vec<String>`-carry
8058            // axis.
8059            for p in e.paths() {
8060                if p.is_empty() {
8061                    return Err(AplicacaoError::EntradaPathEmpty);
8062                }
8063                if !p.starts_with('/') {
8064                    return Err(AplicacaoError::entrada_path_not_absolute(p));
8065                }
8066                // Per-entry value-shape gate: the path lands verbatim
8067                // as a K8s Gateway API HTTPRoute `matches[].path.value`
8068                // (caixa-mesh/src/lib.rs:498), apiserver-validated
8069                // against `maxLength: 1024` + the Gateway API webhook's
8070                // path-grammar rules (no `//`, no `/./`, no `/../`, no
8071                // query/fragment separators, no whitespace, no control
8072                // characters, no non-ASCII bytes). Until this gate
8073                // landed `validate` only refused the empty string and
8074                // missing-leading-slash (eb3456d); a structurally
8075                // invalid path (`"/api?q=1"`, `"/api#frag"`,
8076                // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
8077                // 1025-byte URL-shaped slug) silently passed validate
8078                // and the failure surfaced at `kubectl apply` time as
8079                // a Gateway API webhook rejection, far from the source
8080                // caixa.lisp, with no field naming the offending
8081                // `:paths` entry. Lifting the gate to caixa-build time
8082                // mirrors the `:entrada :host` value-shape trajectory
8083                // (c7d05ec) on the sibling axis — every author surface
8084                // that emits a Gateway API field now matches the
8085                // apiserver's accepted set at validate time.
8086                validate_entrada_path(p)?;
8087                crate::render::insert_first_seen(&mut seen, p.as_str(), || {
8088                    AplicacaoError::entrada_path_duplicate(p)
8089                })?;
8090            }
8091        }
8092
8093        Ok(())
8094    }
8095
8096    /// Reject `:membros` values that are operationally meaningless. The
8097    /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
8098    /// every entry names a Servico that participates in the Aplicacao,
8099    /// and the rendered programs.yaml fan-out emits one entry per
8100    /// `:membros`. Three authoring footguns are closed here:
8101    ///
8102    ///   - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
8103    ///     a `programs:` entry whose `name:` is the empty string, which
8104    ///     downstream `lareira-fleet-programs` rejects at template time
8105    ///     with a non-localized error;
8106    ///   - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
8107    ///     an empty semver constraint, so the failure surfaces far from
8108    ///     the source caixa.lisp;
8109    ///   - duplicate `:caixa` names — two entries with the same name
8110    ///     produce duplicate programs.yaml entries (one silently
8111    ///     overwrites the other in the cluster's HelmRelease values), and
8112    ///     contract membership lookups against `:contratos` collapse the
8113    ///     two onto one node, masking authoring mistakes.
8114    ///
8115    /// Same value-shape discipline as `:placement :clusters` (where empty
8116    /// + duplicate cluster names are rejected) and `:entrada :paths`
8117    /// (where empty + duplicate path entries are rejected). Lifting these
8118    /// invariants to the typed surface mirrors the MESH-COMPOSITION
8119    /// §III.3 promise that the `:membros` set — the load-bearing identity
8120    /// of the application graph — is well-formed by construction.
8121    fn validate_membros(&self) -> Result<(), AplicacaoError> {
8122        if self.membros().is_empty() {
8123            return Err(AplicacaoError::NoMembros);
8124        }
8125        let mut seen = std::collections::HashSet::new();
8126        for m in self.membros() {
8127            // Every emitted cluster artifact's `metadata.name` derives
8128            // from a `:membros :caixa` value verbatim — the rendered
8129            // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
8130            // the [`crate::LABEL_PROGRAM`] label value on every CNP
8131            // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
8132            // 272), the composed `CiliumNetworkPolicy` `metadata.name`
8133            // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
8134            // `metadata.name` when the member is the `:entrada :para`
8135            // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
8136            // schema enforces the DNS-1123 label rule on admission;
8137            // a structurally invalid member name (`"Cart"`, `"my_cart"`,
8138            // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
8139            // mistaken-identity slug) silently passes the prior empty-/
8140            // duplicate-only gate and the failure surfaces at `kubectl
8141            // apply` time as a `metadata.name: Invalid value` rejection,
8142            // far from the source caixa.lisp, with no field naming the
8143            // offending `:membros` entry. Lifting the gate to caixa-build
8144            // time mirrors the `:entrada :host` value-shape trajectory
8145            // (c7d05ec) on the peer axis — every author surface that
8146            // emits a K8s name now matches the apiserver's accepted set
8147            // at validate time.
8148            validate_membro_caixa(m.nome())?;
8149            // The author surface for `:versao` is the same Cargo-shaped
8150            // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
8151            // `"*"`) every `:deps` entry carries — and the lacre pipeline
8152            // resolves both axes through the same
8153            // [`crate::version::parse_requirement`] entry-point. The
8154            // shared [`crate::render::require_valid_versao_requirement`]
8155            // helper brackets the empty-first + parse cascade both peer
8156            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
8157            // [`crate::SupervisorSpec::validate`] on `:children :versao`)
8158            // route through, so drift between the three axes' accepted
8159            // requirement sets is structurally impossible and the parse-
8160            // side no-op the empty-first arm closes (semver's empty
8161            // parse yields an implicit `*`) lives in exactly one
8162            // predicate.
8163            crate::render::require_valid_versao_requirement(
8164                m.versao_requirement(),
8165                || AplicacaoError::membro_versao_empty(m.nome()),
8166                |reason| {
8167                    AplicacaoError::membro_versao_invalid(m.nome(), m.versao_requirement(), reason)
8168                },
8169            )?;
8170            crate::render::insert_first_seen(&mut seen, m.nome(), || {
8171                AplicacaoError::membro_duplicate(m.nome())
8172            })?;
8173        }
8174        Ok(())
8175    }
8176
8177    /// Reject `:placement` values that are operationally meaningless or
8178    /// internally contradictory. Each strategy variant has the same
8179    /// invariants on `:clusters` (non-empty list, non-empty unique
8180    /// entries) — the §III.1 author surface is uniform on this axis,
8181    /// even though the *meaning* of the list differs by strategy
8182    /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
8183    /// shard pool).
8184    ///
8185    /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
8186    /// are the same authoring footgun closed for `:politicas` zero
8187    /// values and `:entrada` empty paths: the field is *declared* but
8188    /// carries no meaning, so downstream renderers either skip it
8189    /// silently (cluster-fanout drops the empty entry, no diagnostic)
8190    /// or apply it literally and fail at admission time. Lifting both
8191    /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
8192    /// violation is a build error" promise.
8193    ///
8194    /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
8195    /// is required exactly when `:estrategia Sharded` (hash-keyed
8196    /// distribution, Akka cluster-sharding convention, §II.4) and
8197    /// refused on `:estrategia Replicated`/`SingleNode` (where no
8198    /// hash-keyed routing axis consumes it). The partition closes the
8199    /// "I think I configured sharding" footgun where an author writes
8200    /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
8201    /// the typed slot's value silently vanishes at the renderer layer
8202    /// — every validated `Placement` past this call satisfies
8203    /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
8204    fn validate_placement(&self) -> Result<(), AplicacaoError> {
8205        // Every strategy needs at least one named cluster: `Replicated`
8206        // and `SingleNode` use the list as hosting/takeover candidates
8207        // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
8208        // §II.1), while `Sharded` uses it as the shard pool
8209        // (Akka cluster-sharding convention — §II.4). An empty list is
8210        // meaningless under any of the three.
8211        //
8212        // Route the paired pre-flight `.is_empty()` refusal probe and
8213        // the per-cluster validate loop's traversal head through the
8214        // lifted [`Placement::clusters`] slice-return accessor rather
8215        // than the raw `self.placement.clusters` field access — the
8216        // two production consumers of the per-`:placement` cluster-
8217        // pool `Vec`-carry now key off exactly one typed dispatch on
8218        // the substrate primitive, so any future rebrand on the axis
8219        // (a per-tenant cluster-pool overlay the operator pins through
8220        // a future `:placement :clusters-overrides` slot, a per-
8221        // Aplicacao dynamic cluster-pool derivation the future M5
8222        // adaptive-placement engine computes from `:affinity` weights)
8223        // migrates as a single caixa-core edit rather than a
8224        // coordinated rewrite of the paired arms — sibling of the
8225        // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
8226        // arm migration on the per-`:supervisor` static-child-list
8227        // `Vec`-carry axis.
8228        //
8229        // Route the per-`:placement` outer-composite reference read
8230        // through the lifted [`AplicacaoSpec::placement`] outer accessor
8231        // rather than the raw `&self.placement` field access — the
8232        // per-axis bracket-dispatch fan-out below (`p.clusters()`,
8233        // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
8234        // axis-level lifted accessor family) now routes through the
8235        // substrate-primitive typed dispatch at the outer composition
8236        // altitude, the same shape the peer caixa-mesh
8237        // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
8238        // and the sibling `feira app graph` per-Aplicacao print line
8239        // now key off after this accessor lift.
8240        let p = self.placement();
8241        if p.clusters().is_empty() {
8242            return Err(AplicacaoError::PlacementWithoutClusters {
8243                estrategia: p.estrategia(),
8244            });
8245        }
8246        let mut seen = std::collections::HashSet::new();
8247        for c in p.clusters() {
8248            // Per-entry value-shape gate: the cluster name lands in
8249            // every K8s context / `lareira-fleet-programs` aggregator
8250            // filter / future M4 CR materializer's per-cluster axis
8251            // a validated `:clusters` entry passes through, each
8252            // enforcing the DNS-1123 label rule on admission. Same
8253            // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
8254            // on the peer name axis — both axes' validated values
8255            // are guaranteed-accepted by the apiserver without
8256            // re-validation at any downstream renderer or admission
8257            // layer.
8258            validate_placement_cluster(c)?;
8259            crate::render::insert_first_seen(&mut seen, c.as_str(), || {
8260                AplicacaoError::PlacementClusterDuplicate { cluster: c.clone() }
8261            })?;
8262        }
8263        // Route the per-`:placement :affinity` per-hint value-shape
8264        // gate through the typed [`Placement::affinity`] accessor rather
8265        // than the raw `&self.placement.affinity` field access — the
8266        // sole open-coded field-access site on the per-`:placement`
8267        // M3-Adaptive-compression-hint axis the accessor lift now owns.
8268        // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
8269        // the accessor's `Option<&str>` return type;
8270        // [`validate_placement_affinity`]'s `&str` parameter accepts
8271        // the narrower borrow without a re-allocation, so the routing
8272        // change is byte-for-byte in the pass arm and remains
8273        // byte-for-byte in every failure diagnostic
8274        // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
8275        // String` field is populated inside
8276        // [`validate_placement_affinity`] via the peer `.to_string()`
8277        // path on the same borrowed slice). Peer of the sibling
8278        // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
8279        // routing through [`Placement::shard_key`] at the caixa-core
8280        // site above — extends the "read `:placement` optional-scalars
8281        // through the typed accessor" discipline to the second
8282        // `Option<String>`-shape slot on the M3 mesh-slot family.
8283        //
8284        // Per-hint value-shape gate: the `:affinity` value lands
8285        // verbatim in the M3 Adaptive compression overlay
8286        // (caixa-mesh's `placement.affinity` emission) and every
8287        // future M4 placement-engine routing axis keying off the
8288        // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
8289        // selector — each enforces the DNS-1123 label rule on
8290        // admission. Same typed-shape trajectory as `:placement
8291        // :clusters` (6c8c00b) on the sibling slot and the four
8292        // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
8293        // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
8294        // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
8295        // on the Aplicacao surface to land on the canonical
8296        // [`crate::render::is_dns_1123_label`] floor.
8297        if let Some(a) = p.affinity() {
8298            validate_placement_affinity(a)?;
8299        }
8300        match p.estrategia() {
8301            // Route the `Sharded`-arm shape-gate cascade through the
8302            // typed [`Placement::shard_key`] accessor rather than the
8303            // raw `&self.placement.shard_key` field access — one of the
8304            // two open-coded field-access sites on the per-`:placement`
8305            // Akka-cluster-sharding-key axis the accessor lift now
8306            // owns. The `Some(k)`-bound `k` narrows from `&String` to
8307            // `&str` under the accessor's `Option<&str>` return type;
8308            // `str::is_empty` and [`validate_placement_shard_key`]'s
8309            // `&str` parameter both accept the narrower borrow without
8310            // a re-allocation.
8311            PlacementStrategy::Sharded => match p.shard_key() {
8312                None => return Err(AplicacaoError::ShardedWithoutKey),
8313                Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
8314                // Per-axis value-shape gate on the Akka-cluster-sharding
8315                // `:shard-key` extractor expression. The shape gate runs
8316                // after the more self-locating `ShardedKeyEmpty` arm so
8317                // a `:shard-key ""` surfaces the narrower empty
8318                // diagnostic first; every non-empty `:shard-key` past
8319                // this call is guaranteed to be a printable-ASCII
8320                // single-token reference the future M4 Akka-style
8321                // cluster-sharding reconciler can hash without
8322                // re-validating at the runtime layer. Mirrors the
8323                // payload-axis shape gates on the peer `:contratos`
8324                // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
8325                // 63e18a0 / c4213a4) — each lifts the runtime parser's
8326                // intersection-floor to a caixa-build-time gate.
8327                Some(k) => validate_placement_shard_key(k)?,
8328            },
8329            // `:shard-key` is the Akka-cluster-sharding axis
8330            // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
8331            // across the cluster pool. `Replicated` (active-active across
8332            // every named cluster) and `SingleNode` (Erlang/OTP
8333            // distributed-app takeover/failover, §II.1) have no hash-keyed
8334            // routing axis to consume the slot; downstream renderers
8335            // (caixa-mesh's `placement.shardKey` overlay at
8336            // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
8337            // sharding reconciler) ignore `:shard-key` outside the
8338            // `Sharded` arm by construction. Until this gate landed an
8339            // author who wrote `:placement (:estrategia Replicated
8340            // :shard-key "tenantId")` (an off-by-one strategy typo, a
8341            // copy-paste from a Sharded sibling caixa, the "I think I
8342            // configured sharding" footgun) silently passed validate and
8343            // the typed slot's value vanished at the renderer layer with
8344            // no diagnostic — the canonical "declared-but-inert" footgun
8345            // the empty-:affinity / empty-shard-key / zero-:politicas /
8346            // empty-:contratos-target gates already close on every other
8347            // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
8348            // Lifting the rejection to a build-time gate closes the
8349            // Sharded ↔ non-Sharded partition over the typed
8350            // `:placement` slot: every validated `Placement` past this
8351            // call has `shard_key.is_some()` iff `estrategia ==
8352            // Sharded`, structurally — the future Akka reconciler can
8353            // reach for `placement.shard_key` knowing it's `Some` exactly
8354            // when the strategy consumes it, without re-deriving the
8355            // partition from inline strategy probes.
8356            PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
8357                // Route the non-`Sharded`-arm declared-but-inert refusal
8358                // through the typed [`Placement::shard_key`] accessor —
8359                // the second of the two open-coded field-access sites the
8360                // accessor lift now owns. The `Some(k)`-bound `k` narrows
8361                // from `&String` to `&str`; the `AplicacaoError::
8362                // ShardKeyOnNonSharded { shard_key: String }` diagnostic
8363                // materializes the owned `String` via `k.to_string()`
8364                // (peer to the sibling per-Membro `String`-carry sites
8365                // 4127bb6 routed through `m.nome().to_string()` /
8366                // `m.versao_requirement().to_string()`), so the whole
8367                // `Sharded` ↔ non-`Sharded` partition on the
8368                // `:shard-key` axis now flows through the same typed
8369                // dispatch as the sibling `Sharded`-arm shape gate.
8370                if let Some(k) = p.shard_key() {
8371                    return Err(AplicacaoError::ShardKeyOnNonSharded {
8372                        estrategia: p.estrategia(),
8373                        shard_key: k.to_string(),
8374                    });
8375                }
8376            }
8377        }
8378        Ok(())
8379    }
8380
8381    /// Reject `:politicas` values that are operationally meaningless.
8382    /// Each axis is optional — omitting it expresses "no policy on this
8383    /// axis". Carrying a *zero* value for a declared axis is the bug
8384    /// this function rejects: zero is either
8385    ///
8386    ///   - re-interpreted as "infinite" by downstream proxies (Envoy's
8387    ///     `RouteAction.timeout = 0s` disables the timeout entirely),
8388    ///     directly contradicting MESH-COMPOSITION §V CSE invariant
8389    ///     "every Aplicacao declares :politicas :timeout (no infinite
8390    ///     blocking)", or
8391    ///   - a renderer footgun (a 0-failure circuit breaker trips on the
8392    ///     first call; a 0-rate rate-limit denies every request).
8393    ///
8394    /// Lifting these "0 means the opposite of what you think" idioms to
8395    /// the typed Aplicacao surface as build errors mirrors the §III.3
8396    /// promise that contract drift, capability leaks, and cycles are all
8397    /// build errors — not runtime surprises.
8398    fn validate_politicas(&self) -> Result<(), AplicacaoError> {
8399        // Route the whole per-axis + cross-axis `:politicas` cascade
8400        // through the substrate primitive [`MeshPolicy::validate`],
8401        // which folds all six per-axis brackets (`:timeout`,
8402        // `:retries`, `:circuit-breaker :max-failures`,
8403        // `:circuit-breaker :window`, `:rate-limit` rate, `:rate-limit`
8404        // window-canonical-form) plus the compound cross-axis fold
8405        // [`MeshPolicy::first_cross_axis_violation`] into one
8406        // `Result<(), AplicacaoError>` return. The whole per-axis-
8407        // brackets + cross-axis-fold cascade collapses to one call, and
8408        // every future [`MeshPolicy`] consumer (the future M4
8409        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
8410        // admission webhook, the per-`:contratos`-edge `:politicas`
8411        // override MESH-COMPOSITION §III.2 #3 acknowledges — the last
8412        // of which resolves an *effective* per-edge [`MeshPolicy`] and
8413        // must emit *the same* diagnostic on the same input as `feira
8414        // build`) reaches through the same substrate-primitive dispatch
8415        // rather than re-inlining the four-per-axis + one-cross-axis
8416        // cascade in lockstep with this validate gate. Same trajectory
8417        // the peer per-kind compound entry gates
8418        // [`crate::render::require_aplicacao_view`] (7242d45 / 3aefefb),
8419        // [`crate::render::require_supervisor_view`] (8d8a5c3),
8420        // [`crate::render::require_v0_servico_shape`] (per-Caixa
8421        // layout axis) and the sibling compound cross-axis fold
8422        // [`MeshPolicy::first_cross_axis_violation`] (90a6f87) carry —
8423        // extended here onto the per-slot compound entry gate that
8424        // folds both per-axis + cross-axis surfaces on the M3
8425        // mesh-slot family.
8426        self.politicas().validate()
8427    }
8428
8429    /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
8430    /// A synchronous edge is any contract whose typed [`WitTarget`] is
8431    /// `Http`, `Store`, or `Capability` — the caller blocks on the
8432    /// callee, so a cycle would deadlock at runtime. Pub-sub edges
8433    /// (`WitTarget::PubSub`) are skipped: an event publisher does not
8434    /// block on its subscribers, so they can never close a sync loop.
8435    ///
8436    /// Iterative DFS with three-coloring; the reported cycle is the
8437    /// path of caixa names traversed from the back-edge target around
8438    /// to itself, in declaration order. Adjacency lists and DFS roots
8439    /// are visited in `BTreeMap` key order so the diagnostic is
8440    /// deterministic across runs.
8441    ///
8442    /// Now the cross-edge axis of the per-slot compound gate
8443    /// [`AplicacaoSpec::validate_contratos`] — invoked at the tail of
8444    /// the per-entry cascade rather than at the outer
8445    /// [`AplicacaoSpec::validate`] dispatch, so both structural axes on
8446    /// `:contratos` (per-entry shape + membership + dedup; cross-edge
8447    /// sync-cycle) reach every consumer through one call. Kept
8448    /// standalone (rather than inlined) so consumers that want only the
8449    /// cross-edge axis (the M4 per-edge policy resolver
8450    /// MESH-COMPOSITION §III.2 #3 acknowledges, whose per-edge patch
8451    /// mutates one `:contratos` entry and needs to re-probe *just* the
8452    /// cycle invariant against the post-patch adjacency without
8453    /// re-running the per-entry shape/membership/dedup cascade the
8454    /// per-entry-only [M4 admission] fast path already covered) still
8455    /// have a self-contained entry point on the cycle axis.
8456    fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
8457        use std::collections::{BTreeMap, BTreeSet};
8458
8459        #[derive(Clone, Copy, PartialEq, Eq)]
8460        enum Mark {
8461            White,
8462            Gray,
8463            Black,
8464        }
8465
8466        let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
8467        for m in self.membros() {
8468            adj.entry(m.nome()).or_default();
8469        }
8470        for c in self.contratos() {
8471            // target() was already called by validate(); re-running here
8472            // keeps detect_sync_cycles self-contained for callers that
8473            // reuse it (M4 per-edge policy resolver) without revalidating.
8474            //
8475            // The pub-sub-arm check routes through the lifted
8476            // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
8477            // arm-discriminator predicate rather than a raw `matches!(…,
8478            // WitTarget::PubSub { .. })` on the variant so a future
8479            // rebrand on the axis (an M4 per-edge WIT registry split of
8480            // [`WitTarget::PubSub`] into shape-specific peers, a
8481            // per-consumer rename that the accept-set already carries)
8482            // reaches this call site through the derive rather than a
8483            // scattered per-arm `matches!` rewrite — same
8484            // `IsVariant`-derived-arm-discriminator discipline the
8485            // peer closed-set typed enums ([`crate::CaixaKind`] via
8486            // f5bba80, [`PlacementStrategy`] via 766ec63,
8487            // [`crate::supervisor::RestartStrategy`] +
8488            // [`crate::supervisor::RestartPolicy`],
8489            // [`crate::upgrade::UpgradeInstruction`] via 915a934)
8490            // already route through on the substrate's other typed-enum
8491            // arm-discriminator axes.
8492            if c.target()?.is_pubsub() {
8493                continue;
8494            }
8495            adj.entry(c.source()).or_default().insert(c.destination());
8496        }
8497
8498        let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
8499        let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
8500
8501        // Stable DFS root order — BTreeMap iteration is sorted by key.
8502        let roots: Vec<&str> = adj.keys().copied().collect();
8503
8504        // Frame: (node, sorted-neighbours snapshot, next-edge index).
8505        for root in roots {
8506            if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
8507                continue;
8508            }
8509            let root_neighbors: Vec<&str> = adj
8510                .get(root)
8511                .map(|s| s.iter().copied().collect())
8512                .unwrap_or_default();
8513            let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
8514            color.insert(root, Mark::Gray);
8515
8516            loop {
8517                // Read+advance the top frame in one borrow scope so we
8518                // can later mutate the stack (push/pop) without holding
8519                // a borrow across.
8520                let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
8521                    let node = top.0;
8522                    if top.2 >= top.1.len() {
8523                        (node, None)
8524                    } else {
8525                        let nxt = top.1[top.2];
8526                        top.2 += 1;
8527                        (node, Some(nxt))
8528                    }
8529                });
8530                let Some((node, nxt_opt)) = step else { break };
8531                let Some(nxt) = nxt_opt else {
8532                    color.insert(node, Mark::Black);
8533                    stack.pop();
8534                    continue;
8535                };
8536                let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
8537                match nxt_color {
8538                    Mark::Gray => {
8539                        // Reconstruct the cycle from `node` back through
8540                        // the parent chain to `nxt`, then close.
8541                        let mut cycle = Vec::new();
8542                        let mut cur = node;
8543                        cycle.push(cur.to_string());
8544                        while cur != nxt {
8545                            match parent.get(cur).copied() {
8546                                Some(p) => {
8547                                    cur = p;
8548                                    cycle.push(cur.to_string());
8549                                }
8550                                None => break,
8551                            }
8552                        }
8553                        cycle.reverse();
8554                        cycle.push(nxt.to_string());
8555                        return Err(AplicacaoError::ContratoCycle { cycle });
8556                    }
8557                    Mark::White => {
8558                        parent.insert(nxt, node);
8559                        color.insert(nxt, Mark::Gray);
8560                        let nxt_neighbors: Vec<&str> = adj
8561                            .get(nxt)
8562                            .map(|s| s.iter().copied().collect())
8563                            .unwrap_or_default();
8564                        stack.push((nxt, nxt_neighbors, 0));
8565                    }
8566                    Mark::Black => {}
8567                }
8568            }
8569        }
8570        Ok(())
8571    }
8572
8573    /// Substrate-canonical destination-facing TCP port every emitted
8574    /// per-Aplicacao artifact must key `destination`-shaped port axes
8575    /// off. Returns the typed `:entrada :port` scalar when this
8576    /// Aplicacao's `:entrada` block names `destination` under its
8577    /// `:para` axis (the destination Servico *is* the ingress apex, so
8578    /// the substrate honors the author-declared listener port
8579    /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
8580    /// fallback otherwise (every non-apex destination — the internal
8581    /// mesh Servicos `:contratos` reach across, the future per-edge
8582    /// policy resolver's per-destination probe targets, the
8583    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
8584    /// L4 port resolver — reads the same substrate-canonical port floor
8585    /// by construction).
8586    ///
8587    /// Prior to this lift the "if :entrada matches this destination use
8588    /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
8589    /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
8590    /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
8591    /// prior to this lift), with no typed method on the substrate primitive
8592    /// that named the rule. A future per-destination port axis addition
8593    /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
8594    /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
8595    /// per-Servico listener ports land, a per-cluster override the operator
8596    /// pins through a future `:placement :default-port` slot — would have
8597    /// to be threaded through every renderer's inline cascade in lockstep
8598    /// or one consumer would silently disagree on which port a given
8599    /// destination Servico's ingress lands at. Lifting the rule to a
8600    /// typed method on the substrate primitive means the M4 CR
8601    /// materializer, the future per-edge policy resolver, and every
8602    /// downstream test-fixture navigator reach for exactly one typed
8603    /// dispatch — the resolver's accept-set moves as a unit on any
8604    /// future axis addition.
8605    ///
8606    /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
8607    /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
8608    /// the typed primitive, thin projections at each consumer"
8609    /// discipline lifts on the sibling `:contratos` payload / `:politicas
8610    /// :rate-limit` unit-suffix axes; extends the discipline onto the
8611    /// destination-facing port-resolution axis every per-Aplicacao
8612    /// L4-fallback renderer consumes.
8613    #[must_use]
8614    pub fn port_for_destination(&self, destination: &str) -> u16 {
8615        // Route the per-`:entrada` composite-reference read through
8616        // the lifted [`AplicacaoSpec::entrada`] accessor rather than
8617        // the raw `self.entrada.as_ref()` field access — the
8618        // per-destination L4-port fallback resolver's composite-
8619        // projection seed is now the canonical read-side surface
8620        // every per-Aplicacao entrada consumer routes through, peer
8621        // of the sibling `validate` per-`:entrada` shape-and-
8622        // membership gate migration on the same outer-composite
8623        // axis.
8624        // Route the per-`:entrada` apex-destination membership probe
8625        // through the lifted [`Entrada::destination`] accessor rather
8626        // than the raw `e.para == destination` field access — the last
8627        // un-lifted `.para` production-code read site on the per-
8628        // `:entrada` `:para` axis, sibling to the four caixa-core
8629        // consumer sites the peer 15ddd8c converge already routed
8630        // through the accessor (the three
8631        // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
8632        // membership gate sites: the `validate_entrada_para` DNS-1123
8633        // shape gate, the per-`:membros` membership lookup, and the
8634        // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
8635        // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
8636        // `entrada.para`-projection converge at
8637        // caixa-core/src/render.rs (the `gateway_api_http_route_name`
8638        // route-name projection site). Prior to this converge the
8639        // `port_for_destination` resolver was the solitary consumer
8640        // bypassing the typed dispatch on the `.para` axis — the two
8641        // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
8642        // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
8643        // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
8644        // reach through the same accessor family compose with this
8645        // resolver at the emit boundary via the apex-identity
8646        // invariant `spec.port_for_destination(entrada.destination())
8647        // == entrada.port` the sibling
8648        // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
8649        // pin pins across four permutations. A future extension of the
8650        // `:entrada :para` axis to a richer author surface (a per-
8651        // cluster alias overlay the operator pins through a future
8652        // `:placement`-scoped slot, a namespace-qualified rewrite the
8653        // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
8654        // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
8655        // §III.2 acknowledges) that lands on the accessor would silently
8656        // disagree between this resolver and the two `caixa-mesh` emit
8657        // sites — an author-declared `:para "cart"` value the accessor
8658        // rewrote to `"cart-v2"` under a future canary arm would leave
8659        // the resolver's membership arm falling through to
8660        // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
8661        // `.para`) while the peer emit-site consumers landed on the
8662        // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
8663        // silently disagreed on which destination port a given typed
8664        // `:entrada` resolves to at cluster-apply time. Pinned by the
8665        // drift-detection test
8666        // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
8667        // below.
8668        self.entrada()
8669            .filter(|e| e.destination() == destination)
8670            .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
8671    }
8672}
8673
8674/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
8675/// entry may name the Aplicacao's own `:nome`.
8676///
8677/// An Aplicacao that lists itself as a member is a degenerate self-edge in
8678/// the typed graph — the application graph is a DAG rooted at the Aplicacao
8679/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
8680/// Servicos that compose the app; an Aplicacao is never its own constituent),
8681/// and the lacre pipeline's closure-resolution would otherwise be handed a
8682/// node that is its own parent: a one-node cycle it either rejects far from
8683/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
8684/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
8685/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
8686/// label + lacre closure root), a member whose `:caixa` equals the
8687/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
8688/// peer.
8689///
8690/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
8691/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
8692/// gate `validate_upgrade_from_against_versao` and the supervision-tree
8693/// self-parent gate `crate::supervisor::validate_no_self_supervision`
8694/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
8695/// not a tree/mesh edge" discipline, here on the second typed-graph axis
8696/// (the Aplicacao :membros set; the supervision-tree :children list was the
8697/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
8698/// every validated Supervisor's children are distinct from its `:nome`,
8699/// every validated Aplicacao's membros are distinct from its `:nome`. The
8700/// transitive consequence is that `:entrada :para` and `:contratos`
8701/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
8702/// name the Aplicacao itself, without re-deriving the partition.
8703pub fn validate_no_self_membership(
8704    membros: &[Membro],
8705    parent_nome: &str,
8706) -> Result<(), AplicacaoError> {
8707    for m in membros {
8708        if m.nome() == parent_nome {
8709            return Err(AplicacaoError::membro_is_self_aplicacao(parent_nome));
8710        }
8711    }
8712    Ok(())
8713}
8714
8715#[derive(Debug, Error, PartialEq, Eq)]
8716pub enum AplicacaoError {
8717    #[error("Aplicacao must declare at least one :membros entry")]
8718    NoMembros,
8719    #[error(
8720        ":membros entry has empty :caixa (every member must name a Servico; \
8721         omit the entry instead of carrying an empty name)"
8722    )]
8723    MembroCaixaEmpty,
8724    #[error(
8725        ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
8726         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
8727         name / label value the member name lands in; use a lowercase \
8728         alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
8729    )]
8730    MembroCaixaInvalid { caixa: String, reason: String },
8731    #[error(
8732        ":membros entry {caixa:?} has empty :versao (every member must pin a \
8733         semver constraint that resolves through the lacre pipeline)"
8734    )]
8735    MembroVersaoEmpty { caixa: String },
8736    #[error(
8737        ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
8738         requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
8739         `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
8740         carries; the lacre pipeline resolves both through the same parser)"
8741    )]
8742    MembroVersaoInvalid {
8743        caixa: String,
8744        versao: String,
8745        reason: String,
8746    },
8747    #[error(
8748        ":membros entry {caixa:?} appears more than once (the graph node set \
8749         is a set, not a multiset; duplicate members produce duplicate \
8750         programs.yaml entries and ambiguous :contratos membership lookups)"
8751    )]
8752    MembroDuplicate { caixa: String },
8753    #[error(
8754        "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
8755         never its own constituent Servico (the application graph is a DAG rooted \
8756         at the Aplicacao; :membros names the *other* caixas that compose the \
8757         app, not the app itself). Since every :nome is a globally-unique \
8758         substrate identity, a member naming the Aplicacao's own :nome is a \
8759         one-node lacre-closure recursion, not a coincidentally-named peer; \
8760         drop the self-referential :membros entry or rename it to the actual \
8761         constituent caixa."
8762    )]
8763    MembroIsSelfAplicacao { caixa: String },
8764    #[error(
8765        "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
8766         caixa declared in :membros; omit the contract or fill the {slot} field with a \
8767         member name)"
8768    )]
8769    ContratoCaixaEmpty { slot: &'static str },
8770    #[error(
8771        "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
8772         :contratos {slot} value names a member of :membros, which is itself a \
8773         DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
8774         object the member name lands in — Service, Pod, identity-based Cilium \
8775         selector; use a lowercase alphanumeric + hyphen identifier like \
8776         `\"checkout\"` or `\"cart-v2\"`)"
8777    )]
8778    ContratoCaixaInvalid {
8779        slot: &'static str,
8780        caixa: String,
8781        reason: String,
8782    },
8783    #[error("contrato references caixa {caixa:?} not declared in :membros")]
8784    ContratoMemberMissing { caixa: String },
8785    #[error(
8786        "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
8787         entry is an inter-Servico contract whose :de and :para must name distinct \
8788         :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
8789         the contract, or point :para at the member it actually calls)"
8790    )]
8791    ContratoSelfLoop { caixa: String, wit: String },
8792    #[error("contrato {de:?} → {para:?} has empty :wit")]
8793    EmptyWit { de: String, para: String },
8794    #[error(
8795        "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
8796         {reason} (the substrate dispatches `:wit` values on the canonical \
8797         lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
8798         `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
8799         demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
8800         kebab-case identifier per segment)"
8801    )]
8802    ContratoWitInvalid {
8803        de: String,
8804        para: String,
8805        wit: String,
8806        reason: String,
8807    },
8808    #[error(
8809        ":entrada :para is empty (every :entrada must route to a caixa declared in \
8810         :membros; fill the :para field with a member name)"
8811    )]
8812    EntradaParaEmpty,
8813    #[error(
8814        ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
8815         :entrada :para value names a member of :membros, which is itself a DNS-1123 \
8816         label per the K8s apiserver's `metadata.name` rule on every object the \
8817         member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
8818         Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
8819         `\"checkout\"` or `\"cart-v2\"`)"
8820    )]
8821    EntradaParaInvalid { para: String, reason: String },
8822    #[error(":entrada routes to caixa {para:?} not declared in :membros")]
8823    EntradaMemberMissing { para: String },
8824    #[error(":entrada must declare a non-empty :host")]
8825    EmptyEntradaHost,
8826    #[error(
8827        ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
8828         (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
8829         `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
8830         like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
8831    )]
8832    EntradaHostInvalid { host: String, reason: String },
8833    #[error(":entrada :port must be in 1..=65535, got 0")]
8834    EntradaPortZero,
8835    #[error(":entrada :paths entry is empty (use the empty list to match all)")]
8836    EntradaPathEmpty,
8837    #[error(
8838        ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
8839    )]
8840    EntradaPathNotAbsolute { path: String },
8841    #[error(
8842        ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
8843         value: {reason} (the K8s apiserver enforces the same shape on \
8844         `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
8845         single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
8846         requires percent-encoding `%XX` for non-ASCII and whitespace)"
8847    )]
8848    EntradaPathInvalid { path: String, reason: String },
8849    #[error(":entrada :paths entry {path:?} appears more than once")]
8850    EntradaPathDuplicate { path: String },
8851    #[error(
8852        ":placement {estrategia} requires at least one :clusters entry \
8853         (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
8854    )]
8855    PlacementWithoutClusters { estrategia: PlacementStrategy },
8856    #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
8857    PlacementClusterEmpty,
8858    #[error(
8859        ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
8860         (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
8861         in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
8862         future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
8863         — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
8864         identifier like `\"rio\"` or `\"mar-east\"`)"
8865    )]
8866    PlacementClusterInvalid { cluster: String, reason: String },
8867    #[error(":placement :clusters entry {cluster:?} appears more than once")]
8868    PlacementClusterDuplicate { cluster: String },
8869    #[error(
8870        ":placement :affinity must be non-empty when set (omit :affinity to express \
8871         `no placement hint`)"
8872    )]
8873    PlacementAffinityEmpty,
8874    #[error(
8875        ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
8876         (placement hints land verbatim in the M3 Adaptive compression overlay's \
8877         `placement.affinity` field and in every future M4 placement-engine routing \
8878         axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
8879         selector — both enforce the DNS-1123 label rule on admission; use a \
8880         lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
8881         `\"low-latency\"`, or `\"anti-affinity\"`)"
8882    )]
8883    PlacementAffinityInvalid { affinity: String, reason: String },
8884    #[error(":placement Sharded requires :shard-key")]
8885    ShardedWithoutKey,
8886    #[error(
8887        ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
8888         hashes every entity onto the same shard, defeating sharding entirely)"
8889    )]
8890    ShardedKeyEmpty,
8891    #[error(
8892        ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
8893         entity-id extractor expression: {reason} (the future M4 Akka-style \
8894         cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
8895         as a single-token property reference and hashes the extracted entity ID \
8896         to compute shard placement; use a printable-ASCII extractor expression \
8897         like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
8898         `\"${{tenant}}\"`)"
8899    )]
8900    ShardKeyInvalid { shard_key: String, reason: String },
8901    #[error(
8902        ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
8903         Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
8904         convention); :estrategia Replicated runs every cluster active-active and \
8905         :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
8906         distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
8907         to :estrategia Sharded if hash-keyed routing is the intent"
8908    )]
8909    ShardKeyOnNonSharded {
8910        estrategia: PlacementStrategy,
8911        shard_key: String,
8912    },
8913    #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
8914    ContratoMissingTarget {
8915        de: String,
8916        para: String,
8917        wit: String,
8918        expected: &'static str,
8919    },
8920    #[error(
8921        "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
8922         expected `:{expected}` only"
8923    )]
8924    ContratoWrongTarget {
8925        de: String,
8926        para: String,
8927        wit: String,
8928        expected: &'static str,
8929    },
8930    #[error(
8931        "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
8932         like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
8933         that matches no traffic and silently drops every request)"
8934    )]
8935    ContratoEndpointEmpty { de: String, para: String },
8936    #[error(
8937        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
8938         (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
8939         :entrada :paths)"
8940    )]
8941    ContratoEndpointNotAbsolute {
8942        de: String,
8943        para: String,
8944        endpoint: String,
8945    },
8946    #[error(
8947        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
8948         Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
8949         emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
8950         caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
8951         shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
8952         like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
8953         and whitespace)"
8954    )]
8955    ContratoEndpointInvalid {
8956        de: String,
8957        para: String,
8958        endpoint: String,
8959        reason: String,
8960    },
8961    #[error(
8962        "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
8963         subject is a no-op subscribe; omit :subject only if the WIT world is not \
8964         pub-sub-shaped)"
8965    )]
8966    ContratoSubjectEmpty { de: String, para: String },
8967    #[error(
8968        "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
8969         NATS subject: {reason} (the NATS server's subject parser enforces the \
8970         same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
8971         single-token and `>` multi-token wildcards — at publish/subscribe time; \
8972         use a token-by-token form like `\"checkout.events.charge.failed\"` or \
8973         `\"orders.*.completed\"` — a malformed subject silently drops every \
8974         message at runtime far from the source caixa.lisp)"
8975    )]
8976    ContratoSubjectInvalid {
8977        de: String,
8978        para: String,
8979        subject: String,
8980        reason: String,
8981    },
8982    #[error(
8983        "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
8984         addresses the bucket root, defeating the per-key isolation the slot exists \
8985         for; omit :slot only if the WIT world is not store-shaped)"
8986    )]
8987    ContratoSlotEmpty { de: String, para: String },
8988    #[error(
8989        "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
8990         WASI keyvalue store slot template: {reason} (the substrate enforces \
8991         the printable-ASCII intersection-floor every kv backend admits — \
8992         use a single-token path / template expression like `\"checkout/$orderId\"`, \
8993         `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
8994         percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
8995         slot either gets rejected on write by strict backends or silently \
8996         corrupts the next read on permissive ones, far from the source caixa.lisp)"
8997    )]
8998    ContratoSlotInvalid {
8999        de: String,
9000        para: String,
9001        slot: String,
9002        reason: String,
9003    },
9004    #[error(
9005        "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
9006         or an event-sourced indirection (MESH-COMPOSITION §III.3)",
9007        cycle.join(" → ")
9008    )]
9009    ContratoCycle { cycle: Vec<String> },
9010    #[error(
9011        ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
9012         than once (the typed graph edges are a set, not a multiset; duplicate \
9013         contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
9014         values that K8s admission rejects far from the source caixa.lisp)"
9015    )]
9016    ContratoDuplicate {
9017        de: String,
9018        para: String,
9019        wit: String,
9020        target: String,
9021    },
9022    #[error(
9023        ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
9024         contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
9025         express `no per-call deadline on this axis`"
9026    )]
9027    PolicyTimeoutZero,
9028    #[error(
9029        ":politicas :retries must be > 0 when set; omit :retries to express \
9030         `no retries on transient failure`"
9031    )]
9032    PolicyRetriesZero,
9033    #[error(
9034        ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
9035         (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
9036         retry policy into a thundering-herd amplification vector on transient \
9037         failure (one caller request fans out to `(retries+1)^depth` server-side \
9038         calls across the synchronous-:contratos subgraph), exactly the failure \
9039         mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
9040         Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
9041         or omit :retries to disable retries entirely"
9042    )]
9043    PolicyRetriesExceedsCap { retries: u32 },
9044    #[error(
9045        ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
9046         breaker trips on the first call); omit :circuit-breaker to disable it"
9047    )]
9048    PolicyBreakerZeroFailures,
9049    #[error(
9050        ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
9051         mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
9052         above this cap turns the typed breaker policy into a no-op: the trip \
9053         threshold is structurally so high that no realistic failures-per-:window \
9054         traffic shape can reach it, so the breaker never trips and every typed-slot \
9055         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
9056         Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
9057         structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
9058         Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
9059         omit :circuit-breaker to disable the breaker entirely"
9060    )]
9061    PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
9062    #[error(
9063        ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
9064         tracks no failures); omit :circuit-breaker to disable it"
9065    )]
9066    PolicyBreakerZeroWindow,
9067    #[error(
9068        ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
9069         request); omit :rate-limit to disable rate limiting"
9070    )]
9071    PolicyRateLimitZero,
9072    #[error(
9073        ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
9074         (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
9075         rate-limit policy into a no-op limiter: the token-bucket capacity is \
9076         structurally so high that no realistic per-edge traffic shape can drain it, \
9077         so the limiter never trips and every typed-slot consumer (the future \
9078         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9079         local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
9080         that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
9081         Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
9082         Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
9083         Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
9084         to disable rate limiting entirely"
9085    )]
9086    PolicyRateLimitExceedsCap { rate: u32 },
9087    #[error(
9088        ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
9089         the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
9090         rate-limit codec round-trips losslessly; got {window:?} which renders to a \
9091         non-round-trippable form (omit :rate-limit to disable, or pick one of the \
9092         three canonical windows)"
9093    )]
9094    PolicyRateLimitWindowNotCanonical { window: Duration },
9095    #[error(
9096        ":politicas :timeout must be an integer number of milliseconds — the canonical \
9097         authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
9098         duration codec round-trips losslessly; got {timeout:?} which carries a \
9099         sub-millisecond residue that either truncates to a different `Duration` on \
9100         re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
9101         to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
9102         zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
9103         (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
9104    )]
9105    PolicyTimeoutNotCanonical { timeout: Duration },
9106    #[error(
9107        ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
9108         (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
9109         per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
9110         overlays carry a deadline so long no realistic synchronous-:contratos \
9111         traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
9112         CSE invariant degenerates to enforcement only at the per-Servico \
9113         `:limits :wall-clock` layer — far above the per-edge granularity the typed \
9114         `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
9115         (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
9116         ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
9117         maxes out at the same `3600s` ceiling) or omit :timeout to express \
9118         `no per-call deadline on this axis` (the synchronous-call deadline then \
9119         relies entirely on the per-Servico `:limits :wall-clock` axis)"
9120    )]
9121    PolicyTimeoutExceedsCap { timeout: Duration },
9122    #[error(
9123        ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
9124         the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
9125         the shared duration codec round-trips losslessly; got {window:?} which carries a \
9126         sub-millisecond residue that either truncates to a different `Duration` on \
9127         re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
9128         Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
9129    )]
9130    PolicyBreakerWindowNotCanonical { window: Duration },
9131    #[error(
9132        ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
9133         (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
9134         rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
9135         is structurally so long that transient failures are never forgotten, the breaker \
9136         trips once and stays tripped for the lifetime of the component, and every typed-slot \
9137         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9138         outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
9139         Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
9140         default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
9141         the breaker entirely"
9142    )]
9143    PolicyBreakerWindowExceedsCap { window: Duration },
9144    #[error(
9145        ":politicas :circuit-breaker :window ({window:?}) is shorter than :politicas \
9146         :timeout ({timeout:?}) — the rolling failure-observation interval closes before \
9147         a single timing-out call can be declared failed, so the dominant failure mode \
9148         the breaker exists to catch is structurally never counted: a call dispatched at \
9149         t=0 is only reported failed at t={timeout:?}, by which point the window that was \
9150         open at dispatch has already rolled, and every typed-slot consumer (the future \
9151         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9152         outlier_detection.interval paired against the per-route request timeout) emits a \
9153         breaker that cannot trip on timeouts however high the call volume. Pin :window \
9154         at or above :timeout (Hystrix defaults 10s rolling window against a 1s execution \
9155         timeout — a 10× ratio; Envoy / resilience4j production playbooks recommend the \
9156         same shape), lower :timeout, or omit one of the two axes"
9157    )]
9158    PolicyBreakerWindowBelowTimeout { window: Duration, timeout: Duration },
9159    #[error(
9160        ":politicas :rate-limit ({rate} per {rl_window:?}) starves :politicas \
9161         :circuit-breaker so :max-failures ({max_failures}) cannot be reached inside \
9162         :window ({cb_window:?}) — the token-bucket dispatches at most \
9163         `rate × cb_window / rl_window` calls per rolling breaker window, which is \
9164         structurally below the trip threshold, so the breaker cannot trip even under \
9165         100% failure and every typed-slot consumer (the future \
9166         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9167         outlier_detection.consecutive_5xx paired against \
9168         local_rate_limit.token_bucket.max_tokens) emits a protection that is \
9169         structurally never enforced. Raise :rate, shorten :rate-limit :window, lower \
9170         :max-failures, lengthen :circuit-breaker :window, or omit one of the two axes"
9171    )]
9172    PolicyBreakerCannotTripUnderRateLimit {
9173        rate: u32,
9174        rl_window: Duration,
9175        max_failures: u32,
9176        cb_window: Duration,
9177    },
9178    #[error(
9179        ":politicas :retries ({retries}) plus the initial attempt saturates :politicas \
9180         :circuit-breaker :max-failures ({max_failures}) mid-retry — one client's failing \
9181         attempts alone accumulate {retries}+1 failures, which reaches the trip threshold \
9182         at or before the last retry, so the breaker opens with declared retries still \
9183         unused and every typed-slot consumer (the future CiliumClusterwideEnvoyConfig \
9184         per-:politicas overlay, Envoy's retry_policy.num_retries paired against \
9185         outlier_detection.consecutive_5xx) emits a retry policy the substrate \
9186         structurally truncates. Pin :max-failures strictly above :retries (Hystrix / \
9187         Envoy / resilience4j production playbooks recommend the breaker's trip \
9188         threshold be observably larger than any single client's retry budget so the \
9189         breaker distinguishes one persistently-failing client from sustained \
9190         multi-client failure), lower :retries, or omit one of the two axes"
9191    )]
9192    PolicyBreakerTripsBeforeRetriesExhausted { retries: u32, max_failures: u32 },
9193    #[error(
9194        ":politicas :rate-limit ({rate} per window) cannot admit :politicas :retries \
9195         ({retries}) plus the initial attempt — one client's declared retry sequence is \
9196         {retries}+1 attempts, each of which consumes one token from the local rate-limit \
9197         bucket, but the bucket admits at most {rate} tokens per refill window, so the \
9198         retry policy is silently truncated by the same rate limiter it feeds through and \
9199         every typed-slot consumer (the future CiliumClusterwideEnvoyConfig per-:politicas \
9200         overlay, Envoy's retry_policy.num_retries paired against \
9201         local_rate_limit.token_bucket.max_tokens) emits a retry policy the substrate \
9202         structurally throttles. Raise :rate strictly above :retries (Envoy / Istio / \
9203         resilience4j / AWS App Mesh production playbooks recommend the local rate-limit \
9204         bucket capacity be observably larger than any single client's retry budget so the \
9205         limiter distinguishes one client's declared retries from sustained multi-client \
9206         load), lower :retries, or omit one of the two axes"
9207    )]
9208    PolicyRateLimitCannotAdmitRetryBurst { retries: u32, rate: u32 },
9209}
9210
9211// The `AplicacaoError::EntradaHostInvalid { host, reason }` variant's
9212// ctor `entrada_host_invalid` is folded onto the sibling
9213// [`aplicacao_field_reason_ctors!`] macro below alongside the six peer
9214// `{ <field>: String, reason: String }` variants
9215// (`MembroCaixaInvalid` / `EntradaParaInvalid` / `EntradaPathInvalid` /
9216// `PlacementClusterInvalid` / `PlacementAffinityInvalid` /
9217// `ShardKeyInvalid`), so every variant on the uniform two-slot
9218// `{ <field>: String, reason: String }` envelope on [`AplicacaoError`]
9219// reads through one substrate-primitive family rather than one macro
9220// closing six sites plus a hand-written seventh ctor closing the
9221// paired site alone. Prior separate-ctor rationale (17dd504) migrates
9222// verbatim to the macro's outer doc block.
9223
9224// Fold the seven `AplicacaoError::Contrato{Wrong,Missing}Target { de, para,
9225// wit, expected }` wire-up sites at [`WitContract::target`] onto one
9226// substrate-primitive family per typed variant — the paired sibling on
9227// [`AplicacaoError`] of the four `LayoutError` constructor families
9228// [`layout_violation_ctors!`] (131ca0d, 16 variants on `{ caixa, issue }`),
9229// [`layout_slot_kind_ctors!`] (0419438, 4 variants on
9230// `{ caixa, kind, slots }`), [`LayoutError::missing_entry`] (1b09f9d,
9231// 1 variant on `{ kind, path }`), and [`layout_nome_only_ctors!`] (3fe3dd7,
9232// 6 variants on `<Variant>(String)`) each carry on the sibling layout-side
9233// envelope. Every one of the seven wire-up sites in [`WitContract::target`]
9234// (four `ContratoWrongTarget` arms on the payload-field-mismatch axis —
9235// HTTP with subject/slot, PubSub with endpoint/slot, Store with
9236// endpoint/subject, Capability with any payload; three
9237// `ContratoMissingTarget` arms on the payload-field-absent axis — HTTP
9238// without `:endpoint`, PubSub without `:subject`, Store without `:slot`)
9239// opened the identical six-line
9240// `AplicacaoError::Contrato<Wrong|Missing>Target { de, para, wit, expected:
9241// WitTarget::<label> }` struct-literal against the local `edge()` closure
9242// returning `(de, para, wit) = self.edge_triple()` — the exact "same block
9243// re-inlined at every consumer" shape the PRIME DIRECTIVE names as a bug,
9244// on the same altitude the peer four `LayoutError` constructor families
9245// each closed on their sibling envelopes.
9246//
9247// The macro below generates one `#[must_use]` inherent constructor per
9248// variant of shape `fn <ctor>(edge: (String, String, String), expected:
9249// &'static str) -> AplicacaoError`, collapsing the seven sites onto one
9250// dispatch per arm: `return
9251// Err(AplicacaoError::contrato_wrong_target(edge(), <label>));` / `.ok_or_else(||
9252// AplicacaoError::contrato_missing_target(edge(), <label>))?`, byte-equal to
9253// the pre-lift struct-literal on the same edge fixture. The uniform four-
9254// field construction (`de, para, wit` triple-destructure onto same-named
9255// fields + `expected` verbatim) is spelled once — inside the macro —
9256// rather than at every wire-up site. `#[must_use]` fires a compile warning
9257// at any wire-up that mistakenly discards the constructed error.
9258//
9259// Every future consumer that wants to construct one of these two variants
9260// outside [`WitContract::target`] (a deferred
9261// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
9262// admission validator raising wrong-target / missing-target diagnostics
9263// on unrecognized shapes, a future `feira validate --contratos` per-caixa
9264// admission verb, a per-`WitContract` payload-axis pre-emitter probing
9265// the [`WitTarget`] arm against the declared `:endpoint`/`:subject`/`:slot`
9266// slots) reaches the variant through one call rather than re-inlining the
9267// six-line struct-literal block in lockstep with the seven in-crate
9268// wire-up sites.
9269macro_rules! contrato_target_ctors {
9270    ($($ctor:ident => $variant:ident),* $(,)?) => {
9271        impl AplicacaoError {
9272            $(
9273                #[doc = concat!(
9274                    "Construct an [`AplicacaoError::",
9275                    stringify!($variant),
9276                    "`] naming the offending edge `(de, para, wit)` triple ",
9277                    "under the given `expected` payload-field-name label. ",
9278                    "Folds the uniform `{ de, para, wit, expected }` four-",
9279                    "slot struct-literal onto one substrate primitive so ",
9280                    "every [`WitContract::target`] wire-up on this variant ",
9281                    "reads through one dispatch rather than the pre-lift ",
9282                    "six-line open-coded block. The `edge` triple threads ",
9283                    "verbatim from [`WitContract::edge_triple`] via the ",
9284                    "local `edge()` closure at the call site."
9285                )]
9286                #[must_use]
9287                pub fn $ctor(edge: (String, String, String), expected: &'static str) -> Self {
9288                    let (de, para, wit) = edge;
9289                    Self::$variant { de, para, wit, expected }
9290                }
9291            )*
9292        }
9293    };
9294}
9295
9296contrato_target_ctors! {
9297    contrato_wrong_target => ContratoWrongTarget,
9298    contrato_missing_target => ContratoMissingTarget,
9299}
9300
9301// Fold the four `AplicacaoError::{EmptyWit, ContratoEndpointEmpty,
9302// ContratoSubjectEmpty, ContratoSlotEmpty} { de, para }` wire-up sites
9303// onto one substrate-primitive family per typed variant — the paired
9304// `{ de: String, para: String }` two-slot sibling on [`AplicacaoError`]
9305// of the peer four-slot [`contrato_target_ctors!`] (14b81d5,
9306// `{ de, para, wit, expected }` on `ContratoWrongTarget` /
9307// `ContratoMissingTarget`) and of the two-slot
9308// [`AplicacaoError::entrada_host_invalid`] (17dd504, `{ host, reason }`)
9309// on the sibling per-`:entrada :host` envelope. Every one of the four
9310// wire-up sites — three under [`WitContract::target`] (the empty
9311// [`WitTarget::Http`] `:endpoint`, empty [`WitTarget::PubSub`]
9312// `:subject`, empty [`WitTarget::Store`] `:slot`) and one under
9313// [`AplicacaoSpec::validate`] (the empty `:contratos :wit` field the
9314// value-shape gate fires ahead of) — opened the identical two-line
9315// `let (de, para) = <contract>.edge_pair(); return Err(
9316// AplicacaoError::<Variant> { de, para });` block against the local
9317// [`WitContract::edge_pair`] composite-projection accessor, the exact
9318// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE
9319// names as a bug, on the same altitude the peer [`contrato_target_ctors!`]
9320// and [`AplicacaoError::entrada_host_invalid`] each closed on their
9321// sibling envelopes.
9322//
9323// The macro below generates one `#[must_use]` inherent constructor per
9324// variant of shape `fn <ctor>(edge: (String, String)) -> AplicacaoError`,
9325// collapsing the four sites onto one dispatch per arm:
9326// `return Err(AplicacaoError::<ctor>(<contract>.edge_pair()));`, byte-
9327// equal to the pre-lift struct-literal on the same edge pair. The
9328// uniform two-field construction (`de, para` pair-destructure onto
9329// same-named fields) is spelled once — inside the macro — rather than
9330// at every wire-up site. `#[must_use]` fires a compile warning at any
9331// wire-up that mistakenly discards the constructed error.
9332//
9333// Every future consumer that wants to construct one of these four
9334// variants outside the two in-crate wire-up sites (a deferred
9335// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
9336// admission validator raising empty-payload / empty-`:wit` diagnostics,
9337// a future `feira validate --contratos` per-caixa admission verb, an
9338// M4 typed WIT-registry-driven per-arm pre-emitter probing the
9339// [`WitContract`] payload slot against a canonical per-arm requirement
9340// table) reaches the variant through one call rather than re-inlining
9341// the two-line pair-destructure block in lockstep with the four
9342// in-crate wire-up sites.
9343macro_rules! contrato_empty_pair_ctors {
9344    ($($ctor:ident => $variant:ident),* $(,)?) => {
9345        impl AplicacaoError {
9346            $(
9347                #[doc = concat!(
9348                    "Construct an [`AplicacaoError::",
9349                    stringify!($variant),
9350                    "`] naming the offending edge `(de, para)` pair. ",
9351                    "Folds the uniform `{ de, para }` two-slot struct-",
9352                    "literal onto one substrate primitive so every ",
9353                    "wire-up on this variant reads through one dispatch ",
9354                    "rather than the pre-lift two-line open-coded ",
9355                    "`let (de, para) = <contract>.edge_pair(); return ",
9356                    "Err(<Variant> { de, para });` block. The `edge` ",
9357                    "pair threads verbatim from [`WitContract::edge_pair`] ",
9358                    "at the call site."
9359                )]
9360                #[must_use]
9361                pub fn $ctor(edge: (String, String)) -> Self {
9362                    let (de, para) = edge;
9363                    Self::$variant { de, para }
9364                }
9365            )*
9366        }
9367    };
9368}
9369
9370contrato_empty_pair_ctors! {
9371    empty_wit => EmptyWit,
9372    contrato_endpoint_empty => ContratoEndpointEmpty,
9373    contrato_subject_empty => ContratoSubjectEmpty,
9374    contrato_slot_empty => ContratoSlotEmpty,
9375}
9376
9377// Fold the last open-coded `AplicacaoError::ContratoEndpointNotAbsolute
9378// { de, para, endpoint: <val>.to_string() }` three-slot struct-literal
9379// wire-up site at [`WitContract::target`]'s HTTP-arm leading-slash gate
9380// onto one substrate primitive on [`AplicacaoError`] — sibling on the
9381// `{ de: String, para: String, <field>: String }` three-slot envelope of
9382// the peer [`contrato_empty_pair_ctors!`] macro just above (8580068, four
9383// variants on the paired `{ de, para }` two-slot envelope carrying the
9384// same `let (de, para) = <contract>.edge_pair(); return Err(<Variant>
9385// { de, para });` pair-destructure prelude), the peer four-slot
9386// [`contrato_pair_value_reason_ctors!`] macro (14e13f1, four variants on
9387// the paired `{ de, para, <field>: String, reason: String }` envelope
9388// carrying the parser-shaped `reason` trailer), and the peer four-slot
9389// [`contrato_target_ctors!`] macro (14b81d5, two variants on the paired
9390// `{ de, para, wit, expected: &'static str }` envelope carrying the
9391// canonical target-field-name label). The `ContratoEndpointNotAbsolute`
9392// variant is the sole occupant of the three-slot `{ de, para, <field>:
9393// String }` shape on [`AplicacaoError`] (no sibling
9394// `ContratoSubjectNotAbsolute` / `ContratoSlotNotAbsolute` — the `:subject`
9395// and `:slot` axes carry no "must start with /" invariant, since the
9396// NATS subject grammar and the WASI keyvalue slot template grammar don't
9397// share the Gateway-API-HTTPPathMatch leading-slash prelude the
9398// `:endpoint` axis does), so a full macro isn't warranted; a single
9399// `#[must_use]` inherent ctor matching the ambient
9400// `fn <ctor>(edge: (String, String), <field>: &str) -> Self` shape the
9401// peer per-`:contratos` ctor families each carry closes the last
9402// open-coded three-slot struct-literal on the envelope, matching the
9403// same standalone-ctor discipline the sibling
9404// [`crate::LayoutError::missing_entry`] (1b09f9d, one variant on the
9405// `{ kind: &'static str, path: PathBuf }` two-slot envelope),
9406// [`crate::SupervisorError::child_caixa_invalid`] /
9407// [`::child_versao_invalid`] (d2ef2ec, two variants on the paired
9408// `{ caixa: String, [versao: String,] reason: String }` two- and three-
9409// slot envelopes), and [`AplicacaoError::entrada_host_invalid`] (17dd504,
9410// one variant on the `{ host: String, reason: String }` two-slot
9411// envelope) apply on their sibling one-off variants.
9412//
9413// The one wire-up site on this variant — [`WitContract::target`]'s
9414// HTTP-arm leading-slash gate at `if !ep.starts_with('/')`, one of the
9415// six per-`:contratos` value-shape gates inside the same method body,
9416// where the other five (`ContratoWrongTarget`, `ContratoMissingTarget`,
9417// `ContratoEndpointEmpty`, `ContratoEndpointInvalid`,
9418// `ContratoWitInvalid`) each already reach through one of the three
9419// peer macro-generated ctor families above — opened the same five-line
9420// `let (de, para) = self.edge_pair(); return
9421// Err(AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint:
9422// ep.to_string() });` struct-literal against the local
9423// [`WitContract::edge_pair`] composite-projection accessor and the
9424// caller-side `&str` endpoint — the exact "same block re-inlined at
9425// every consumer" shape the PRIME DIRECTIVE names as a bug, on the same
9426// altitude the six peer `AplicacaoError` constructor families each
9427// closed on their sibling envelopes. Every guarantee in MESH-COMPOSITION
9428// §III.3 (a `:contratos :endpoint` value that doesn't start with `/`
9429// becomes a caixa-build error, not a Cilium L7 policy-side path-match
9430// silent traffic drop far from the source caixa.lisp) now routes through
9431// one substrate primitive on the envelope.
9432//
9433// The ctor below folds the site onto one dispatch:
9434// `return Err(AplicacaoError::contrato_endpoint_not_absolute(
9435// self.edge_pair(), ep));`, byte-equal to the pre-lift struct-literal
9436// on the same `(edge_pair, endpoint)` pair. The uniform three-field
9437// construction (`de, para` pair-destructure onto same-named fields +
9438// `endpoint: endpoint.to_string()`) is spelled once — inside the ctor
9439// body — rather than at the wire-up site. `#[must_use]` fires a compile
9440// warning at any future wire-up that mistakenly discards the constructed
9441// error.
9442//
9443// Every future consumer that wants to construct this variant outside
9444// [`WitContract::target`] (a deferred `mesh.pleme.io/v1alpha1/Aplicacao`
9445// CR materializer's per-`:contratos` admission validator raising the
9446// leading-slash diagnostic on unrecognized `:endpoint` shapes, a future
9447// `feira validate --contratos` per-caixa admission verb re-running the
9448// leading-slash arm on demand, an M4 typed Cilium L7 rule pre-emitter
9449// probing each declared `:endpoint` against the same shared
9450// HTTPPathMatch grammar prelude, a per-tenant per-`Aplicacao` overlay
9451// resolver rejecting a leading-slash-missing `:endpoint` against a
9452// cluster-local Cilium snapshot the M4 CR materializer projects) now
9453// reaches this variant through one call rather than re-inlining the
9454// five-line pair-destructure + struct-literal block in lockstep with
9455// the sole in-crate wire-up site.
9456impl AplicacaoError {
9457    /// Construct an [`AplicacaoError::ContratoEndpointNotAbsolute`]
9458    /// naming the offending edge `(de, para)` pair and the per-payload
9459    /// `endpoint` value. Folds the uniform `{ de, para, endpoint:
9460    /// endpoint.to_string() }` three-slot struct-literal onto one
9461    /// substrate primitive so every wire-up on this variant reads
9462    /// through one dispatch rather than the pre-lift five-line
9463    /// pair-destructure + struct-literal block. The `edge` pair threads
9464    /// verbatim from [`WitContract::edge_pair`] at the call site,
9465    /// matching the sibling [`AplicacaoError::contrato_endpoint_empty`] /
9466    /// [`AplicacaoError::contrato_endpoint_invalid`] ctors' shape on the
9467    /// paired two-slot and four-slot per-`:contratos :endpoint`
9468    /// envelopes on the same [`AplicacaoError`] type.
9469    #[must_use]
9470    pub fn contrato_endpoint_not_absolute(edge: (String, String), endpoint: &str) -> Self {
9471        let (de, para) = edge;
9472        Self::ContratoEndpointNotAbsolute {
9473            de,
9474            para,
9475            endpoint: endpoint.to_string(),
9476        }
9477    }
9478
9479    /// Construct an [`AplicacaoError::ContratoSelfLoop`] naming the
9480    /// offending self-edge's owning `caixa` and its `:wit` world
9481    /// reference, projecting both slots through the [`WitContract`]'s
9482    /// own [`WitContract::source`] and [`WitContract::world_ref`]
9483    /// scalar accessors on the substrate primitive.
9484    ///
9485    /// Folds the uniform `{ caixa: contract.source().to_string(), wit:
9486    /// contract.world_ref().to_string() }` two-slot struct-literal onto
9487    /// one substrate primitive so every wire-up on this variant reads
9488    /// through one dispatch rather than the pre-lift four-line
9489    /// twin-`.to_string()` struct-literal block. The `contract` borrow
9490    /// threads verbatim from the caller-side `for c in
9491    /// self.contratos()` iteration at the sole in-crate wire-up site
9492    /// [`AplicacaoSpec::validate_contratos`], matching the sibling
9493    /// per-`:contratos` `WitContract`-projection ctor discipline the
9494    /// peer [`AplicacaoError::empty_wit`] /
9495    /// [`AplicacaoError::contrato_endpoint_empty`] /
9496    /// [`AplicacaoError::contrato_subject_empty`] /
9497    /// [`AplicacaoError::contrato_slot_empty`] ctors carry through
9498    /// [`WitContract::edge_pair`] on the sibling two-slot `{ de, para }`
9499    /// envelope.
9500    ///
9501    /// The `caixa` slot is projected through [`WitContract::source`]
9502    /// rather than [`WitContract::destination`] to preserve byte-equal
9503    /// diagnostic ordering with the pre-lift open-coded body — a
9504    /// [`WitContract::is_self_loop`]-gated call site has
9505    /// `source() == destination()` by that predicate's own contract, so
9506    /// the two accessors are exchange-symmetric at this call site, but
9507    /// naming `source` at the ctor definition matches the pre-lift
9508    /// site's field selection and pins the discipline for any future
9509    /// consumer that constructs the variant against a not-yet-gated
9510    /// candidate contract (e.g. an M4
9511    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
9512    /// webhook re-checking a per-`(:de, :para)` patched contract, a
9513    /// future `feira validate --contratos` per-caixa verb re-running
9514    /// the self-loop diagnostic on demand, a per-tenant per-Aplicacao
9515    /// overlay resolver rejecting a self-edge introduced by a
9516    /// cluster-local `:contratos` override the M4 CR materializer
9517    /// projects).
9518    ///
9519    /// Peer of the sibling `WitContract`-projection ctors on the
9520    /// per-`:contratos` envelopes on the same [`AplicacaoError`] type —
9521    /// same "one typed dispatch on the substrate primitive, projecting
9522    /// through the paired [`WitContract`] accessors, thin projections
9523    /// at each consumer" discipline extended here onto the last unlifted
9524    /// two-slot `{ caixa: String, wit: String }` per-self-edge envelope
9525    /// inside [`AplicacaoSpec::validate_contratos`].
9526    #[must_use]
9527    pub fn contrato_self_loop(contract: &WitContract) -> Self {
9528        Self::ContratoSelfLoop {
9529            caixa: contract.source().to_string(),
9530            wit: contract.world_ref().to_string(),
9531        }
9532    }
9533
9534    /// Construct an [`AplicacaoError::MembroVersaoInvalid`] naming the
9535    /// offending `:membros :caixa` and its `:versao` requirement under
9536    /// the given `reason`. Folds the uniform `Self::MembroVersaoInvalid {
9537    /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
9538    /// reason.into() }` three-slot struct-literal onto one substrate
9539    /// primitive so every wire-up on this variant reads through one
9540    /// dispatch, matching the peer
9541    /// [`crate::SupervisorError::child_versao_invalid`] (d2ef2ec) ctor's
9542    /// shape verbatim on the sibling `SupervisorError { caixa: String,
9543    /// versao: String, reason: String }` envelope's per-`:children :versao`
9544    /// axis. `reason` accepts both `&str` literals and `format!(…)`
9545    /// outputs through the `impl Into<String>` bound so the sole
9546    /// [`AplicacaoSpec::validate_membros`] wire-up's per-`:membros`
9547    /// requirement-cascade closure (routing the shared
9548    /// [`crate::render::require_valid_versao_requirement`]-delivered
9549    /// `reason` verbatim) picks the ctor up without a per-arm wrapper
9550    /// transformation on the caller-side `reason` axis. The
9551    /// [`Membro::nome`] / [`Membro::versao_requirement`] typed-accessor
9552    /// routing the sole wire-up already threads through remains verbatim
9553    /// — the ctor's two `&str` parameters accept the two accessors'
9554    /// returns as-is with no re-allocation at the call site.
9555    #[must_use]
9556    pub fn membro_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
9557        Self::MembroVersaoInvalid {
9558            caixa: caixa.to_string(),
9559            versao: versao.to_string(),
9560            reason: reason.into(),
9561        }
9562    }
9563}
9564
9565// Fold the seven `AplicacaoError::{MembroCaixa, EntradaPara, EntradaHost,
9566// EntradaPath, PlacementCluster, PlacementAffinity, ShardKey}Invalid
9567// { <field>: <val>.to_string(), reason: <expr> }` wire-up sites onto one
9568// substrate-primitive family per typed variant — the paired
9569// `{ <field>: String, reason: String }` two-slot sibling on
9570// [`AplicacaoError`] of the peer four-slot [`contrato_target_ctors!`]
9571// (14b81d5, `{ de, para, wit, expected }` on `ContratoWrongTarget` /
9572// `ContratoMissingTarget`) and the peer two-slot
9573// [`contrato_empty_pair_ctors!`] (8580068, `{ de, para }` on `EmptyWit` /
9574// `ContratoEndpointEmpty` / `ContratoSubjectEmpty` / `ContratoSlotEmpty`)
9575// on the sibling per-`:contratos` envelopes, plus the peer four-family
9576// `LayoutError` ctor set ([`layout_violation_ctors!`] 131ca0d — 16
9577// variants on `{ caixa, issue }`, [`layout_slot_kind_ctors!`] 0419438 —
9578// 4 variants on `{ caixa, kind, slots }`, [`LayoutError::missing_entry`]
9579// 1b09f9d — 1 variant on `{ kind, path }`, [`layout_nome_only_ctors!`]
9580// 3fe3dd7 — 6 variants on `<Variant>(String)`) each carry on the
9581// sibling layout-side envelope.
9582//
9583// Every one of the seven wire-up sites — six under the per-axis
9584// `validate_*` wrappers around [`crate::render::require_valid_dns_1123_label`]
9585// (`validate_membro_caixa` on `MembroCaixaInvalid`, `validate_entrada_para`
9586// on `EntradaParaInvalid`, `validate_placement_cluster` on
9587// `PlacementClusterInvalid`, `validate_placement_affinity` on
9588// `PlacementAffinityInvalid`) plus [`crate::render::is_gateway_api_http_path`]
9589// (`validate_entrada_path` on `EntradaPathInvalid`), and two under
9590// [`validate_placement_shard_key`] (the length-cap arm and the per-byte
9591// printable-ASCII arm on `ShardKeyInvalid`) — plus the fourteen wire-up
9592// sites at [`validate_entrada_host`] (17dd504 already folded onto the
9593// pre-macro standalone `entrada_host_invalid` ctor, now converged onto
9594// the macro-generated ctor of the same name), opened the identical
9595// four-line `AplicacaoError::<Variant>Invalid
9596// { <field>: <val>.to_string(), reason: <expr> }` struct-literal against
9597// the local `<field>: &str` argument — the exact "same block re-inlined
9598// at every consumer" shape the PRIME DIRECTIVE names as a bug, on the
9599// same altitude the peer three `AplicacaoError` constructor families
9600// and the four peer `LayoutError` constructor families each closed on
9601// their sibling envelopes.
9602//
9603// The macro below generates one `#[must_use]` inherent constructor per
9604// variant of shape `fn <ctor>(<field>: &str, reason: impl Into<String>)
9605// -> AplicacaoError`, collapsing every site onto one dispatch per arm:
9606// `return Err(AplicacaoError::<ctor>(<val>, <reason>));` /
9607// `|reason| AplicacaoError::<ctor>(<val>, reason)`, byte-equal to the
9608// pre-lift struct-literal on the same `(<field>, reason)` pair. The
9609// uniform two-field construction (`<field>: <val>.to_string()`,
9610// `reason: reason.into()`) is spelled once — inside the macro — rather
9611// than at every wire-up site. The `reason: impl Into<String>` bound
9612// accepts both `&str` literals (with or without a trailing
9613// `.to_string()` at the caller) and `format!(…)` outputs verbatim so no
9614// wire-up site changes its per-arm diagnostic shape at the lift.
9615// `#[must_use]` fires a compile warning at any wire-up that mistakenly
9616// discards the constructed error rather than routing it through
9617// `return Err(…)` / `.map_err(…)` / a closure return.
9618//
9619// Every future consumer that wants to construct one of these seven
9620// variants outside the current in-crate wire-up sites (the deferred
9621// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-slot
9622// admission validators, a future `feira validate --<axis>` per-caixa
9623// admission verb, a per-`Certificate` SAN pre-emitter for cert-manager
9624// on `:entrada :host`, an M4 typed placement-engine per-cluster /
9625// per-affinity / per-shard-key pre-emitter, an M4 typed Gateway API
9626// per-path pre-emitter) reaches the variant through one call rather
9627// than re-inlining the four-line struct-literal block in lockstep with
9628// the current in-crate wire-up sites.
9629macro_rules! aplicacao_field_reason_ctors {
9630    ($($ctor:ident => $variant:ident { $field:ident }),* $(,)?) => {
9631        impl AplicacaoError {
9632            $(
9633                #[doc = concat!(
9634                    "Construct an [`AplicacaoError::",
9635                    stringify!($variant),
9636                    "`] naming the offending `",
9637                    stringify!($field),
9638                    "` under the given `reason`. Folds the uniform ",
9639                    "`{ ",
9640                    stringify!($field),
9641                    ": ",
9642                    stringify!($field),
9643                    ".to_string(), reason: reason.into() }` two-slot ",
9644                    "construction onto one substrate primitive so every ",
9645                    "wire-up on this variant reads through one dispatch ",
9646                    "rather than the pre-lift four-line struct-literal ",
9647                    "block. `reason` accepts both `&str` literals and ",
9648                    "`format!(…)` outputs through the `impl Into<String>` ",
9649                    "bound."
9650                )]
9651                #[must_use]
9652                pub fn $ctor($field: &str, reason: impl Into<String>) -> Self {
9653                    Self::$variant {
9654                        $field: $field.to_string(),
9655                        reason: reason.into(),
9656                    }
9657                }
9658            )*
9659        }
9660    };
9661}
9662
9663aplicacao_field_reason_ctors! {
9664    membro_caixa_invalid => MembroCaixaInvalid { caixa },
9665    entrada_para_invalid => EntradaParaInvalid { para },
9666    entrada_host_invalid => EntradaHostInvalid { host },
9667    entrada_path_invalid => EntradaPathInvalid { path },
9668    placement_cluster_invalid => PlacementClusterInvalid { cluster },
9669    placement_affinity_invalid => PlacementAffinityInvalid { affinity },
9670    shard_key_invalid => ShardKeyInvalid { shard_key },
9671}
9672
9673// Fold the four `AplicacaoError::Contrato{Endpoint,Subject,Slot,Wit}Invalid
9674// { de, para, <field>: <val>.to_string(), reason }` wire-up sites at
9675// [`WitContract::target`] onto one substrate-primitive family per typed
9676// variant — the paired `{ de: String, para: String, <field>: String,
9677// reason: String }` four-slot sibling on [`AplicacaoError`] of the peer
9678// four-slot [`contrato_target_ctors!`] (14b81d5, `{ de, para, wit,
9679// expected }` on `ContratoWrongTarget` / `ContratoMissingTarget`), the
9680// peer two-slot [`contrato_empty_pair_ctors!`] (8580068, `{ de, para }`
9681// on `EmptyWit` / `ContratoEndpointEmpty` / `ContratoSubjectEmpty` /
9682// `ContratoSlotEmpty`), and the peer two-slot
9683// [`aplicacao_field_reason_ctors!`] (981060b, `{ <field>: String,
9684// reason: String }` on `MembroCaixaInvalid` / `EntradaParaInvalid` /
9685// `EntradaHostInvalid` / `EntradaPathInvalid` / `PlacementClusterInvalid`
9686// / `PlacementAffinityInvalid` / `ShardKeyInvalid`) each carry on the
9687// sibling `AplicacaoError` envelopes, plus the peer four-family
9688// `LayoutError` ctor set on the sibling layout-side envelope.
9689//
9690// Every one of the four wire-up sites — four per-`:contratos` value-
9691// shape gates inside [`WitContract::target`] (the world-ref prefix
9692// [`crate::render::is_wit_world_ref`] failure on `:wit`, the HTTP arm's
9693// [`crate::render::is_gateway_api_http_path`] failure on `:endpoint`,
9694// the pub-sub arm's [`crate::render::is_nats_subject`] failure on
9695// `:subject`, the store arm's [`crate::render::is_wasi_keyvalue_slot`]
9696// failure on `:slot`) — opened the identical five-line
9697// `let (de, para) = self.edge_pair();
9698// return Err(AplicacaoError::Contrato<Field>Invalid { de, para,
9699// <field>: <val>.to_string(), reason });` block against the local
9700// [`WitContract::edge_pair`] composite-projection accessor and the
9701// per-arm `<val>: &str` argument — the exact "same block re-inlined at
9702// every consumer" shape the PRIME DIRECTIVE names as a bug, on the same
9703// altitude the peer three `AplicacaoError` constructor families and the
9704// four peer `LayoutError` constructor families each closed on their
9705// sibling envelopes. Absorbing `ContratoWitInvalid` onto the same
9706// macro closes the last unlifted `{ de, para, <field>: String, reason:
9707// String }` four-slot envelope inside `impl WitContract`, so every
9708// per-`:contratos` value-shape diagnostic on [`AplicacaoError`] now
9709// reads through this one substrate primitive.
9710//
9711// The macro below generates one `#[must_use]` inherent constructor per
9712// variant of shape `fn <ctor>(edge: (String, String), <field>: &str,
9713// reason: impl Into<String>) -> AplicacaoError`, collapsing the four
9714// sites onto one dispatch per arm:
9715// `return Err(AplicacaoError::<ctor>(self.edge_pair(), <val>, reason));`,
9716// byte-equal to the pre-lift struct-literal on the same
9717// `(edge_pair, <val>, reason)` triple. The uniform four-field
9718// construction (`de, para` pair-destructure onto same-named fields +
9719// `<field>: <val>.to_string()` + `reason: reason.into()`) is spelled
9720// once — inside the macro — rather than at every wire-up site. The
9721// `reason: impl Into<String>` bound accepts both `&str` literals and
9722// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
9723// diagnostic shape at the lift, matching the peer
9724// [`aplicacao_field_reason_ctors!`] bound on the sibling two-slot
9725// envelope. `#[must_use]` fires a compile warning at any wire-up that
9726// mistakenly discards the constructed error.
9727//
9728// Every future consumer that wants to construct one of these four
9729// variants outside [`WitContract::target`] (a deferred
9730// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
9731// admission validator raising per-payload value-shape diagnostics on
9732// unrecognized `:wit` / `:endpoint` / `:subject` / `:slot` shapes, a
9733// future `feira validate --contratos` per-caixa admission verb, an M4
9734// typed WIT-registry-driven per-arm pre-emitter probing each declared
9735// `:endpoint` / `:subject` / `:slot` payload against a canonical
9736// per-arm shape gate, a per-`Certificate` SAN pre-emitter for
9737// cert-manager on the `:endpoint` axis, an M4 typed Cilium L7 rule
9738// pre-emitter probing each `:endpoint` against the same shared
9739// HTTPPathMatch grammar) reaches the variant through one call rather
9740// than re-inlining the five-line pair-destructure + struct-literal
9741// block in lockstep with the four in-crate wire-up sites.
9742macro_rules! contrato_pair_value_reason_ctors {
9743    ($($ctor:ident => $variant:ident { $field:ident }),* $(,)?) => {
9744        impl AplicacaoError {
9745            $(
9746                #[doc = concat!(
9747                    "Construct an [`AplicacaoError::",
9748                    stringify!($variant),
9749                    "`] naming the offending edge `(de, para)` pair, the ",
9750                    "per-payload `",
9751                    stringify!($field),
9752                    "` value, and the parser-shaped `reason`. Folds the ",
9753                    "uniform `{ de, para, ",
9754                    stringify!($field),
9755                    ": ",
9756                    stringify!($field),
9757                    ".to_string(), reason: reason.into() }` four-slot ",
9758                    "construction onto one substrate primitive so every ",
9759                    "wire-up on this variant reads through one dispatch ",
9760                    "rather than the pre-lift five-line pair-destructure ",
9761                    "+ struct-literal block. The `edge` pair threads ",
9762                    "verbatim from [`WitContract::edge_pair`] at the ",
9763                    "call site; `reason` accepts both `&str` literals ",
9764                    "and `format!(…)` outputs through the `impl ",
9765                    "Into<String>` bound."
9766                )]
9767                #[must_use]
9768                pub fn $ctor(edge: (String, String), $field: &str, reason: impl Into<String>) -> Self {
9769                    let (de, para) = edge;
9770                    Self::$variant {
9771                        de,
9772                        para,
9773                        $field: $field.to_string(),
9774                        reason: reason.into(),
9775                    }
9776                }
9777            )*
9778        }
9779    };
9780}
9781
9782contrato_pair_value_reason_ctors! {
9783    contrato_endpoint_invalid => ContratoEndpointInvalid { endpoint },
9784    contrato_subject_invalid => ContratoSubjectInvalid { subject },
9785    contrato_slot_invalid => ContratoSlotInvalid { slot },
9786    contrato_wit_invalid => ContratoWitInvalid { wit },
9787}
9788
9789// Fold the five `AplicacaoError::{ContratoMemberMissing, MembroVersaoEmpty,
9790// MembroDuplicate, MembroIsSelfAplicacao} { caixa: <&str>.to_string() }`
9791// caixa-only struct-variant wire-up sites at
9792// [`WitContract::require_endpoints_in`] (two sites, the `:contratos :de` and
9793// `:contratos :para` arms of `ContratoMemberMissing`),
9794// [`AplicacaoSpec::validate_membros`] (two sites, the empty-`:versao` arm of
9795// `MembroVersaoEmpty` and the per-`:membros` dedup arm of `MembroDuplicate`),
9796// and [`validate_no_self_membership`] (one site, the parent-`:nome`
9797// self-membership arm of `MembroIsSelfAplicacao`) onto one substrate primitive
9798// per typed variant — the sibling on the M3 mesh `AplicacaoError` envelope of
9799// the peer [`crate::supervisor::supervisor_caixa_only_ctors!`] macro (db09650,
9800// three variants on `{ caixa: String }` at
9801// [`crate::SupervisorSpec::validate_children`] and
9802// [`crate::supervisor::validate_no_self_supervision`]) on the sibling M2
9803// `SupervisorError` envelope, extending the same "one substrate primitive per
9804// typed variant on the single-slot `{ <ident>: String }` envelope shape" fold
9805// discipline onto the M3 mesh side. Peers on peer envelopes: the M2 sibling
9806// [`crate::behavior::behavior_slot_path_ctors!`] (67c31ec, 3 variants on
9807// `{ slot: &'static str, path: PathBuf }`) two-slot fold on the `:behavior`
9808// envelope; the M2 sibling [`crate::upgrade::upgrade_from_script_ctors!`]
9809// (8e67041, 3 variants on `{ from: String, script: PathBuf }`) and
9810// [`crate::upgrade::upgrade_script_only_ctors!`] (7468ca9, 3 variants on
9811// `{ script: PathBuf }`) two folds on the sibling `:upgrade-from` envelope;
9812// the sibling [`crate::dep::dep_nome_only_ctors!`] (792aa92, 5 variants on
9813// `{ nome: String }`), [`crate::dep::fonte_caminho_ctors!`] (f85f145, 11
9814// variants on `{ nome, caminho }`), and
9815// [`crate::dep::fonte_caminho_byte_ctors!`] (0e35793, 12 variants on
9816// `{ nome, caminho, byte }`) folds on the sibling `DepError` envelope; the
9817// peer three `AplicacaoError` sub-family folds already lifted here
9818// ([`contrato_target_ctors!`] 14b81d5, [`contrato_empty_pair_ctors!`] 8580068,
9819// [`aplicacao_field_reason_ctors!`] 981060b,
9820// [`contrato_pair_value_reason_ctors!`] 14e13f1); the peer four `LayoutError`
9821// families ([`crate::layout::layout_violation_ctors!`] 131ca0d,
9822// [`crate::layout::layout_slot_kind_ctors!`] 0419438,
9823// [`crate::LayoutError::missing_entry`] 1b09f9d,
9824// [`crate::layout::layout_nome_only_ctors!`] 3fe3dd7); and the three
9825// [`crate::limits::limits_codec_value_*_ctors!`] codec families (81c856c).
9826//
9827// Each of the five wire-up sites on this shape (two on `ContratoMemberMissing`
9828// at the per-`:contratos :de`/`:para` unknown-member arms, one on
9829// `MembroVersaoEmpty` at the per-`:membros` empty-semver-requirement arm, one
9830// on `MembroDuplicate` at the per-`:membros` dedup arm, one on
9831// `MembroIsSelfAplicacao` at the parent-`:nome` self-membership arm) opened
9832// the identical `AplicacaoError::<Variant> { caixa: <&str>.to_string() }`
9833// three-line struct-literal against a caller-side `&str` — the exact "same
9834// block re-inlined at every consumer" shape the PRIME DIRECTIVE names as a
9835// bug, on the same altitude the peer `SupervisorError` /
9836// `AplicacaoError` (three prior sub-families) / `DepError` / `LayoutError` /
9837// `UpgradeError` / `BehaviorError` / `LimitsError` families each closed on
9838// their sibling envelopes. The four variants share one `{ caixa: String }`
9839// shape, so the fold routes each wire-up site through one dispatch per typed
9840// variant.
9841//
9842// The macro below generates one `#[must_use]` inherent constructor per
9843// variant of shape `fn <ctor>(caixa: &str) -> AplicacaoError`, so every
9844// wire-up site collapses onto one dispatch:
9845// `AplicacaoError::<ctor>(<&str>)`, byte-equal to the pre-lift struct-literal
9846// on the same `&str` fixture. The uniform one-field construction
9847// (`caixa: caixa.to_string()`) is spelled once — inside the macro — rather
9848// than at every wire-up site. Every constructor is `#[must_use]` so a caller
9849// who mistakenly discards the constructed error trips a compile warning at
9850// the wire-up site.
9851//
9852// Every future consumer that wants to construct one of these four variants
9853// outside the current in-crate wire-up sites — a deferred
9854// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook
9855// re-checking one added/renamed `:membros` entry against the sibling
9856// `:contratos` graph, a future `feira validate --membros` per-caixa admission
9857// verb re-checking each declared `:membros` entry's `:caixa` name against the
9858// same axes, a per-tenant per-`Aplicacao` overlay resolver rejecting a
9859// duplicate / self-referencing / unknown-membered `:contratos` entry against
9860// a cluster-local snapshot the M4 CR materializer projects — now reaches each
9861// variant through one call rather than re-inlining the three-line
9862// struct-literal in lockstep with the five in-crate wire-up sites.
9863macro_rules! aplicacao_caixa_only_ctors {
9864    ($($ctor:ident => $variant:ident),* $(,)?) => {
9865        impl AplicacaoError {
9866            $(
9867                #[doc = concat!(
9868                    "Construct an [`AplicacaoError::",
9869                    stringify!($variant),
9870                    "`] naming the offending `:membros :caixa` (or ",
9871                    "parent `:nome`, on the self-membership arm; or ",
9872                    "`:contratos :de`/`:para`, on the unknown-member ",
9873                    "arm). Folds the uniform `Self::",
9874                    stringify!($variant),
9875                    " { caixa: caixa.to_string() }` one-field ",
9876                    "struct-literal onto one substrate primitive so ",
9877                    "every wire-up on this variant reads through one ",
9878                    "dispatch rather than the pre-lift three-line ",
9879                    "open-coded struct-literal block."
9880                )]
9881                #[must_use]
9882                pub fn $ctor(caixa: &str) -> Self {
9883                    Self::$variant { caixa: caixa.to_string() }
9884                }
9885            )*
9886        }
9887    };
9888}
9889
9890aplicacao_caixa_only_ctors! {
9891    contrato_member_missing => ContratoMemberMissing,
9892    membro_versao_empty => MembroVersaoEmpty,
9893    membro_duplicate => MembroDuplicate,
9894    membro_is_self_aplicacao => MembroIsSelfAplicacao,
9895}
9896
9897// Fold the three `AplicacaoError::{EntradaPathNotAbsolute,
9898// EntradaPathDuplicate} { path: <val>.to_string() | <val>.clone() }` wire-up
9899// sites onto one substrate-primitive family per typed variant — the direct
9900// per-`:entrada :paths` value-shape sibling of the peer
9901// `aplicacao_caixa_only_ctors!` (d9f6867, `{ caixa: String }` on
9902// `ContratoMemberMissing` / `MembroVersaoEmpty` / `MembroDuplicate` /
9903// `MembroIsSelfAplicacao`) on the sibling per-`:membros :caixa` envelope, and
9904// per-`:entrada :para` sibling of the peer `contrato_empty_pair_ctors!`
9905// (8580068, `{ de, para }` on `EmptyWit` / `ContratoEndpointEmpty` /
9906// `ContratoSubjectEmpty` / `ContratoSlotEmpty`) on the per-`:contratos` edge
9907// envelope. Same shape family as the [`crate::dep::dep_nome_only_ctors!`]
9908// (792aa92, `{ nome: String }` on five `DepError` variants) fold on the peer
9909// `:deps` envelope — every single-`String`-slot error family in caixa-core
9910// now reaches through one substrate primitive per typed variant.
9911//
9912// The three wire-up sites — one under [`validate_entrada_path`]'s
9913// leading-slash grammar arm (`EntradaPathNotAbsolute` against
9914// `path: &str`), one under the per-`:entrada :paths` loop's identical
9915// arm (`EntradaPathNotAbsolute` against a `&String` head via `.clone()`),
9916// and one under the per-`:entrada :paths` loop's dedup arm
9917// (`EntradaPathDuplicate` against the same `&String` via
9918// [`crate::render::insert_first_seen`]'s ctor closure) — opened the identical
9919// `AplicacaoError::EntradaPath<Variant> { path: <val>.to_string() | .clone() }`
9920// three-line struct-literal against a caller-side `&str` / `&String`, the
9921// exact "same block re-inlined at every consumer" shape the PRIME DIRECTIVE
9922// names as a bug. Every one of the compile-time guarantees in
9923// MESH-COMPOSITION.md §III.3 (a `:entrada :paths` entry whose value doesn't
9924// start with `/` becomes a caixa-build error, not a Gateway API webhook
9925// rejection at `kubectl apply` time; a duplicated `:entrada :paths` entry
9926// becomes a caixa-build error, not a silent last-writer-wins render) now
9927// routes through one dispatch per typed variant at every emit site.
9928//
9929// The macro below generates one `#[must_use]` inherent constructor per
9930// variant of shape `fn <ctor>(path: &str) -> AplicacaoError`, collapsing
9931// every wire-up site onto one dispatch:
9932// `AplicacaoError::<ctor>(<path>)` (byte-equal to the pre-lift struct-literal
9933// on the same `&str` fixture) or the `&String` sites through
9934// `p.as_str()` (byte-equal on the same slice-view). The uniform one-field
9935// construction (`path: path.to_string()`) is spelled once — inside the
9936// macro — rather than at every wire-up site. Every ctor is `#[must_use]` so
9937// a caller who mistakenly discards the constructed error trips a compile
9938// warning at the wire-up site.
9939//
9940// Every future consumer that wants to construct one of these two variants
9941// outside the current in-crate wire-up sites — a deferred
9942// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook
9943// per-`:entrada :paths` re-check against a cluster-local Gateway API
9944// snapshot, a future `feira validate --entrada` per-caixa admission verb
9945// re-checking each declared `:paths` entry against the same axes, a
9946// per-tenant per-`Aplicacao` overlay resolver rejecting a
9947// duplicate / non-absolute `:paths` entry against a cluster-local Gateway
9948// snapshot the M4 CR materializer projects — now reaches each variant
9949// through one call rather than re-inlining the three-line struct-literal in
9950// lockstep with the three in-crate wire-up sites.
9951macro_rules! aplicacao_path_only_ctors {
9952    ($($ctor:ident => $variant:ident),* $(,)?) => {
9953        impl AplicacaoError {
9954            $(
9955                #[doc = concat!(
9956                    "Construct an [`AplicacaoError::",
9957                    stringify!($variant),
9958                    "`] naming the offending `:entrada :paths` entry. ",
9959                    "Folds the uniform `Self::",
9960                    stringify!($variant),
9961                    " { path: path.to_string() }` one-field ",
9962                    "struct-literal onto one substrate primitive so ",
9963                    "every wire-up on this variant reads through one ",
9964                    "dispatch rather than the pre-lift three-line ",
9965                    "open-coded struct-literal block."
9966                )]
9967                #[must_use]
9968                pub fn $ctor(path: &str) -> Self {
9969                    Self::$variant { path: path.to_string() }
9970                }
9971            )*
9972        }
9973    };
9974}
9975
9976aplicacao_path_only_ctors! {
9977    entrada_path_not_absolute => EntradaPathNotAbsolute,
9978    entrada_path_duplicate => EntradaPathDuplicate,
9979}
9980
9981// Fold the eight `AplicacaoError::Policy<Slot><Axis> { <field>: <val> }`
9982// one-slot `Copy`-scalar wire-up sites at [`MeshPolicy::validate`] onto one
9983// substrate-primitive family per typed variant — the per-`:politicas` copy-
9984// scalar `{ timeout | retries | max_failures | window | rate: Duration | u32 }`
9985// sibling of the peer per-`:membros :caixa` [`aplicacao_caixa_only_ctors!`]
9986// (d9f6867, `{ caixa: String }` on `ContratoMemberMissing` /
9987// `MembroVersaoEmpty` / `MembroDuplicate` / `MembroIsSelfAplicacao`) and the
9988// peer per-`:entrada :paths` [`aplicacao_path_only_ctors!`] (3ba8de6,
9989// `{ path: String }` on `EntradaPathNotAbsolute` / `EntradaPathDuplicate`) on
9990// the `String`-slot axis, and the peer per-`:politicas` cross-axis
9991// [`AplicacaoError::Policy*`] cascade [`MeshPolicy::first_cross_axis_violation`]
9992// carries at line 3064 on the same M3 mesh envelope.
9993//
9994// The eight wire-up sites inside [`MeshPolicy::validate`] at lines 3170-3218
9995// each opened the identical `|<slot>| AplicacaoError::Policy<Slot><Axis>
9996// { <slot> }` one-line struct-literal closure against the caller-side
9997// `<slot>: <ty>` argument that the shared
9998// [`crate::render::require_positive_bounded_u32`] /
9999// [`crate::render::require_positive_canonical_bounded_duration`] gate rebinds
10000// verbatim under the `impl FnOnce(u32) -> AplicacaoError` /
10001// `impl FnOnce(Duration) -> AplicacaoError` bracket-closure slots (plus one
10002// direct `return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical
10003// { window: rl.window() })` at the `:rate-limit :window` canonical-form arm
10004// on line 3211) — the exact "same one-line struct-literal re-inlined at every
10005// consumer" shape the PRIME DIRECTIVE names as a bug, on the last remaining
10006// per-`:politicas` per-axis `AplicacaoError` variant family that had not yet
10007// been folded onto a substrate primitive.
10008//
10009// The macro below generates one `#[must_use] pub const fn <ctor>(<field>: <ty>)
10010// -> AplicacaoError` per variant of shape `Self::<variant> { <field> }`,
10011// collapsing every wire-up onto either one direct dispatch
10012// (`return Err(AplicacaoError::<ctor>(<val>))`, byte-equal to the pre-lift
10013// struct-literal on the same `Copy`-`<ty>` fixture) or one bare function
10014// pointer at the `impl FnOnce(<ty>) -> AplicacaoError` bracket-closure slot
10015// (`AplicacaoError::<ctor>` in the position where every pre-lift site spelled
10016// `|<slot>| AplicacaoError::<Variant> { <slot> }`) — Rust's function-pointer-
10017// to-`FnOnce` coercion on any `fn(<ty>) -> AplicacaoError` inherent
10018// constructor with matching arity and signature. The `const fn` qualifier
10019// preserves the pre-lift `Copy`-pass-through's zero-runtime-work property
10020// verbatim (no `.to_string()` / `.into()` allocation, no branching); the
10021// per-variant `$field:ident` axis re-uses the enum's canonical field name so
10022// the generated ctor's parameter name matches every wire-up's local binding
10023// (`|timeout|` calls `policy_timeout_not_canonical(timeout)`, etc.), matching
10024// the peer [`aplicacao_field_reason_ctors!`] / [`aplicacao_caixa_only_ctors!`]
10025// / [`aplicacao_path_only_ctors!`] convention. `#[must_use]` fires a compile
10026// warning at any wire-up that mistakenly discards the constructed error, on
10027// the same footing as every sibling `AplicacaoError` / `DepError` /
10028// `SupervisorError` / `LayoutError` / `LimitsError` / `BehaviorError` /
10029// `UpgradeError` ctor macro (14b81d5 / 8580068 / 981060b / 14e13f1 / 81c856c
10030// / 8e67041 / 7468ca9 / 67c31ec / d2ef2ec / f85f145 / 0e35793 / 792aa92 /
10031// 6f5e0cd / 3fe3dd7 / 1b09f9d / 131ca0d / 0419438).
10032//
10033// Every future consumer that wants to construct one of these eight variants
10034// outside [`MeshPolicy::validate`] — a deferred
10035// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook re-
10036// checking each `:politicas` axis against a cluster-local `:politicas` cap
10037// overlay, a future per-`:contratos`-edge `:politicas` override the
10038// MESH-COMPOSITION §III.2 #3 roadmap acknowledges resolving an *effective*
10039// per-edge [`MeshPolicy`] and emitting the same per-axis diagnostic on the
10040// same input as `feira build`, an M4 per-cluster `:politicas`-cap resolver
10041// projecting a per-tenant per-axis ceiling into the same diagnostic shape,
10042// a future `feira validate --politicas` per-caixa admission verb re-checking
10043// each declared per-axis value against the same bounds — now reaches each
10044// variant through one call rather than re-inlining the one-line struct-
10045// literal in lockstep with the seven `MeshPolicy::validate` wire-up sites,
10046// which is exactly the invariant every prior ctor-macro lift already closed
10047// on its sibling envelope. Closes the last remaining per-`:politicas`
10048// per-axis `AplicacaoError` variant family that had not yet been folded onto
10049// a substrate primitive; the compound cross-axis variants
10050// ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`] / `*RateLimit` /
10051// `*RetriesBurst`) each carry a distinct multi-slot field shape and are folded
10052// on a separate axis by [`MeshPolicy::first_cross_axis_violation`].
10053macro_rules! aplicacao_policy_scalar_ctors {
10054    ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
10055        impl AplicacaoError {
10056            $(
10057                #[doc = concat!(
10058                    "Construct an [`AplicacaoError::",
10059                    stringify!($variant),
10060                    "`] naming the offending per-`:politicas` `",
10061                    stringify!($field),
10062                    "` scalar. Folds the uniform `Self::",
10063                    stringify!($variant),
10064                    " { ",
10065                    stringify!($field),
10066                    " }` one-field `Copy`-pass-through struct-literal onto ",
10067                    "one substrate primitive so every per-axis wire-up on ",
10068                    "this variant reads through one dispatch — as a direct ",
10069                    "call (`AplicacaoError::",
10070                    stringify!($ctor),
10071                    "(<val>)`, byte-equal to the pre-lift struct-literal on ",
10072                    "the same `Copy`-`",
10073                    stringify!($ty),
10074                    "` fixture) or as a bare function pointer in the ",
10075                    "`impl FnOnce(",
10076                    stringify!($ty),
10077                    ") -> AplicacaoError` bracket-closure slot every ",
10078                    "`crate::render::require_positive_bounded_*` / ",
10079                    "`crate::render::require_positive_canonical_bounded_*` ",
10080                    "gate carries — rather than the pre-lift open-coded ",
10081                    "one-line closure over the same one-field struct-",
10082                    "literal. `const fn` preserves the `Copy`-pass-through's ",
10083                    "zero-runtime-work property verbatim."
10084                )]
10085                #[must_use]
10086                pub const fn $ctor($field: $ty) -> Self {
10087                    Self::$variant { $field }
10088                }
10089            )*
10090        }
10091    };
10092}
10093
10094aplicacao_policy_scalar_ctors! {
10095    policy_timeout_not_canonical => PolicyTimeoutNotCanonical { timeout: Duration },
10096    policy_timeout_exceeds_cap => PolicyTimeoutExceedsCap { timeout: Duration },
10097    policy_retries_exceeds_cap => PolicyRetriesExceedsCap { retries: u32 },
10098    policy_breaker_max_failures_exceeds_cap =>
10099        PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
10100    policy_breaker_window_not_canonical =>
10101        PolicyBreakerWindowNotCanonical { window: Duration },
10102    policy_breaker_window_exceeds_cap =>
10103        PolicyBreakerWindowExceedsCap { window: Duration },
10104    policy_rate_limit_exceeds_cap => PolicyRateLimitExceedsCap { rate: u32 },
10105    policy_rate_limit_window_not_canonical =>
10106        PolicyRateLimitWindowNotCanonical { window: Duration },
10107}
10108
10109#[cfg(test)]
10110mod tests {
10111    use super::*;
10112
10113    fn membro(name: &str, ver: &str) -> Membro {
10114        Membro {
10115            caixa: name.into(),
10116            versao: ver.into(),
10117        }
10118    }
10119
10120    fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
10121        WitContract {
10122            de: de.into(),
10123            para: para.into(),
10124            wit: "wasi:http/proxy".into(),
10125            endpoint: Some(ep.into()),
10126            subject: None,
10127            slot: None,
10128        }
10129    }
10130
10131    fn three_member_spec() -> AplicacaoSpec {
10132        AplicacaoSpec {
10133            membros: vec![
10134                membro("catalog", "^0.1"),
10135                membro("cart", "^0.1"),
10136                membro("payment", "^0.2"),
10137            ],
10138            contratos: vec![
10139                contract_http("cart", "catalog", "/products/:id"),
10140                contract_http("cart", "payment", "/charge"),
10141            ],
10142            politicas: MeshPolicy {
10143                timeout: Some(Duration::from_secs(30)),
10144                retries: Some(3),
10145                mtls_required: Some(true),
10146                ..Default::default()
10147            },
10148            placement: Placement {
10149                estrategia: PlacementStrategy::Replicated,
10150                clusters: vec!["rio".into(), "mar".into()],
10151                affinity: Some("data-locality".into()),
10152                shard_key: None,
10153            },
10154            entrada: Some(Entrada {
10155                host: "checkout.quero.cloud".into(),
10156                para: "cart".into(),
10157                paths: vec!["/api/cart".into(), "/api/products".into()],
10158                port: 8080,
10159            }),
10160        }
10161    }
10162
10163    #[test]
10164    fn happy_path_validates() {
10165        three_member_spec().validate().unwrap();
10166    }
10167
10168    #[test]
10169    fn rejects_empty_membros() {
10170        let mut s = three_member_spec();
10171        s.membros = vec![];
10172        assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
10173    }
10174
10175    #[test]
10176    fn rejects_empty_membro_caixa() {
10177        // A `:caixa ""` entry has no name to render into programs.yaml
10178        // and no caixa.lisp to resolve at lacre time.
10179        let mut s = three_member_spec();
10180        s.membros[1].caixa = String::new();
10181        assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
10182    }
10183
10184    #[test]
10185    fn rejects_empty_membro_versao() {
10186        // A `:versao ""` entry can't pin a semver constraint, so the
10187        // lacre pipeline fails far from the source.
10188        let mut s = three_member_spec();
10189        s.membros[2].versao = String::new();
10190        let err = s.validate().unwrap_err();
10191        assert!(
10192            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
10193            "got {err:?}"
10194        );
10195    }
10196
10197    #[test]
10198    fn rejects_duplicate_membro_caixa() {
10199        // Two `:membros` entries with the same `:caixa` collapse to one
10200        // node in the membership HashSet, which masks `:contratos`
10201        // membership errors and produces duplicate programs.yaml entries.
10202        let mut s = three_member_spec();
10203        s.membros.push(membro("cart", "^0.2"));
10204        let err = s.validate().unwrap_err();
10205        assert!(
10206            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
10207            "got {err:?}"
10208        );
10209    }
10210
10211    #[test]
10212    fn rejects_invalid_membro_versao_requirement() {
10213        // The fail-before-pass-after pin: a non-empty but malformed
10214        // semver requirement (`"^bad-version"`) silently passed
10215        // `validate()` on every pre-gate codebase because the prior
10216        // shape only refused the empty string. The parse failure
10217        // surfaced far downstream at lacre-resolve time with a
10218        // `semver::Error` that didn't name which `:membros` entry
10219        // carried the typo. The new gate moves the check to caixa-build
10220        // time at the source caixa.lisp.
10221        let mut s = three_member_spec();
10222        s.membros[2].versao = "^bad-version".into();
10223        let err = s.validate().unwrap_err();
10224        assert!(
10225            matches!(
10226                err,
10227                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
10228                    if caixa == "payment" && versao == "^bad-version"
10229            ),
10230            "got {err:?}"
10231        );
10232    }
10233
10234    #[test]
10235    fn rejects_membro_versao_with_double_caret_typo() {
10236        // `"^^0.1"` is the canonical doubled-caret typo — looks like a
10237        // Cargo-shaped requirement on first glance but fails the parser
10238        // because semver doesn't accept stacked operators. Pin this
10239        // adjacent-shape footgun explicitly so a future relaxation that
10240        // accepts "looks-canonical-but-isn't" forms surfaces here.
10241        let mut s = three_member_spec();
10242        s.membros[0].versao = "^^0.1".into();
10243        let err = s.validate().unwrap_err();
10244        assert!(
10245            matches!(
10246                err,
10247                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
10248                    if caixa == "catalog" && versao == "^^0.1"
10249            ),
10250            "got {err:?}"
10251        );
10252    }
10253
10254    #[test]
10255    fn rejects_membro_versao_with_v_prefixed_tag() {
10256        // `"v0.1"` is the canonical "git-tag-shape leaking into the
10257        // semver requirement slot" typo — an author copies the
10258        // publish-side git-tag string verbatim into `:versao`, but
10259        // Cargo's semver parser rejects the leading `v` (only digits +
10260        // canonical operators are valid in the major-version
10261        // position). The gate's diagnostic names which member entry
10262        // carried the v-prefix so the fix is one edit, not a grep
10263        // through every member's `:versao`. (Note: bare `x`-glob
10264        // shorthands like `^0.1.x` are *accepted* by the semver crate
10265        // as an `*` wildcard on the patch axis — they're a Cargo-side
10266        // valid shape, not a typo, so the gate intentionally lets them
10267        // through.)
10268        let mut s = three_member_spec();
10269        s.membros[1].versao = "v0.1".into();
10270        let err = s.validate().unwrap_err();
10271        assert!(
10272            matches!(
10273                err,
10274                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
10275                    if caixa == "cart" && versao == "v0.1"
10276            ),
10277            "got {err:?}"
10278        );
10279    }
10280
10281    #[test]
10282    fn accepts_canonical_membro_versao_forms() {
10283        // The four Cargo-shaped requirement forms `:deps :versao`
10284        // already accepts via `crate::parse_requirement` must pass the
10285        // membros gate without re-validating at the resolver layer.
10286        // Pin every leg so a future tightening of the canonical set
10287        // surfaces here as a test failure.
10288        for form in [
10289            "^0.1",      // caret — minor-range pin (the most common shape)
10290            "~0.1.2",    // tilde — patch-range pin
10291            "0.1.0",     // exact — single-version pin
10292            "*",         // wildcard — explicitly any-version (semver::VersionReq::STAR)
10293            ">=0.1, <2", // multi-range — comma-separated comparators
10294        ] {
10295            let mut s = three_member_spec();
10296            for m in &mut s.membros {
10297                m.versao = form.into();
10298            }
10299            s.validate()
10300                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
10301        }
10302    }
10303
10304    #[test]
10305    fn membro_versao_empty_takes_precedence_over_invalid() {
10306        // Order pin: the existing `MembroVersaoEmpty` diagnostic
10307        // (which doesn't try to parse) fires before the new
10308        // `MembroVersaoInvalid` parse-side diagnostic, so an empty
10309        // `:versao` keeps its narrower error message — `parse_requirement`
10310        // would also reject `""`, but the empty-string arm is the more
10311        // self-locating diagnostic for the author.
10312        let mut s = three_member_spec();
10313        s.membros[1].versao = String::new();
10314        let err = s.validate().unwrap_err();
10315        assert!(
10316            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
10317            "got {err:?}"
10318        );
10319    }
10320
10321    #[test]
10322    fn membro_versao_invalid_fires_before_duplicate_check() {
10323        // Order pin: a malformed requirement on a non-duplicate entry
10324        // surfaces *its own* diagnostic (which names the offending
10325        // `:versao` string), even when a later entry would otherwise
10326        // collapse onto an earlier name. The per-entry shape gate runs
10327        // inline before the duplicate-key insert, parallel to
10328        // `membros_validation_runs_before_contratos_membership_check`
10329        // and `duplicate_contrato_gate_runs_after_target_shape_check`.
10330        let mut s = three_member_spec();
10331        s.membros[0].versao = "^bad".into();
10332        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
10333        let err = s.validate().unwrap_err();
10334        assert!(
10335            matches!(
10336                err,
10337                AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
10338            ),
10339            "got {err:?}"
10340        );
10341    }
10342
10343    #[test]
10344    fn membro_versao_invalid_diagnostic_carries_offending_versao() {
10345        // The diagnostic-shape pin: the error names the offending
10346        // `:versao` value verbatim so the author can grep their
10347        // caixa.lisp without re-running the build, and carries a
10348        // non-empty `reason` from `semver::VersionReq::parse` so the
10349        // parser's own wording flows through to the diagnostic.
10350        let mut s = three_member_spec();
10351        s.membros[2].versao = "not-a-req".into();
10352        let err = s.validate().unwrap_err();
10353        let AplicacaoError::MembroVersaoInvalid {
10354            caixa,
10355            versao,
10356            reason,
10357        } = err
10358        else {
10359            panic!("expected MembroVersaoInvalid, got other variant");
10360        };
10361        assert_eq!(caixa, "payment");
10362        assert_eq!(versao, "not-a-req");
10363        assert!(
10364            !reason.is_empty(),
10365            "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
10366        );
10367    }
10368
10369    #[test]
10370    fn membro_versao_invalid_runs_before_contratos_check() {
10371        // A malformed `:versao` on any member must surface its own
10372        // diagnostic (which names *which* member to fix) before any
10373        // `:contratos` membership lookup raises `ContratoMemberMissing`.
10374        // The `:contratos` gate runs after `validate_membros`, so this
10375        // is structurally guaranteed — pin it explicitly so a future
10376        // refactor that reorders the gates surfaces here.
10377        let mut s = three_member_spec();
10378        s.membros[1].versao = "^^0.1".into();
10379        // Add a contrato whose `:para` doesn't exist — would normally
10380        // raise ContratoMemberMissing at the membership lookup, but
10381        // the membros gate must fire first.
10382        s.contratos
10383            .push(contract_http("cart", "phantom", "/never-reached"));
10384        let err = s.validate().unwrap_err();
10385        assert!(
10386            matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
10387            "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
10388        );
10389    }
10390
10391    #[test]
10392    fn membros_validation_runs_before_contratos_membership_check() {
10393        // If `:membros` carries a duplicate, the membership-collapse
10394        // would silently accept a `:contratos :para "phantom"` so long
10395        // as some entry hashes to "phantom". Pinning order: the
10396        // duplicate-membros error fires first, regardless of whether
10397        // contratos reference real members.
10398        let mut s = three_member_spec();
10399        s.membros = vec![
10400            membro("cart", "^0.1"),
10401            membro("cart", "^0.2"),
10402            membro("catalog", "^0.1"),
10403            membro("payment", "^0.1"),
10404        ];
10405        let err = s.validate().unwrap_err();
10406        assert!(
10407            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
10408            "got {err:?}"
10409        );
10410    }
10411
10412    #[test]
10413    fn distinct_membros_validate() {
10414        // Pin the happy-path: every `:membros` entry has a non-empty
10415        // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
10416        // The fixture already satisfies this; this test makes the
10417        // invariant explicit so a future refactor of the fixture can't
10418        // silently break the guarantee.
10419        three_member_spec().validate().unwrap();
10420    }
10421
10422    // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
10423
10424    #[test]
10425    fn rejects_membro_caixa_with_uppercase() {
10426        // The canonical "I copied the Servico's display name verbatim"
10427        // typo — caixa names are lowercase per K8s DNS-1123 label rule,
10428        // but author tools often round-trip a TitleCase or CamelCase
10429        // identifier from an ADR or a sketch. Pin the diagnostic names
10430        // the offending name and suggests the lower-cased fix in one
10431        // edit, mirroring the `rejects_entrada_host_with_uppercase`
10432        // gate's shape (c7d05ec).
10433        let mut s = three_member_spec();
10434        s.membros[1].caixa = "Cart".into();
10435        let err = s.validate().unwrap_err();
10436        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
10437            panic!("expected MembroCaixaInvalid, got other variant");
10438        };
10439        assert_eq!(caixa, "Cart");
10440        assert!(
10441            reason.contains("uppercase"),
10442            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
10443        );
10444        assert!(
10445            reason.contains("\"cart\""),
10446            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
10447        );
10448    }
10449
10450    #[test]
10451    fn rejects_membro_caixa_with_underscore() {
10452        // The canonical "I'm thinking of a Python module / Postgres
10453        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
10454        // label schema. K8s rejects `metadata.name: my_cart` at admission
10455        // time with an opaque `field is invalid` (no source-citing
10456        // diagnostic). The gate moves it to caixa-build time.
10457        let mut s = three_member_spec();
10458        s.membros[0].caixa = "my_cart".into();
10459        let err = s.validate().unwrap_err();
10460        assert!(
10461            matches!(
10462                err,
10463                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
10464                    if caixa == "my_cart" && reason.contains('_')
10465            ),
10466            "got {err:?}"
10467        );
10468    }
10469
10470    #[test]
10471    fn rejects_membro_caixa_with_dot() {
10472        // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
10473        // subdomain — even though K8s `metadata.name` itself accepts
10474        // dots (DNS-1123 subdomain rule), this string also lands as a
10475        // K8s Service name (DNS-1035 label — no dots) and as a label
10476        // value on identity-based Cilium selectors. The strictest floor
10477        // among the use sites wins. The "I want to namespace my member
10478        // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
10479        let mut s = three_member_spec();
10480        s.membros[2].caixa = "team.cart".into();
10481        let err = s.validate().unwrap_err();
10482        assert!(
10483            matches!(
10484                err,
10485                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
10486                    if caixa == "team.cart" && reason.contains('.')
10487            ),
10488            "got {err:?}"
10489        );
10490    }
10491
10492    #[test]
10493    fn rejects_membro_caixa_with_leading_hyphen() {
10494        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
10495        // with an alphanumeric. The K8s apiserver rejects `-cart`
10496        // outright; the renderer would emit a `metadata.name: "-cart"`
10497        // that fails admission far from the source caixa.lisp.
10498        let mut s = three_member_spec();
10499        s.membros[0].caixa = "-cart".into();
10500        let err = s.validate().unwrap_err();
10501        assert!(
10502            matches!(
10503                err,
10504                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
10505                    if caixa == "-cart" && reason.contains("start and end")
10506            ),
10507            "got {err:?}"
10508        );
10509    }
10510
10511    #[test]
10512    fn rejects_membro_caixa_with_trailing_hyphen() {
10513        // The symmetric arm of the boundary rule. Pin separately so
10514        // both ends of the label are covered against a future relaxation
10515        // that only checks one boundary.
10516        let mut s = three_member_spec();
10517        s.membros[1].caixa = "cart-".into();
10518        let err = s.validate().unwrap_err();
10519        assert!(
10520            matches!(
10521                err,
10522                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
10523                    if caixa == "cart-"
10524            ),
10525            "got {err:?}"
10526        );
10527    }
10528
10529    #[test]
10530    fn rejects_membro_caixa_with_unicode() {
10531        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
10532        // (`xn--…`) by the author before it reaches K8s. The byte-by-
10533        // byte ASCII validity check rejects multi-byte UTF-8 sequences
10534        // by the first byte that fails the `[a-z0-9-]` predicate.
10535        let mut s = three_member_spec();
10536        s.membros[2].caixa = "café".into();
10537        let err = s.validate().unwrap_err();
10538        assert!(
10539            matches!(
10540                err,
10541                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
10542                    if caixa == "café"
10543            ),
10544            "got {err:?}"
10545        );
10546    }
10547
10548    #[test]
10549    fn rejects_membro_caixa_with_whitespace() {
10550        // Whitespace is the canonical "I pasted from a sketch / doc"
10551        // footgun. The apiserver rejects every `metadata.name` value
10552        // carrying whitespace; pin the gate fires at the right boundary.
10553        let mut s = three_member_spec();
10554        s.membros[0].caixa = "my cart".into();
10555        let err = s.validate().unwrap_err();
10556        assert!(
10557            matches!(
10558                err,
10559                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
10560                    if caixa == "my cart"
10561            ),
10562            "got {err:?}"
10563        );
10564    }
10565
10566    #[test]
10567    fn rejects_membro_caixa_too_long() {
10568        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
10569        // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
10570        // exactly. The gate's reason names both the cap and the actual
10571        // length so the author can shorten in one edit.
10572        let mut s = three_member_spec();
10573        let too_long = "a".repeat(64);
10574        s.membros[1].caixa = too_long.clone();
10575        let err = s.validate().unwrap_err();
10576        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
10577            panic!("expected MembroCaixaInvalid");
10578        };
10579        assert_eq!(caixa, too_long);
10580        assert!(
10581            reason.contains("63") && reason.contains("64"),
10582            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
10583        );
10584    }
10585
10586    #[test]
10587    fn membro_caixa_max_length_validates() {
10588        // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
10589        // so a future tightening (e.g. dropping to 62) surfaces here as
10590        // a regression, mirroring `entrada_host_max_length_validates`
10591        // (c7d05ec).
10592        let mut s = three_member_spec();
10593        s.membros[2].caixa = "a".repeat(63);
10594        s.entrada.as_mut().unwrap().para = "a".repeat(63);
10595        // remove contratos referencing the renamed member; they'd
10596        // raise ContratoMemberMissing otherwise
10597        s.contratos
10598            .retain(|c| c.de != "payment" && c.para != "payment");
10599        s.validate().unwrap();
10600    }
10601
10602    #[test]
10603    fn accepts_canonical_membro_caixa_forms() {
10604        // The DNS-1123 label shapes a caixa author is realistically
10605        // going to write: single-word lowercase, hyphen-joined, ending
10606        // in a digit-suffixed version (`cart-v2`), starting with a
10607        // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
10608        // DNS-1035 which requires a letter at position 0), single-
10609        // character (`a` — boundary). Pin every leg so a future
10610        // tightening that bans (e.g.) digit-start identifiers surfaces
10611        // here.
10612        for form in [
10613            "checkout",
10614            "cart",
10615            "cart-v2",
10616            "a",
10617            "c0",
10618            "3rd-party-shim",
10619            "x-1-2-3-4",
10620        ] {
10621            let mut s = three_member_spec();
10622            // Renaming a member also requires updating downstream refs;
10623            // drop everything else and rebuild a minimal spec around
10624            // just the one renamed member.
10625            s.membros = vec![membro(form, "^0.1")];
10626            s.contratos = vec![];
10627            s.entrada = None;
10628            s.validate()
10629                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
10630        }
10631    }
10632
10633    #[test]
10634    fn membro_caixa_empty_takes_precedence_over_invalid() {
10635        // Order pin: the existing `MembroCaixaEmpty` diagnostic
10636        // (which doesn't try to parse) fires before the new
10637        // `MembroCaixaInvalid` parse-side diagnostic, so an empty
10638        // `:caixa` keeps its narrower error message — the new gate
10639        // would also reject `""`, but the empty-string arm is the more
10640        // self-locating diagnostic for the author. Mirrors the
10641        // `entrada_host_empty_takes_precedence_over_invalid` pin
10642        // (c7d05ec).
10643        let mut s = three_member_spec();
10644        s.membros[1].caixa = String::new();
10645        let err = s.validate().unwrap_err();
10646        assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
10647    }
10648
10649    #[test]
10650    fn membro_caixa_invalid_fires_before_versao_check() {
10651        // Order pin: an invalid-shape `:caixa` surfaces *its own*
10652        // diagnostic (which names the offending caixa name), even when
10653        // the same entry's `:versao` is also empty/invalid. The shape
10654        // gate runs first because the diagnostic is more self-locating —
10655        // an empty/invalid `:versao` on an invalid-shape caixa name is
10656        // a downstream-fix-after-the-caixa-rename concern.
10657        let mut s = three_member_spec();
10658        s.membros[1].caixa = "Cart".into();
10659        s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
10660        let err = s.validate().unwrap_err();
10661        assert!(
10662            matches!(
10663                err,
10664                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
10665            ),
10666            "got {err:?}"
10667        );
10668    }
10669
10670    #[test]
10671    fn membro_caixa_invalid_fires_before_duplicate_check() {
10672        // Order pin: a malformed-shape `:caixa` on an earlier entry
10673        // surfaces *its own* diagnostic, even when a later entry would
10674        // otherwise collapse onto a duplicate name. The per-entry shape
10675        // gate runs inline before the duplicate-key insert, parallel
10676        // to `membro_versao_invalid_fires_before_duplicate_check`.
10677        let mut s = three_member_spec();
10678        s.membros[0].caixa = "Catalog".into();
10679        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
10680        let err = s.validate().unwrap_err();
10681        assert!(
10682            matches!(
10683                err,
10684                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
10685            ),
10686            "got {err:?}"
10687        );
10688    }
10689
10690    #[test]
10691    fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
10692        // The diagnostic-shape pin: the error names the offending
10693        // `:caixa` value verbatim so the author can grep their
10694        // caixa.lisp without re-running the build, and carries a
10695        // non-empty `reason` naming the specific violation. Same
10696        // shape every typed-shape gate enshrines (c7d05ec's
10697        // `entrada_host_diagnostic_carries_offending_host`,
10698        // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
10699        let mut s = three_member_spec();
10700        s.membros[2].caixa = "BAD_NAME".into();
10701        let err = s.validate().unwrap_err();
10702        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
10703            panic!("expected MembroCaixaInvalid");
10704        };
10705        assert_eq!(caixa, "BAD_NAME");
10706        assert!(
10707            !reason.is_empty(),
10708            "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
10709        );
10710    }
10711
10712    #[test]
10713    fn rejects_contrato_with_unknown_de() {
10714        let mut s = three_member_spec();
10715        s.contratos.push(contract_http("phantom", "catalog", "/x"));
10716        let err = s.validate().unwrap_err();
10717        assert!(
10718            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
10719        );
10720    }
10721
10722    #[test]
10723    fn rejects_contrato_with_unknown_para() {
10724        let mut s = three_member_spec();
10725        s.contratos.push(contract_http("cart", "phantom", "/x"));
10726        let err = s.validate().unwrap_err();
10727        assert!(
10728            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
10729        );
10730    }
10731
10732    #[test]
10733    fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
10734        // The read-path pin: the phantom-`:de` refusal arm's
10735        // `ContratoMemberMissing.caixa` carrier must be observed through
10736        // the lifted [`WitContract::source`] accessor, not the raw
10737        // `.de.clone()` field-access `String`-carry. Peer of the sibling
10738        // per-`:contratos` self-loop arm's `.source().to_string()` /
10739        // `.world_ref().to_string()` `String`-carry sites the earlier
10740        // convergence lifted onto the same accessor pair. A future
10741        // silent detour that reintroduced the raw `.de.clone()` at the
10742        // wrap envelope while the shape-gate and membership lookup
10743        // routed through the accessor would surface here as a byte-equal
10744        // miss between the fired diagnostic's `caixa:` field and the
10745        // offending edge's `.source()` — pinning the accessor as the
10746        // sole read path across the phantom-name refusal arm's arg +
10747        // wrap-envelope emit surface.
10748        let mut s = three_member_spec();
10749        let phantom = contract_http("phantom", "catalog", "/x");
10750        s.contratos.push(phantom.clone());
10751        let err = s.validate().unwrap_err();
10752        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
10753            panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
10754        };
10755        assert_eq!(
10756            caixa,
10757            phantom.source(),
10758            "ContratoMemberMissing.caixa on the phantom-:de arm must \
10759             byte-equal WitContract::source — the wrap envelope must \
10760             route through the lifted accessor rather than the raw \
10761             .de.clone() field-access String-carry"
10762        );
10763    }
10764
10765    #[test]
10766    fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
10767        // The symmetric read-path pin on the `:para` phantom-name
10768        // refusal arm — same shape as the sibling `:de` pin above but
10769        // on the callee-Servico axis. Pins the wrap envelope's
10770        // `caixa:` field is observed through the lifted
10771        // [`WitContract::destination`] accessor, not the raw
10772        // `.para.clone()` field-access `String`-carry.
10773        let mut s = three_member_spec();
10774        let phantom = contract_http("cart", "phantom", "/x");
10775        s.contratos.push(phantom.clone());
10776        let err = s.validate().unwrap_err();
10777        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
10778            panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
10779        };
10780        assert_eq!(
10781            caixa,
10782            phantom.destination(),
10783            "ContratoMemberMissing.caixa on the phantom-:para arm must \
10784             byte-equal WitContract::destination — the wrap envelope \
10785             must route through the lifted accessor rather than the raw \
10786             .para.clone() field-access String-carry"
10787        );
10788    }
10789
10790    #[test]
10791    fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
10792        // The read-path pin on the `:de` DNS-1123-malformed shape-gate
10793        // refusal arm — the `validate_contrato_caixa` arg must be
10794        // observed through the lifted [`WitContract::source`] accessor,
10795        // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
10796        // value routes through the shared
10797        // [`crate::render::require_valid_dns_1123_label`] floor with the
10798        // accessor-projected value; the fired
10799        // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
10800        // the offending edge's `.source()`, pinning that the arg + the
10801        // downstream `caixa: caixa.to_string()` wrap route through the
10802        // same accessor's read path.
10803        let mut s = three_member_spec();
10804        let malformed = contract_http("BAD_NAME", "catalog", "/x");
10805        s.contratos.push(malformed.clone());
10806        let err = s.validate().unwrap_err();
10807        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
10808            panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
10809        };
10810        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
10811        assert_eq!(
10812            caixa,
10813            malformed.source(),
10814            "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
10815             byte-equal WitContract::source — the shape-gate arg + wrap \
10816             envelope must route through the lifted accessor rather \
10817             than the raw &c.de &String-borrow"
10818        );
10819    }
10820
10821    #[test]
10822    fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
10823        // Symmetric arm to the sibling `:de` malformed-shape pin above,
10824        // on the `:para` axis. Pins the shape-gate arg + wrap envelope
10825        // route through the lifted [`WitContract::destination`]
10826        // accessor. `:para` runs after the `:de` shape gate in the
10827        // canonical edge-direction order, so the `:de` value must be
10828        // well-shaped for the `:para` gate to fire — the `cart` :de is
10829        // canonical.
10830        let mut s = three_member_spec();
10831        let malformed = contract_http("cart", "BAD_NAME", "/x");
10832        s.contratos.push(malformed.clone());
10833        let err = s.validate().unwrap_err();
10834        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
10835            panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
10836        };
10837        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
10838        assert_eq!(
10839            caixa,
10840            malformed.destination(),
10841            "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
10842             byte-equal WitContract::destination — the shape-gate arg + \
10843             wrap envelope must route through the lifted accessor \
10844             rather than the raw &c.para &String-borrow"
10845        );
10846    }
10847
10848    // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
10849
10850    #[test]
10851    fn rejects_contrato_de_empty() {
10852        // `:de ""` previously fell through to `ContratoMemberMissing`
10853        // (with `caixa: ""`) because the validated `:membros :caixa`
10854        // set never contains the empty string. The narrower
10855        // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
10856        // the offending slot.
10857        let mut s = three_member_spec();
10858        s.contratos.push(contract_http("", "catalog", "/x"));
10859        let err = s.validate().unwrap_err();
10860        assert_eq!(
10861            err,
10862            AplicacaoError::ContratoCaixaEmpty {
10863                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
10864            },
10865            "got {err:?}"
10866        );
10867    }
10868
10869    #[test]
10870    fn rejects_contrato_para_empty() {
10871        // Symmetric arm to `:de ""` — `:para ""` previously fell
10872        // through to `ContratoMemberMissing { caixa: "" }`.
10873        let mut s = three_member_spec();
10874        s.contratos.push(contract_http("cart", "", "/x"));
10875        let err = s.validate().unwrap_err();
10876        assert_eq!(
10877            err,
10878            AplicacaoError::ContratoCaixaEmpty {
10879                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
10880            },
10881            "got {err:?}"
10882        );
10883    }
10884
10885    #[test]
10886    fn rejects_contrato_de_with_uppercase() {
10887        // The canonical "I copied the Servico's TitleCase display
10888        // name from an ADR" typo. Until this gate landed `:de "Cart"`
10889        // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
10890        // as "this caixa isn't in `:membros`" when the root cause is
10891        // "this `:de` value's shape can never legitimately match a
10892        // validated member (DNS-1123 labels are lowercase)". The
10893        // narrower diagnostic names the offending slot, the value
10894        // verbatim, and the parser-shaped reason.
10895        let mut s = three_member_spec();
10896        s.contratos.push(contract_http("Cart", "catalog", "/x"));
10897        let err = s.validate().unwrap_err();
10898        let AplicacaoError::ContratoCaixaInvalid {
10899            slot,
10900            caixa,
10901            reason,
10902        } = err
10903        else {
10904            panic!("expected ContratoCaixaInvalid, got other variant");
10905        };
10906        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
10907        assert_eq!(caixa, "Cart");
10908        assert!(
10909            reason.contains("uppercase"),
10910            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
10911        );
10912    }
10913
10914    #[test]
10915    fn rejects_contrato_para_with_underscore() {
10916        // The canonical "I'm thinking of a Python module" leak —
10917        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
10918        // Pin the `:para` axis surfaces the same diagnostic shape as
10919        // the `:de` axis on the underscore violation.
10920        let mut s = three_member_spec();
10921        s.contratos.push(contract_http("cart", "my_catalog", "/x"));
10922        let err = s.validate().unwrap_err();
10923        assert!(
10924            matches!(
10925                err,
10926                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
10927                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
10928            ),
10929            "got {err:?}"
10930        );
10931    }
10932
10933    #[test]
10934    fn rejects_contrato_de_with_dot() {
10935        // A `:contratos :de` value is a single DNS-1123 *label*, not
10936        // a subdomain — mirroring the `:membros :caixa` floor. The
10937        // strictest floor among the use sites wins.
10938        let mut s = three_member_spec();
10939        s.contratos
10940            .push(contract_http("team.cart", "catalog", "/x"));
10941        let err = s.validate().unwrap_err();
10942        assert!(
10943            matches!(
10944                err,
10945                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
10946                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
10947            ),
10948            "got {err:?}"
10949        );
10950    }
10951
10952    #[test]
10953    fn rejects_contrato_para_with_unicode() {
10954        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
10955        // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
10956        // validity check rejects multi-byte UTF-8 by the first
10957        // non-`[a-z0-9-]` byte.
10958        let mut s = three_member_spec();
10959        s.contratos.push(contract_http("cart", "café", "/x"));
10960        let err = s.validate().unwrap_err();
10961        assert!(
10962            matches!(
10963                err,
10964                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
10965                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
10966            ),
10967            "got {err:?}"
10968        );
10969    }
10970
10971    #[test]
10972    fn rejects_contrato_de_with_leading_hyphen() {
10973        // DNS-1123 boundary rule: labels must start and end with an
10974        // alphanumeric. K8s rejects `-cart` outright; the narrower
10975        // shape diagnostic now names the violation at caixa-build
10976        // time rather than the misframed membership-lookup arm.
10977        let mut s = three_member_spec();
10978        s.contratos.push(contract_http("-cart", "catalog", "/x"));
10979        let err = s.validate().unwrap_err();
10980        assert!(
10981            matches!(
10982                err,
10983                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
10984                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
10985            ),
10986            "got {err:?}"
10987        );
10988    }
10989
10990    #[test]
10991    fn contrato_de_empty_takes_precedence_over_invalid() {
10992        // Order pin: the `ContratoCaixaEmpty` arm fires before the
10993        // `ContratoCaixaInvalid` parse-side arm — same empty-first
10994        // cascade `validate_membro_caixa` / `validate_placement_cluster`
10995        // / `validate_entrada_host` already establish on their peer
10996        // name axes. The empty string is a structurally distinct
10997        // authoring footgun (the author left the field blank, vs.
10998        // typed a malformed value), so it gets its own diagnostic.
10999        let mut s = three_member_spec();
11000        s.contratos.push(contract_http("", "catalog", "/x"));
11001        let err = s.validate().unwrap_err();
11002        assert_eq!(
11003            err,
11004            AplicacaoError::ContratoCaixaEmpty {
11005                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
11006            }
11007        );
11008    }
11009
11010    #[test]
11011    fn contrato_de_shape_fires_before_para_shape() {
11012        // Per-axis order pin: within one `:contratos` entry, the `:de`
11013        // shape gate fires before the `:para` shape gate — same
11014        // edge-direction order the existing `ContratoMemberMissing` /
11015        // `ContratoSelfLoop` / target-dispatch checks use, so the
11016        // diagnostic for a contract with both `:de` and `:para`
11017        // malformed is stable. Authors fixing the surfaced `:de`
11018        // first will see `:para`'s diagnostic on re-run.
11019        let mut s = three_member_spec();
11020        s.contratos.push(contract_http("Cart", "Catalog", "/x"));
11021        let err = s.validate().unwrap_err();
11022        assert!(
11023            matches!(
11024                err,
11025                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
11026                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
11027            ),
11028            "got {err:?}"
11029        );
11030    }
11031
11032    #[test]
11033    fn contrato_shape_fires_before_membership_lookup() {
11034        // The load-bearing pin: an invalid-shape `:de` surfaces its
11035        // *own* diagnostic, not the misframed `ContratoMemberMissing`.
11036        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
11037        // an invalid-shape `:de` could never legitimately match any
11038        // member — the prior `ContratoMemberMissing` diagnostic was
11039        // a structural impossibility framed as a graph-membership
11040        // failure. The shape gate now routes every such input through
11041        // the narrower self-locating diagnostic.
11042        let mut s = three_member_spec();
11043        s.contratos.push(contract_http("Cart", "catalog", "/x"));
11044        let err = s.validate().unwrap_err();
11045        assert!(
11046            matches!(
11047                err,
11048                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
11049            ),
11050            "got {err:?}"
11051        );
11052        // And the symmetric case: an invalid-shape `:para` surfaces
11053        // its own diagnostic too, even when `:de` is well-shaped.
11054        let mut s = three_member_spec();
11055        s.contratos.push(contract_http("cart", "Catalog", "/x"));
11056        let err = s.validate().unwrap_err();
11057        assert!(
11058            matches!(
11059                err,
11060                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
11061            ),
11062            "got {err:?}"
11063        );
11064    }
11065
11066    #[test]
11067    fn contrato_shape_fires_before_self_edge_check() {
11068        // A `:de "Cart" :para "Cart"` entry is two distinct authoring
11069        // bugs: the shape violation (uppercase) and the self-edge
11070        // violation. The narrower per-axis shape diagnostic surfaces
11071        // first because fixing the shape may reveal that the author
11072        // also meant to point `:para` at a different member — the
11073        // self-edge framing is only useful once both endpoints have
11074        // valid shape.
11075        let mut s = three_member_spec();
11076        s.contratos.push(contract_http("Cart", "Cart", "/x"));
11077        let err = s.validate().unwrap_err();
11078        assert!(
11079            matches!(
11080                err,
11081                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
11082                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
11083            ),
11084            "got {err:?}"
11085        );
11086    }
11087
11088    #[test]
11089    fn contrato_well_shaped_phantom_still_raises_member_missing() {
11090        // Strict-improvement pin: a well-shaped `:de` that simply
11091        // isn't in `:membros` (a phantom reference — author meant
11092        // to add the member but didn't, or renamed and missed an
11093        // update) still surfaces `ContratoMemberMissing`, unchanged.
11094        // The shape gate only intercepts inputs that could never
11095        // legitimately match a validated member; legitimately-shaped
11096        // phantom references remain on the graph-membership axis.
11097        let mut s = three_member_spec();
11098        s.contratos
11099            .push(contract_http("phantom-shim", "catalog", "/x"));
11100        let err = s.validate().unwrap_err();
11101        assert!(
11102            matches!(
11103                err,
11104                AplicacaoError::ContratoMemberMissing { ref caixa }
11105                    if caixa == "phantom-shim"
11106            ),
11107            "got {err:?}"
11108        );
11109    }
11110
11111    #[test]
11112    fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
11113        // The diagnostic-shape pin: the error names the offending
11114        // slot (`:de` or `:para`) verbatim and the offending value
11115        // verbatim plus a non-empty parser-shaped reason, so the
11116        // author can grep their caixa.lisp for `:de "<name>"` /
11117        // `:para "<name>"` and fix it in one edit. Same diagnostic
11118        // shape as `MembroCaixaInvalid` (3f9d7a0) and
11119        // `PlacementClusterInvalid` (6c8c00b).
11120        let mut s = three_member_spec();
11121        s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
11122        let err = s.validate().unwrap_err();
11123        let AplicacaoError::ContratoCaixaInvalid {
11124            slot,
11125            caixa,
11126            reason,
11127        } = err
11128        else {
11129            panic!("expected ContratoCaixaInvalid, got {err:?}");
11130        };
11131        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
11132        assert_eq!(caixa, "BAD_NAME");
11133        assert!(
11134            !reason.is_empty(),
11135            "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
11136        );
11137    }
11138
11139    #[test]
11140    fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
11141        // Scalar-value pin: the two author-facing kebab-case labels the
11142        // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
11143        // admits on the `:contratos` per-entry endpoint-shape axis,
11144        // one arm per typed sub-slot. Mirrors the peer scalar-value
11145        // pin the sibling top-level M2 / M3 / Supervisor
11146        // author-facing-label consts carry
11147        // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
11148        // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
11149        // slot itself), so every altitude of the typed-slot algebra
11150        // shares the same "one canonical byte-string per arm"
11151        // discipline. A future rebrand (`:de` → `:from` matching the
11152        // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
11153        // sibling, `:para` → `:to` matching the same, or
11154        // `:de`/`:para` → `:source`/`:target` matching the WIT
11155        // world's `import`/`export` half-vocabulary) lands as an
11156        // edit to exactly one const, and every consumer that reaches
11157        // for the label picks it up at build time rather than at
11158        // runtime as a downstream `ContratoCaixaEmpty` /
11159        // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
11160        // diagnostic mismatch far from the rename's commit.
11161        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
11162        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
11163    }
11164
11165    #[test]
11166    fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
11167        // Production-through-const pin: the two per-axis labels the
11168        // per-`:contratos` entry endpoint-shape gate at
11169        // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
11170        // argument to [`validate_contrato_caixa`] route through the
11171        // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
11172        // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
11173        // future rebrand that reaches the const but not the gate (or
11174        // vice versa) surfaces here at build time rather than at
11175        // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
11176        // `slot: <stale-kebab-case>` diagnostic far from the rename's
11177        // commit. Mirror of the peer
11178        // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
11179        // pin (882f498) on the sibling M3 top-level slot axis.
11180        let mut s = three_member_spec();
11181        s.contratos.push(contract_http("", "catalog", "/x"));
11182        assert_eq!(
11183            s.validate().unwrap_err(),
11184            AplicacaoError::ContratoCaixaEmpty {
11185                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
11186            }
11187        );
11188        let mut s = three_member_spec();
11189        s.contratos.push(contract_http("cart", "", "/x"));
11190        assert_eq!(
11191            s.validate().unwrap_err(),
11192            AplicacaoError::ContratoCaixaEmpty {
11193                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
11194            }
11195        );
11196    }
11197
11198    #[test]
11199    fn accepts_canonical_contrato_caixa_forms() {
11200        // The DNS-1123 label shapes a caixa author is realistically
11201        // going to write on a `:contratos :de` / `:para`. Pin every
11202        // leg so a future tightening that bans (e.g.) digit-start
11203        // identifiers surfaces here, mirroring
11204        // `accepts_canonical_membro_caixa_forms` on the peer name
11205        // axis.
11206        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
11207            let mut s = three_member_spec();
11208            s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
11209            s.contratos = vec![contract_http("checkout", form, "/x")];
11210            s.entrada = None;
11211            s.validate().unwrap_or_else(|e| {
11212                panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
11213            });
11214
11215            let mut s = three_member_spec();
11216            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
11217            s.contratos = vec![contract_http(form, "catalog", "/x")];
11218            s.entrada = None;
11219            s.validate().unwrap_or_else(|e| {
11220                panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
11221            });
11222        }
11223    }
11224
11225    #[test]
11226    fn rejects_empty_wit() {
11227        let mut s = three_member_spec();
11228        s.contratos.push(WitContract {
11229            de: "cart".into(),
11230            para: "catalog".into(),
11231            wit: String::new(),
11232            endpoint: None,
11233            subject: None,
11234            slot: None,
11235        });
11236        let err = s.validate().unwrap_err();
11237        assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
11238    }
11239
11240    #[test]
11241    fn rejects_entrada_to_unknown_member() {
11242        let mut s = three_member_spec();
11243        s.entrada.as_mut().unwrap().para = "phantom".into();
11244        assert!(matches!(
11245            s.validate().unwrap_err(),
11246            AplicacaoError::EntradaMemberMissing { .. }
11247        ));
11248    }
11249
11250    // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
11251
11252    #[test]
11253    fn rejects_entrada_para_empty() {
11254        // `:para ""` previously fell through to
11255        // `EntradaMemberMissing { para: "" }` because the validated
11256        // `:membros :caixa` set never contains the empty string. The
11257        // narrower `EntradaParaEmpty` diagnostic now names the
11258        // offending slot directly — same empty-first cascade
11259        // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
11260        // `ContratoCaixaEmpty` establish on the peer name axes.
11261        let mut s = three_member_spec();
11262        s.entrada.as_mut().unwrap().para = String::new();
11263        let err = s.validate().unwrap_err();
11264        assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
11265    }
11266
11267    #[test]
11268    fn rejects_entrada_para_with_uppercase() {
11269        // The canonical "I copied the Servico's TitleCase display
11270        // name from an ADR" typo. Until this gate landed `:para "Cart"`
11271        // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
11272        // as "this caixa isn't in `:membros`" when the root cause is
11273        // "this `:para` value's shape can never legitimately match a
11274        // validated member (DNS-1123 labels are lowercase)". The
11275        // narrower diagnostic names the value verbatim plus the
11276        // parser-shaped reason.
11277        let mut s = three_member_spec();
11278        s.entrada.as_mut().unwrap().para = "Cart".into();
11279        let err = s.validate().unwrap_err();
11280        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
11281            panic!("expected EntradaParaInvalid, got other variant");
11282        };
11283        assert_eq!(para, "Cart");
11284        assert!(
11285            reason.contains("uppercase"),
11286            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
11287        );
11288    }
11289
11290    #[test]
11291    fn rejects_entrada_para_with_underscore() {
11292        // The canonical "I'm thinking of a Python module" leak —
11293        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
11294        let mut s = three_member_spec();
11295        s.entrada.as_mut().unwrap().para = "my_cart".into();
11296        let err = s.validate().unwrap_err();
11297        assert!(
11298            matches!(
11299                err,
11300                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
11301                    if para == "my_cart" && reason.contains('_')
11302            ),
11303            "got {err:?}"
11304        );
11305    }
11306
11307    #[test]
11308    fn rejects_entrada_para_with_dot() {
11309        // An `:entrada :para` value is a single DNS-1123 *label*, not
11310        // a subdomain — mirroring the `:membros :caixa` floor. The
11311        // strictest floor among the use sites wins.
11312        let mut s = three_member_spec();
11313        s.entrada.as_mut().unwrap().para = "team.cart".into();
11314        let err = s.validate().unwrap_err();
11315        assert!(
11316            matches!(
11317                err,
11318                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
11319                    if para == "team.cart" && reason.contains('.')
11320            ),
11321            "got {err:?}"
11322        );
11323    }
11324
11325    #[test]
11326    fn rejects_entrada_para_with_unicode() {
11327        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
11328        // (`xn--…`) before it reaches K8s.
11329        let mut s = three_member_spec();
11330        s.entrada.as_mut().unwrap().para = "café".into();
11331        let err = s.validate().unwrap_err();
11332        assert!(
11333            matches!(
11334                err,
11335                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
11336            ),
11337            "got {err:?}"
11338        );
11339    }
11340
11341    #[test]
11342    fn rejects_entrada_para_with_leading_hyphen() {
11343        // DNS-1123 boundary rule: labels must start and end with an
11344        // alphanumeric. K8s rejects `-cart` outright.
11345        let mut s = three_member_spec();
11346        s.entrada.as_mut().unwrap().para = "-cart".into();
11347        let err = s.validate().unwrap_err();
11348        assert!(
11349            matches!(
11350                err,
11351                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
11352                    if para == "-cart" && reason.contains("start and end")
11353            ),
11354            "got {err:?}"
11355        );
11356    }
11357
11358    #[test]
11359    fn rejects_entrada_para_with_trailing_hyphen() {
11360        // Symmetric boundary arm.
11361        let mut s = three_member_spec();
11362        s.entrada.as_mut().unwrap().para = "cart-".into();
11363        let err = s.validate().unwrap_err();
11364        assert!(
11365            matches!(
11366                err,
11367                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
11368                    if para == "cart-" && reason.contains("start and end")
11369            ),
11370            "got {err:?}"
11371        );
11372    }
11373
11374    #[test]
11375    fn rejects_entrada_para_too_long() {
11376        // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
11377        // bytes per label. K8s rejects longer names at admission on
11378        // every `metadata.name` axis.
11379        let mut s = three_member_spec();
11380        s.entrada.as_mut().unwrap().para = "a".repeat(64);
11381        let err = s.validate().unwrap_err();
11382        assert!(
11383            matches!(
11384                err,
11385                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
11386                    if para.len() == 64 && reason.contains("max length")
11387            ),
11388            "got {err:?}"
11389        );
11390    }
11391
11392    #[test]
11393    fn entrada_para_empty_takes_precedence_over_invalid() {
11394        // Order pin: the `EntradaParaEmpty` arm fires before the
11395        // `EntradaParaInvalid` parse-side arm — same empty-first
11396        // cascade `validate_membro_caixa` / `validate_placement_cluster`
11397        // / `validate_contrato_caixa` already establish.
11398        let mut s = three_member_spec();
11399        s.entrada.as_mut().unwrap().para = String::new();
11400        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
11401    }
11402
11403    #[test]
11404    fn entrada_para_shape_fires_before_membership_lookup() {
11405        // The load-bearing pin: an invalid-shape `:para` surfaces its
11406        // *own* diagnostic, not the misframed `EntradaMemberMissing`.
11407        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
11408        // an invalid-shape `:para` could never legitimately match any
11409        // member — the prior `EntradaMemberMissing` diagnostic framed
11410        // a structural impossibility as a graph-membership failure.
11411        let mut s = three_member_spec();
11412        s.entrada.as_mut().unwrap().para = "Cart".into();
11413        let err = s.validate().unwrap_err();
11414        assert!(
11415            matches!(
11416                err,
11417                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
11418            ),
11419            "got {err:?}"
11420        );
11421    }
11422
11423    #[test]
11424    fn entrada_para_shape_fires_before_host_gate() {
11425        // Per-`:entrada` order pin: the `:para` shape gate fires
11426        // before the `:host` gate, mirroring the existing
11427        // `entrada_host_member_missing_takes_precedence_over_host_invalid`
11428        // ordering where the member-lookup arm preceded the host gate.
11429        // The shape gate slots ahead of that, so a malformed `:para`
11430        // surfaces its own diagnostic even when `:host` is also wrong.
11431        let mut s = three_member_spec();
11432        let e = s.entrada.as_mut().unwrap();
11433        e.para = "Cart".into();
11434        e.host = "BAD HOST".into();
11435        let err = s.validate().unwrap_err();
11436        assert!(
11437            matches!(
11438                err,
11439                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
11440            ),
11441            "got {err:?}"
11442        );
11443    }
11444
11445    #[test]
11446    fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
11447        // Strict-improvement pin: a well-shaped `:para` that simply
11448        // isn't in `:membros` (a phantom reference — author meant to
11449        // add the member but didn't, or renamed and missed an
11450        // update) still surfaces `EntradaMemberMissing`, unchanged.
11451        // The shape gate only intercepts inputs that could never
11452        // legitimately match a validated member.
11453        let mut s = three_member_spec();
11454        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
11455        let err = s.validate().unwrap_err();
11456        assert!(
11457            matches!(
11458                err,
11459                AplicacaoError::EntradaMemberMissing { ref para }
11460                    if para == "phantom-shim"
11461            ),
11462            "got {err:?}"
11463        );
11464    }
11465
11466    #[test]
11467    fn entrada_para_invalid_diagnostic_carries_offending_para() {
11468        // The diagnostic-shape pin: the error names the offending
11469        // `:para` value verbatim plus a non-empty parser-shaped
11470        // reason, so the author can grep their caixa.lisp for
11471        // `:para "<name>"` and fix it in one edit. Same diagnostic
11472        // shape as `MembroCaixaInvalid` (3f9d7a0),
11473        // `PlacementClusterInvalid` (6c8c00b), and
11474        // `ContratoCaixaInvalid` (8d5af6b).
11475        let mut s = three_member_spec();
11476        s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
11477        let err = s.validate().unwrap_err();
11478        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
11479            panic!("expected EntradaParaInvalid, got {err:?}");
11480        };
11481        assert_eq!(para, "BAD_NAME");
11482        assert!(
11483            !reason.is_empty(),
11484            "EntradaParaInvalid `reason` must carry a parser-shaped wording"
11485        );
11486    }
11487
11488    #[test]
11489    fn accepts_canonical_entrada_para_forms() {
11490        // Positive-control sweep covering the DNS-1123 label shapes a
11491        // caixa author is realistically going to write on `:entrada
11492        // :para`. Pin every leg so a future tightening that bans
11493        // (e.g.) digit-start identifiers surfaces here, mirroring
11494        // `accepts_canonical_membro_caixa_forms` and
11495        // `accepts_canonical_contrato_caixa_forms` on the peer name
11496        // axes.
11497        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
11498            let mut s = three_member_spec();
11499            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
11500            s.contratos = vec![contract_http(form, "catalog", "/x")];
11501            s.entrada = Some(Entrada {
11502                host: "checkout.quero.cloud".into(),
11503                para: form.into(),
11504                paths: vec!["/api".into()],
11505                port: 8080,
11506            });
11507            s.validate().unwrap_or_else(|e| {
11508                panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
11509            });
11510        }
11511    }
11512
11513    #[test]
11514    fn rejects_replicated_without_clusters() {
11515        let mut s = three_member_spec();
11516        s.placement.clusters = vec![];
11517        assert!(matches!(
11518            s.validate().unwrap_err(),
11519            AplicacaoError::PlacementWithoutClusters { .. }
11520        ));
11521    }
11522
11523    #[test]
11524    fn rejects_sharded_without_key() {
11525        let mut s = three_member_spec();
11526        s.placement.estrategia = PlacementStrategy::Sharded;
11527        s.placement.shard_key = None;
11528        s.placement.clusters = vec!["rio".into()];
11529        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
11530    }
11531
11532    #[test]
11533    fn sharded_with_key_validates() {
11534        let mut s = three_member_spec();
11535        s.placement.estrategia = PlacementStrategy::Sharded;
11536        s.placement.shard_key = Some("$tenantId".into());
11537        s.validate().unwrap();
11538    }
11539
11540    #[test]
11541    fn round_trip_via_json_preserves_shape() {
11542        let s = three_member_spec();
11543        let json = serde_json::to_string(&s.membros).unwrap();
11544        let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
11545        assert_eq!(back, s.membros);
11546
11547        let json = serde_json::to_string(&s.contratos).unwrap();
11548        let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
11549        assert_eq!(back, s.contratos);
11550
11551        let json = serde_json::to_string(&s.placement).unwrap();
11552        let back: Placement = serde_json::from_str(&json).unwrap();
11553        assert_eq!(back, s.placement);
11554
11555        let json = serde_json::to_string(&s.entrada).unwrap();
11556        let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
11557        assert_eq!(back, s.entrada);
11558    }
11559
11560    #[test]
11561    fn rate_limit_round_trip_seconds() {
11562        let policy = MeshPolicy {
11563            rate_limit: Some(RateLimit {
11564                rate: 100,
11565                window: Duration::from_secs(1),
11566            }),
11567            ..Default::default()
11568        };
11569        let json = serde_json::to_string(&policy).unwrap();
11570        assert!(json.contains("\"100/s\""));
11571        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
11572        assert_eq!(back.rate_limit.unwrap().rate, 100);
11573        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
11574    }
11575
11576    #[test]
11577    fn rate_limit_round_trip_minutes() {
11578        let policy = MeshPolicy {
11579            rate_limit: Some(RateLimit {
11580                rate: 5000,
11581                window: Duration::from_secs(60),
11582            }),
11583            ..Default::default()
11584        };
11585        let json = serde_json::to_string(&policy).unwrap();
11586        assert!(json.contains("\"5000/m\""));
11587    }
11588
11589    #[test]
11590    fn circuit_breaker_round_trip() {
11591        let policy = MeshPolicy {
11592            circuit_breaker: Some(CircuitBreaker {
11593                max_failures: 5,
11594                window: Duration::from_secs(60),
11595            }),
11596            ..Default::default()
11597        };
11598        let json = serde_json::to_string(&policy).unwrap();
11599        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
11600        assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
11601        assert_eq!(
11602            back.circuit_breaker.unwrap().window,
11603            Duration::from_secs(60)
11604        );
11605    }
11606
11607    #[test]
11608    fn rejects_http_contrato_without_endpoint() {
11609        let mut s = three_member_spec();
11610        s.contratos.push(WitContract {
11611            de: "cart".into(),
11612            para: "catalog".into(),
11613            wit: "wasi:http/proxy".into(),
11614            endpoint: None,
11615            subject: None,
11616            slot: None,
11617        });
11618        let err = s.validate().unwrap_err();
11619        assert!(matches!(
11620            err,
11621            AplicacaoError::ContratoMissingTarget {
11622                expected: WitTarget::HTTP_FIELD_NAME,
11623                ..
11624            }
11625        ));
11626    }
11627
11628    #[test]
11629    fn rejects_http_contrato_with_subject() {
11630        let mut s = three_member_spec();
11631        s.contratos.push(WitContract {
11632            de: "cart".into(),
11633            para: "catalog".into(),
11634            wit: "wasi:http/proxy".into(),
11635            endpoint: Some("/x".into()),
11636            subject: Some("not.allowed.here".into()),
11637            slot: None,
11638        });
11639        let err = s.validate().unwrap_err();
11640        assert!(matches!(
11641            err,
11642            AplicacaoError::ContratoWrongTarget {
11643                expected: WitTarget::HTTP_FIELD_NAME,
11644                ..
11645            }
11646        ));
11647    }
11648
11649    #[test]
11650    fn rejects_pubsub_contrato_without_subject() {
11651        let mut s = three_member_spec();
11652        s.contratos.push(WitContract {
11653            de: "cart".into(),
11654            para: "catalog".into(),
11655            wit: "nats:pub-sub".into(),
11656            endpoint: None,
11657            subject: None,
11658            slot: None,
11659        });
11660        let err = s.validate().unwrap_err();
11661        assert!(matches!(
11662            err,
11663            AplicacaoError::ContratoMissingTarget {
11664                expected: WitTarget::PUBSUB_FIELD_NAME,
11665                ..
11666            }
11667        ));
11668    }
11669
11670    #[test]
11671    fn rejects_pubsub_contrato_with_endpoint() {
11672        let mut s = three_member_spec();
11673        s.contratos.push(WitContract {
11674            de: "cart".into(),
11675            para: "catalog".into(),
11676            wit: "kafka:topic".into(),
11677            endpoint: Some("/wrong".into()),
11678            subject: Some("topic.x".into()),
11679            slot: None,
11680        });
11681        let err = s.validate().unwrap_err();
11682        assert!(matches!(
11683            err,
11684            AplicacaoError::ContratoWrongTarget {
11685                expected: WitTarget::PUBSUB_FIELD_NAME,
11686                ..
11687            }
11688        ));
11689    }
11690
11691    #[test]
11692    fn rejects_store_contrato_without_slot() {
11693        let mut s = three_member_spec();
11694        s.contratos.push(WitContract {
11695            de: "cart".into(),
11696            para: "catalog".into(),
11697            wit: "wasi:keyvalue/store".into(),
11698            endpoint: None,
11699            subject: None,
11700            slot: None,
11701        });
11702        let err = s.validate().unwrap_err();
11703        assert!(matches!(
11704            err,
11705            AplicacaoError::ContratoMissingTarget {
11706                expected: WitTarget::STORE_FIELD_NAME,
11707                ..
11708            }
11709        ));
11710    }
11711
11712    // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
11713
11714    #[test]
11715    fn rejects_http_contrato_with_empty_endpoint() {
11716        // `Some("")` for an HTTP endpoint passes the presence check
11717        // (target() previously returned WitTarget::Http { endpoint: "" })
11718        // but renders as a `path: ""` Cilium L7 rule that matches no
11719        // traffic. Same value-shape footgun closed for :entrada :paths
11720        // entries (eb3456d).
11721        let mut s = three_member_spec();
11722        s.contratos.push(WitContract {
11723            de: "cart".into(),
11724            para: "catalog".into(),
11725            wit: "wasi:http/proxy".into(),
11726            endpoint: Some(String::new()),
11727            subject: None,
11728            slot: None,
11729        });
11730        let err = s.validate().unwrap_err();
11731        assert!(
11732            matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
11733                if de == "cart" && para == "catalog"),
11734            "got {err:?}"
11735        );
11736    }
11737
11738    #[test]
11739    fn rejects_http_contrato_with_relative_endpoint() {
11740        // Cilium L7 :path + Gateway API PathPrefix both require a
11741        // leading `/`. Same shape required of :entrada :paths
11742        // (eb3456d). Lifted into target() so every consumer of the
11743        // typed WitTarget view inherits the guarantee.
11744        let mut s = three_member_spec();
11745        s.contratos.push(WitContract {
11746            de: "cart".into(),
11747            para: "catalog".into(),
11748            wit: "wasi:http/proxy".into(),
11749            endpoint: Some("products/:id".into()),
11750            subject: None,
11751            slot: None,
11752        });
11753        let err = s.validate().unwrap_err();
11754        assert!(
11755            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
11756                if endpoint == "products/:id"),
11757            "got {err:?}"
11758        );
11759    }
11760
11761    #[test]
11762    fn rejects_pubsub_contrato_with_empty_subject() {
11763        // NATS / Kafka publish without a subject is a no-op subscribe;
11764        // never the author's intent. Same empty-string rejection as
11765        // :membros :caixa, :placement :clusters entries, :entrada
11766        // :paths entries — every value carried by every typed slot is
11767        // value-shape-checked at validate().
11768        let mut s = three_member_spec();
11769        s.contratos.push(WitContract {
11770            de: "cart".into(),
11771            para: "catalog".into(),
11772            wit: "nats:pub-sub".into(),
11773            endpoint: None,
11774            subject: Some(String::new()),
11775            slot: None,
11776        });
11777        let err = s.validate().unwrap_err();
11778        assert!(
11779            matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
11780                if de == "cart" && para == "catalog"),
11781            "got {err:?}"
11782        );
11783    }
11784
11785    #[test]
11786    fn rejects_store_contrato_with_empty_slot() {
11787        // An empty slot template addresses the bucket root, defeating
11788        // the per-key isolation the slot exists for — a footgun on
11789        // `wasi:keyvalue/store` whose closest analog is the empty
11790        // shard-key rejected on :placement Sharded (c7c7799).
11791        let mut s = three_member_spec();
11792        s.contratos.push(WitContract {
11793            de: "cart".into(),
11794            para: "catalog".into(),
11795            wit: "wasi:keyvalue/store".into(),
11796            endpoint: None,
11797            subject: None,
11798            slot: Some(String::new()),
11799        });
11800        let err = s.validate().unwrap_err();
11801        assert!(
11802            matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
11803                if de == "cart" && para == "catalog"),
11804            "got {err:?}"
11805        );
11806    }
11807
11808    #[test]
11809    fn http_contrato_root_endpoint_validates() {
11810        // Pin the boundary case: a single-`/` endpoint is the catch-all
11811        // form the Gateway HTTPRoute renderer falls back to when
11812        // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
11813        // must remain a valid contrato endpoint too.
11814        let mut s = three_member_spec();
11815        s.contratos.push(contract_http("cart", "catalog", "/"));
11816        s.validate().unwrap();
11817    }
11818
11819    // ── :contratos :endpoint value-shape gate ────────────────────────────
11820    //
11821    // Mirrors the `:entrada :paths` value-shape suite on the peer
11822    // HTTP-path axis. Until this gate landed `WitContract::target()`
11823    // only refused the empty string + the missing-leading-`/` form
11824    // (c4213a4); a structurally invalid endpoint passed validate and
11825    // landed verbatim as a Cilium L7 `path:` rule
11826    // (caixa-mesh/src/lib.rs:311) that either silently dropped all
11827    // traffic or was rejected at apply time by Cilium policy admission.
11828    // Every authoring footgun the K8s Gateway API webhook / Cilium
11829    // policy validator would catch on admission now becomes a caixa-
11830    // build-time `ContratoEndpointInvalid` with the offending
11831    // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
11832    // shape as `EntradaPathInvalid` on the sibling axis; same shared
11833    // predicate (`crate::render::is_gateway_api_http_path`) ensures
11834    // drift between the two axes' rule enforcement is a build error
11835    // at the predicate.
11836
11837    fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
11838        // Fresh spec per call so the would-be-duplicate edge
11839        // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
11840        // `three_member_spec`'s pre-existing
11841        // `(cart, catalog, …, /products/:id)` entry — only the
11842        // endpoint payload differs.
11843        let mut s = three_member_spec();
11844        s.contratos.push(contract_http("cart", "catalog", ep));
11845        s.validate().unwrap_err()
11846    }
11847
11848    #[test]
11849    fn rejects_http_contrato_endpoint_with_query() {
11850        // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
11851        // silently rendered as a Cilium L7 `path: "/charge?token=X"`
11852        // rule the L7 matcher would never satisfy.
11853        let err = contrato_endpoint_err("/charge?token=X");
11854        assert!(
11855            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
11856                if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
11857            "got {err:?}"
11858        );
11859    }
11860
11861    #[test]
11862    fn rejects_http_contrato_endpoint_with_fragment() {
11863        let err = contrato_endpoint_err("/charge#frag");
11864        assert!(
11865            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
11866                if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
11867            "got {err:?}"
11868        );
11869    }
11870
11871    #[test]
11872    fn rejects_http_contrato_endpoint_with_whitespace() {
11873        let err = contrato_endpoint_err("/foo bar");
11874        assert!(
11875            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
11876                if endpoint == "/foo bar" && reason.contains("whitespace")),
11877            "got {err:?}"
11878        );
11879    }
11880
11881    #[test]
11882    fn rejects_http_contrato_endpoint_with_control_char() {
11883        let err = contrato_endpoint_err("/api/\x01bar");
11884        assert!(
11885            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
11886                if endpoint == "/api/\x01bar" && reason.contains("control character")),
11887            "got {err:?}"
11888        );
11889    }
11890
11891    #[test]
11892    fn rejects_http_contrato_endpoint_with_non_ascii() {
11893        let err = contrato_endpoint_err("/api/café");
11894        assert!(
11895            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
11896                if endpoint == "/api/café" && reason.contains("non-ASCII")),
11897            "got {err:?}"
11898        );
11899    }
11900
11901    #[test]
11902    fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
11903        let err = contrato_endpoint_err("/api//cart");
11904        assert!(
11905            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
11906                if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
11907            "got {err:?}"
11908        );
11909    }
11910
11911    #[test]
11912    fn rejects_http_contrato_endpoint_with_dot_segment() {
11913        let err = contrato_endpoint_err("/api/./cart");
11914        assert!(
11915            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
11916                if endpoint == "/api/./cart" && reason.contains("`.` segment")),
11917            "got {err:?}"
11918        );
11919    }
11920
11921    #[test]
11922    fn rejects_http_contrato_endpoint_with_parent_segment() {
11923        // Path-traversal in a contrato endpoint is the canonical
11924        // "L7 rule that the workload's HTTP server's path-resolution
11925        // logic interprets differently than the policy enforcer"
11926        // footgun. Rejected outright at validate time.
11927        let err = contrato_endpoint_err("/api/../etc");
11928        assert!(
11929            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
11930                if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
11931            "got {err:?}"
11932        );
11933    }
11934
11935    #[test]
11936    fn rejects_http_contrato_endpoint_too_long() {
11937        // 1025-byte endpoint — one over the Gateway API
11938        // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
11939        // path matcher has no inherent length limit but the policy
11940        // CR itself rides through the K8s apiserver, which enforces
11941        // ConfigMap-shaped limits; sharing the Gateway API cap is the
11942        // conservative floor.
11943        let big = format!("/api/{}", "a".repeat(1020));
11944        assert_eq!(big.len(), 1025);
11945        let err = contrato_endpoint_err(&big);
11946        assert!(
11947            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
11948                if endpoint == &big && reason.contains("max length of 1024")),
11949            "got {err:?}"
11950        );
11951    }
11952
11953    #[test]
11954    fn http_contrato_endpoint_max_length_validates() {
11955        // 1024-byte endpoint — exactly the cap. Boundary pin: drift
11956        // in the cap surfaces here and at
11957        // `rejects_http_contrato_endpoint_too_long` simultaneously,
11958        // mirroring `entrada_path_max_length_validates` on the peer
11959        // axis.
11960        let big = format!("/api/{}", "a".repeat(1019));
11961        assert_eq!(big.len(), 1024);
11962        let mut s = three_member_spec();
11963        s.contratos.push(contract_http("cart", "catalog", &big));
11964        s.validate().unwrap();
11965    }
11966
11967    #[test]
11968    fn http_contrato_endpoint_accepts_canonical_forms() {
11969        // Positive-set sweep: every canonical HTTP-path shape the
11970        // sibling `:entrada :paths` axis accepts (the bare-root `/`,
11971        // plain paths, hidden-file-style `.config` segments distinct
11972        // from the `.` segment, digit-bearing segments, the canonical
11973        // route-template `:param` form, trailing-slash form,
11974        // percent-encoded segments, the `/foo..bar` interior-`..`-
11975        // substring forms that are NOT `..` segments) must remain a
11976        // valid contrato endpoint too. Drift between this list and
11977        // the entrada path positive sweep surfaces at the shared
11978        // `is_gateway_api_http_path` substrate-side suite — one
11979        // source of truth. Uses a fresh `(payment, catalog)` edge so
11980        // none of the swept endpoints collide with the pre-existing
11981        // `(cart, catalog, /products/:id)` / `(cart, payment,
11982        // /charge)` entries in `three_member_spec`.
11983        for ep in [
11984            "/",
11985            "/charge",
11986            "/v1/charge",
11987            "/api/.config",
11988            "/products/:id",
11989            "/api/cart/",
11990            "/api/caf%C3%A9",
11991            "/foo..bar",
11992            "/...",
11993        ] {
11994            let mut s = three_member_spec();
11995            s.contratos.push(contract_http("payment", "catalog", ep));
11996            s.validate()
11997                .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
11998        }
11999    }
12000
12001    #[test]
12002    fn contrato_endpoint_empty_takes_precedence_over_invalid() {
12003        // Ordering pin: `ContratoEndpointEmpty` is the more self-
12004        // locating diagnostic on `""` and must lead — the value-
12005        // shape gate is only reached after the empty-check fires.
12006        // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
12007        // on the peer axis.
12008        let mut s = three_member_spec();
12009        s.contratos.push(WitContract {
12010            de: "cart".into(),
12011            para: "catalog".into(),
12012            wit: "wasi:http/proxy".into(),
12013            endpoint: Some(String::new()),
12014            subject: None,
12015            slot: None,
12016        });
12017        let err = s.validate().unwrap_err();
12018        assert!(
12019            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
12020            "got {err:?}"
12021        );
12022    }
12023
12024    #[test]
12025    fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
12026        // Ordering pin: an endpoint without a leading `/` surfaces the
12027        // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
12028        // value-shape gate is only consulted on endpoints that already
12029        // satisfy the absolute-prefix invariant. Mirrors
12030        // `entrada_path_not_absolute_takes_precedence_over_invalid`.
12031        let err = contrato_endpoint_err("bad path");
12032        assert!(
12033            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
12034                if endpoint == "bad path"),
12035            "got {err:?}"
12036        );
12037    }
12038
12039    #[test]
12040    fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
12041        // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
12042        // `:para` + a non-empty reason flow through verbatim so the
12043        // author can grep their caixa.lisp for the offending contrato
12044        // block and fix it in one edit. Same shape as
12045        // `entrada_path_diagnostic_carries_offending_path`.
12046        let err = contrato_endpoint_err("/api?q=1");
12047        match err {
12048            AplicacaoError::ContratoEndpointInvalid {
12049                de,
12050                para,
12051                endpoint,
12052                reason,
12053            } => {
12054                assert_eq!(de, "cart");
12055                assert_eq!(para, "catalog");
12056                assert_eq!(endpoint, "/api?q=1");
12057                assert!(!reason.is_empty(), "reason field must be non-empty");
12058            }
12059            other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
12060        }
12061    }
12062
12063    #[test]
12064    fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
12065        // The compounding theorem: every &str inside a WitTarget
12066        // returned by target() is non-empty (and absolute, for Http).
12067        // Renderers downstream of typed_view() can rely on this
12068        // without re-checking — the type system carries the proof.
12069        let http = contract_http("cart", "catalog", "/x");
12070        match http.target().unwrap() {
12071            WitTarget::Http { endpoint } => {
12072                assert!(!endpoint.is_empty());
12073                assert!(endpoint.starts_with('/'));
12074            }
12075            other => panic!("expected Http, got {other:?}"),
12076        }
12077        let nats = WitContract {
12078            de: "a".into(),
12079            para: "b".into(),
12080            wit: "nats:pub-sub".into(),
12081            endpoint: None,
12082            subject: Some("topic.x".into()),
12083            slot: None,
12084        };
12085        match nats.target().unwrap() {
12086            WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
12087            other => panic!("expected PubSub, got {other:?}"),
12088        }
12089        let kv = WitContract {
12090            de: "a".into(),
12091            para: "b".into(),
12092            wit: "wasi:keyvalue/store".into(),
12093            endpoint: None,
12094            subject: None,
12095            slot: Some("checkout/$orderId".into()),
12096        };
12097        match kv.target().unwrap() {
12098            WitTarget::Store { slot } => assert!(!slot.is_empty()),
12099            other => panic!("expected Store, got {other:?}"),
12100        }
12101    }
12102
12103    #[test]
12104    fn target_diagnostic_names_offending_endpoint_value() {
12105        // When the malformed endpoint string is non-trivial, the
12106        // diagnostic carries the actual value back to the author —
12107        // not a generic "endpoint malformed" error.
12108        let bad = WitContract {
12109            de: "src".into(),
12110            para: "dst".into(),
12111            wit: "wasi:http/proxy".into(),
12112            endpoint: Some("api/v1/charge".into()),
12113            subject: None,
12114            slot: None,
12115        };
12116        match bad.target().unwrap_err() {
12117            AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
12118                assert_eq!(de, "src");
12119                assert_eq!(para, "dst");
12120                assert_eq!(endpoint, "api/v1/charge");
12121            }
12122            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
12123        }
12124    }
12125
12126    #[test]
12127    fn rejects_unknown_wit_with_target_set() {
12128        let mut s = three_member_spec();
12129        s.contratos.push(WitContract {
12130            de: "cart".into(),
12131            para: "catalog".into(),
12132            wit: "custom:exchange".into(),
12133            endpoint: Some("/leaked".into()),
12134            subject: None,
12135            slot: None,
12136        });
12137        let err = s.validate().unwrap_err();
12138        assert!(matches!(
12139            err,
12140            AplicacaoError::ContratoWrongTarget {
12141                expected: WitTarget::CAPABILITY_EXPECTED,
12142                ..
12143            }
12144        ));
12145    }
12146
12147    #[test]
12148    fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
12149        // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
12150        // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
12151        // fourth arm of the same "which payload field name goes in the
12152        // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
12153        // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
12154        // consts cover on the peer HTTP / PubSub / Store arms
12155        // (`wit_target_field_name_pins_per_variant`). Until this lift
12156        // landed the byte-string sat twice — once inline in the
12157        // [`WitContract::target`] Capability-arm rejection at the
12158        // production dispatch, once in `rejects_unknown_wit_with_target_set`
12159        // pinning against the same literal — with no compile-time link
12160        // between them. Same "one canonical declaration, next to the
12161        // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
12162        // lift established for the payload-less arm's human-readable
12163        // label axis; this test is the shape peer of
12164        // `wit_target_label_pins_per_variant`'s Capability-arm assertion
12165        // pair (routes-through-const + scalar-value pin) on the
12166        // wrong-target diagnostic-scalar axis.
12167        //
12168        // Fail-before-pass-after was verified locally by mutating the
12169        // const declaration to `"capability"` — the scalar-value pin
12170        // below fires (`"capability" != "none"`) and the routes-through
12171        // assertion below still holds (production and const walk in
12172        // lockstep), which is the correct behavior: a rename on the
12173        // const drifts here first, not at a downstream consumer.
12174        assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
12175
12176        let mut s = three_member_spec();
12177        s.contratos.push(WitContract {
12178            de: "cart".into(),
12179            para: "catalog".into(),
12180            wit: "custom:exchange".into(),
12181            endpoint: Some("/leaked".into()),
12182            subject: None,
12183            slot: None,
12184        });
12185        match s.validate().unwrap_err() {
12186            AplicacaoError::ContratoWrongTarget { expected, .. } => {
12187                assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
12188            }
12189            other => panic!("expected ContratoWrongTarget, got {other:?}"),
12190        }
12191    }
12192
12193    #[test]
12194    fn unknown_wit_capability_only_validates() {
12195        let mut s = three_member_spec();
12196        s.contratos.push(WitContract {
12197            de: "cart".into(),
12198            para: "catalog".into(),
12199            // A WIT world we haven't yet shaped — accept it as a typed
12200            // capability edge so authors aren't blocked while the WIT
12201            // registry catches up. No payload field may be carried.
12202            wit: "custom:exchange".into(),
12203            endpoint: None,
12204            subject: None,
12205            slot: None,
12206        });
12207        s.validate().unwrap();
12208        let added = s.contratos.last().unwrap();
12209        assert_eq!(added.target().unwrap(), WitTarget::Capability);
12210    }
12211
12212    #[test]
12213    fn target_typed_view_round_trips_each_shape() {
12214        let http = contract_http("cart", "catalog", "/products/:id");
12215        assert_eq!(
12216            http.target().unwrap(),
12217            WitTarget::Http {
12218                endpoint: "/products/:id"
12219            }
12220        );
12221        let nats = WitContract {
12222            de: "a".into(),
12223            para: "b".into(),
12224            wit: "nats:pub-sub".into(),
12225            endpoint: None,
12226            subject: Some("topic.x".into()),
12227            slot: None,
12228        };
12229        assert_eq!(
12230            nats.target().unwrap(),
12231            WitTarget::PubSub { subject: "topic.x" }
12232        );
12233        let kv = WitContract {
12234            de: "a".into(),
12235            para: "b".into(),
12236            wit: "wasi:keyvalue/store".into(),
12237            endpoint: None,
12238            subject: None,
12239            slot: Some("checkout/$orderId".into()),
12240        };
12241        assert_eq!(
12242            kv.target().unwrap(),
12243            WitTarget::Store {
12244                slot: "checkout/$orderId"
12245            }
12246        );
12247    }
12248
12249    #[test]
12250    fn wit_contract_kind_predicates() {
12251        let http = contract_http("a", "b", "/x");
12252        assert!(http.is_http());
12253        assert!(!http.is_pubsub());
12254        assert!(!http.is_store());
12255        assert!(!http.is_capability());
12256
12257        let nats = WitContract {
12258            de: "a".into(),
12259            para: "b".into(),
12260            wit: "nats:pub-sub".into(),
12261            endpoint: None,
12262            subject: Some("topic.x".into()),
12263            slot: None,
12264        };
12265        assert!(nats.is_pubsub());
12266        assert!(!nats.is_http());
12267        assert!(!nats.is_capability());
12268
12269        let kv = WitContract {
12270            de: "a".into(),
12271            para: "b".into(),
12272            wit: "wasi:keyvalue/store".into(),
12273            endpoint: None,
12274            subject: None,
12275            slot: Some("checkout/$orderId".into()),
12276        };
12277        assert!(kv.is_store());
12278        assert!(!kv.is_http());
12279        assert!(!kv.is_capability());
12280
12281        // Fourth arm on the paired closed-set predicate family: the
12282        // payload-less capability edge that projects to the payload-
12283        // less [`WitTarget::Capability`] arm under [`WitContract::target`].
12284        // Extends the 3-arm predicate sweep this test opened to cover
12285        // the closed 4-way partition [`WitContract::is_capability`]
12286        // closes on the pre-projection WIT-shape axis, matched with the
12287        // sibling post-projection [`WitTarget`]-side `IsVariant`-derived
12288        // 4-arm predicate set.
12289        let cap = WitContract {
12290            de: "a".into(),
12291            para: "b".into(),
12292            wit: "custom:capability-only".into(),
12293            endpoint: None,
12294            subject: None,
12295            slot: None,
12296        };
12297        assert!(cap.is_capability());
12298        assert!(!cap.is_http());
12299        assert!(!cap.is_pubsub());
12300        assert!(!cap.is_store());
12301    }
12302
12303    // ── :contratos :wit value-shape gate ─────────────────────────────────
12304    //
12305    // Mirrors the `:contratos :endpoint` value-shape suite on the peer
12306    // dispatch-discriminator axis. Until this gate landed
12307    // `WitContract::target()` accepted any non-empty string and
12308    // silently demoted unrecognized shapes to a capability-only L4
12309    // edge — the canonical "I thought I had L7 HTTP routing, got
12310    // L4-only" footgun. Every authoring footgun the WIT registry's
12311    // own grammar rejects (uppercase, hyphen-for-colon typo,
12312    // whitespace, empty package, doubled `@`, …) now becomes a
12313    // caixa-build-time `ContratoWitInvalid` with the offending
12314    // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
12315    // as `ContratoEndpointInvalid` on the sibling axis; same shared
12316    // predicate (`crate::render::is_wit_world_ref`) ensures drift
12317    // between any two axes' rule enforcement is a build error at the
12318    // predicate, not piecemeal across renderers.
12319
12320    fn contrato_wit_err(wit: &str) -> AplicacaoError {
12321        // Fresh spec per call so the new contract doesn't collide on
12322        // identity with `three_member_spec`'s pre-existing entries.
12323        // The new edge uses `(payment, catalog)` — a pair the fixture
12324        // doesn't already declare — with no payload field set, so the
12325        // wit-shape gate fires before any payload-shape arm.
12326        let mut s = three_member_spec();
12327        s.contratos.push(WitContract {
12328            de: "payment".into(),
12329            para: "catalog".into(),
12330            wit: wit.into(),
12331            endpoint: None,
12332            subject: None,
12333            slot: None,
12334        });
12335        s.validate().unwrap_err()
12336    }
12337
12338    #[test]
12339    fn rejects_wit_with_uppercase_namespace() {
12340        // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
12341        // didn't match the lowercase `wasi:http/` prefix is_http() keys
12342        // off, so the dispatch fell through to the capability arm and
12343        // the contract silently rendered as an L4-only Cilium edge.
12344        // The new gate surfaces the uppercase typo at validate time
12345        // with the offending `:wit` named.
12346        let err = contrato_wit_err("WASI:http/proxy");
12347        assert!(
12348            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12349                if wit == "WASI:http/proxy" && reason.contains("lowercase")),
12350            "got {err:?}"
12351        );
12352    }
12353
12354    #[test]
12355    fn rejects_wit_with_hyphen_for_colon_typo() {
12356        // The canonical "I forgot the `:` separator" typo — pre-gate
12357        // this passed as Capability silently, so the renderer emitted
12358        // an L4-only policy where the author expected L7 HTTP rules.
12359        let err = contrato_wit_err("wasi-http/proxy");
12360        assert!(
12361            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12362                if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
12363            "got {err:?}"
12364        );
12365    }
12366
12367    #[test]
12368    fn rejects_wit_with_multiple_colons() {
12369        // Doubled `:` — the namespace/package split has nowhere to
12370        // anchor, so the dispatch silently demotes to Capability.
12371        let err = contrato_wit_err("wasi:http:proxy");
12372        assert!(
12373            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12374                if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
12375            "got {err:?}"
12376        );
12377    }
12378
12379    #[test]
12380    fn rejects_wit_with_empty_package() {
12381        // `wasi:` — namespace alone with no package. Pre-gate this
12382        // failed neither the is_http nor is_pubsub nor is_store
12383        // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
12384        // a bare `wasi:`), so it silently demoted to Capability.
12385        let err = contrato_wit_err("wasi:");
12386        assert!(
12387            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12388                if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
12389            "got {err:?}"
12390        );
12391    }
12392
12393    #[test]
12394    fn rejects_wit_with_underscore() {
12395        // Underscore — WIT identifiers are kebab-case, same rule
12396        // DNS-1123 enforces on its peer axes. The diagnostic carries
12397        // the explicit "use `-` instead" remediation.
12398        let err = contrato_wit_err("wasi:http_proxy");
12399        assert!(
12400            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12401                if wit == "wasi:http_proxy" && reason.contains('_')),
12402            "got {err:?}"
12403        );
12404    }
12405
12406    #[test]
12407    fn rejects_wit_with_whitespace() {
12408        // Whitespace mid-token — the prefix check matches but the
12409        // package-and-onward parse silently demoted to Capability.
12410        let err = contrato_wit_err("wasi:http proxy");
12411        assert!(
12412            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12413                if wit == "wasi:http proxy" && reason.contains("whitespace")),
12414            "got {err:?}"
12415        );
12416    }
12417
12418    #[test]
12419    fn rejects_wit_with_non_ascii() {
12420        // Un-percent-encoded non-ASCII byte — the canonical "I copied
12421        // the package name from a doc with smart quotes / accented
12422        // characters" footgun.
12423        let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
12424        assert!(
12425            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12426                if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
12427            "got {err:?}"
12428        );
12429    }
12430
12431    #[test]
12432    fn rejects_wit_with_consecutive_hyphens() {
12433        // `pub--sub` — WIT identifiers join words with single hyphens.
12434        let err = contrato_wit_err("nats:pub--sub");
12435        assert!(
12436            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12437                if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
12438            "got {err:?}"
12439        );
12440    }
12441
12442    #[test]
12443    fn rejects_wit_with_trailing_at_no_version() {
12444        // `wasi:http/proxy@` — the version-suffix author started to
12445        // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
12446        // parser would reject this; surface it at validate time.
12447        let err = contrato_wit_err("wasi:http/proxy@");
12448        assert!(
12449            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12450                if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
12451            "got {err:?}"
12452        );
12453    }
12454
12455    #[test]
12456    fn rejects_wit_too_long() {
12457        // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
12458        // The legitimate-shape arms all pass (lowercase, single `:`,
12459        // kebab-case identifiers); only the cap arm fires. Surfaces
12460        // the paste-from-binary / accidental-multi-line-blob landing
12461        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
12462        // on the peer axis.
12463        let big = format!("wasi:{}", "a".repeat(124));
12464        assert_eq!(big.len(), 129);
12465        let err = contrato_wit_err(&big);
12466        assert!(
12467            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12468                if wit == &big && reason.contains("max length of 128")),
12469            "got {err:?}"
12470        );
12471    }
12472
12473    #[test]
12474    fn wit_max_length_validates() {
12475        // 128-byte WIT reference — exactly the cap. Boundary pin:
12476        // drift in the cap surfaces here and at `rejects_wit_too_long`
12477        // simultaneously, mirroring
12478        // `http_contrato_endpoint_max_length_validates` on the peer
12479        // axis.
12480        let big = format!("wasi:{}", "a".repeat(123));
12481        assert_eq!(big.len(), 128);
12482        let mut s = three_member_spec();
12483        s.contratos.push(WitContract {
12484            de: "payment".into(),
12485            para: "catalog".into(),
12486            wit: big,
12487            endpoint: None,
12488            subject: None,
12489            slot: None,
12490        });
12491        s.validate().unwrap();
12492    }
12493
12494    #[test]
12495    fn wit_accepts_canonical_forms_at_aplicacao_layer() {
12496        // Positive-set sweep through the AplicacaoSpec::validate
12497        // surface (rather than the substrate-side predicate directly)
12498        // — pins every shape the existing test fixtures + the
12499        // checkout-aplicacao example carry, so the gate's accept-set
12500        // matches the substrate's emit-set. Drift between this list
12501        // and `render::tests::wit_world_ref_accepts_canonical_forms`
12502        // surfaces at the substrate layer's positive sweep — one
12503        // source of truth for the rule.
12504        for wit in [
12505            "wasi:http/proxy",
12506            "wasi:keyvalue/store",
12507            "nats:pub-sub",
12508            "kafka:topic",
12509            "custom:exchange",
12510            "pleme:cap/audit",
12511            "wasi:http/proxy@0.2.0",
12512        ] {
12513            // Payload field paired to the dispatched WIT shape so the
12514            // shape-↔-target arm doesn't fire instead of the wit-shape
12515            // arm we're exercising. Routes off the same
12516            // `wit_shape_is_http` / `wit_shape_is_pubsub` /
12517            // `wit_shape_is_store` free functions the production
12518            // `WitContract::is_http` / `is_pubsub` / `is_store`
12519            // methods delegate to (both consult the lifted
12520            // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
12521            // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
12522            // future prefix addition to the routing accept-set
12523            // reaches this test's payload-dispatch arm by
12524            // construction — no per-test-site drift can hide a
12525            // shape-→-target-slot mismatch that would silently
12526            // demote a canonical `:wit` value to the
12527            // `(None, None, None)` capability-only arm and let the
12528            // `AplicacaoSpec::validate` positive sweep pass on a
12529            // shape it should exercise as HTTP / pub-sub / store.
12530            let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
12531                (Some("/x".into()), None, None)
12532            } else if wit_shape_is_pubsub(wit) {
12533                (None, Some("topic.x".into()), None)
12534            } else if wit_shape_is_store(wit) {
12535                (None, None, Some("bucket/$key".into()))
12536            } else {
12537                (None, None, None)
12538            };
12539            let mut s = three_member_spec();
12540            s.contratos.push(WitContract {
12541                de: "payment".into(),
12542                para: "catalog".into(),
12543                wit: wit.into(),
12544                endpoint,
12545                subject,
12546                slot,
12547            });
12548            s.validate()
12549                .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
12550        }
12551    }
12552
12553    #[test]
12554    fn wit_shape_predicates_accept_canonical_prefix_set() {
12555        // Positive-set sweep pinning every prefix in
12556        // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
12557        // WIT_STORE_SHAPE_PREFIXES against the three free-function
12558        // dispatch predicates. The six prefixes are the load-bearing
12559        // routing keys the substrate's WIT-shape dispatch consults
12560        // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
12561        // key/value-store-slot admission); any drift between the
12562        // free-function accept-set and this list surfaces here
12563        // rather than at apply time as a silent
12564        // shape-→-capability-only demotion.
12565        assert!(wit_shape_is_http("wasi:http/proxy"));
12566        assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
12567        assert!(wit_shape_is_http("http:incoming"));
12568
12569        assert!(wit_shape_is_pubsub("nats:pub-sub"));
12570        assert!(wit_shape_is_pubsub("kafka:topic"));
12571
12572        assert!(wit_shape_is_store("wasi:keyvalue/store"));
12573        assert!(wit_shape_is_store("kv:cache/session"));
12574    }
12575
12576    #[test]
12577    fn wit_shape_predicates_reject_uncanonical_forms() {
12578        // Negative-set pin: the six canonical prefixes are
12579        // lowercase-only (mirrors the `is_wit_world_ref` substrate
12580        // predicate's lowercase invariant — see its docstring on the
12581        // "I thought I had L7 HTTP routing, got L4-only" footgun).
12582        // The empty string, an uppercase-prefixed form, a hyphen-
12583        // instead-of-colon typo, and a bare kebab identifier all miss
12584        // every shape arm — reachable-by-construction only via the
12585        // `is_wit_world_ref` gate that admission-checks the `:wit`
12586        // value first, but pinned here so any future
12587        // free-function change (e.g. a case-insensitive
12588        // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
12589        // this unit level.
12590        for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
12591            assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
12592            assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
12593            assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
12594        }
12595    }
12596
12597    #[test]
12598    fn wit_shape_predicates_partition_canonical_set() {
12599        // Every canonical prefix routes to exactly one shape arm —
12600        // the three prefix sets are pairwise disjoint. Pins the
12601        // routing property [`WitContract::target`] relies on: an
12602        // `is_http()` return of `true` guarantees `is_pubsub()` and
12603        // `is_store()` return `false`, so the shape-→-target-slot
12604        // dispatch (endpoint vs subject vs slot) is unambiguous.
12605        // Drift (e.g. a future `"kv:"` moved into the HTTP set
12606        // without removal from the store set) would silently route
12607        // one prefix to two arms and the first-matching-arm order
12608        // becomes load-bearing — this pin surfaces it as a build
12609        // error instead.
12610        for prefix in WIT_HTTP_SHAPE_PREFIXES {
12611            let sample = format!("{prefix}x");
12612            assert!(wit_shape_is_http(&sample));
12613            assert!(!wit_shape_is_pubsub(&sample));
12614            assert!(!wit_shape_is_store(&sample));
12615        }
12616        for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
12617            let sample = format!("{prefix}x");
12618            assert!(!wit_shape_is_http(&sample));
12619            assert!(wit_shape_is_pubsub(&sample));
12620            assert!(!wit_shape_is_store(&sample));
12621        }
12622        for prefix in WIT_STORE_SHAPE_PREFIXES {
12623            let sample = format!("{prefix}x");
12624            assert!(!wit_shape_is_http(&sample));
12625            assert!(!wit_shape_is_pubsub(&sample));
12626            assert!(wit_shape_is_store(&sample));
12627        }
12628    }
12629
12630    #[test]
12631    fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
12632        // Positive pin: [`wit_shape_matches`] is exactly the
12633        // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
12634        // parameterized on the accept-set. Two-prefix accept-set,
12635        // one-prefix accept-set, and empty accept-set (which must
12636        // reject everything, including the empty string — an empty
12637        // `any()` fold returns `false`) all pinned so a future
12638        // reimplementation that swaps `starts_with` for `contains`,
12639        // `==`, or a case-folded comparator surfaces at unit-test
12640        // time.
12641        let two = &["wasi:http/", "http:"];
12642        assert!(wit_shape_matches("wasi:http/proxy", two));
12643        assert!(wit_shape_matches("http:incoming", two));
12644        assert!(!wit_shape_matches("wasi:keyvalue/store", two));
12645
12646        let one = &["nats:"];
12647        assert!(wit_shape_matches("nats:pub-sub", one));
12648        assert!(!wit_shape_matches("kafka:topic", one));
12649
12650        // Empty accept-set matches nothing — the identity element
12651        // for the disjunctive `any()` fold across the prefix set.
12652        // Reachable via a future `wit_shape_is_<name>` const paired
12653        // to a still-empty prefix table on a nascent shape-arm draft.
12654        let empty: &[&str] = &[];
12655        assert!(!wit_shape_matches("wasi:http/proxy", empty));
12656        assert!(!wit_shape_matches("", empty));
12657
12658        // starts_with, not contains: a prefix embedded mid-string
12659        // never matches. Pins the routing invariant [`WitContract::target`]
12660        // relies on (an authored `:wit "custom:wasi:http/"` string
12661        // does not silently route through the HTTP arm just because
12662        // it happens to contain the canonical HTTP prefix).
12663        assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
12664    }
12665
12666    #[test]
12667    fn wit_shape_predicates_delegate_to_wit_shape_matches() {
12668        // Equivalence pin: each per-shape predicate is exactly
12669        // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
12670        // every canonical prefix + the empty string + one negative
12671        // sample against every peer so a future predicate that grew
12672        // its own inline `iter().any(starts_with)` (rather than
12673        // delegating through the lifted combinator) drifts loudly here
12674        // — the peer-const table's contents must agree with the
12675        // predicate's accept-set by construction.
12676        let samples = [
12677            String::new(),
12678            "wasi:http/proxy".to_string(),
12679            "http:incoming".to_string(),
12680            "nats:pub-sub".to_string(),
12681            "kafka:topic".to_string(),
12682            "wasi:keyvalue/store".to_string(),
12683            "kv:cache/session".to_string(),
12684            "custom-shape".to_string(),
12685            "WASI:HTTP/proxy".to_string(),
12686        ];
12687        for wit in &samples {
12688            assert_eq!(
12689                wit_shape_is_http(wit),
12690                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
12691                "wit_shape_is_http drifted from combinator on {wit:?}",
12692            );
12693            assert_eq!(
12694                wit_shape_is_pubsub(wit),
12695                wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
12696                "wit_shape_is_pubsub drifted from combinator on {wit:?}",
12697            );
12698            assert_eq!(
12699                wit_shape_is_store(wit),
12700                wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
12701                "wit_shape_is_store drifted from combinator on {wit:?}",
12702            );
12703        }
12704    }
12705
12706    #[test]
12707    fn wit_contract_shape_methods_delegate_to_free_functions() {
12708        // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
12709        // `is_store` are `&self` conveniences on top of the free
12710        // functions — for every canonical prefix the method's return
12711        // matches its free-function peer. Sweeps the union of the
12712        // three prefix sets so a future method that grew its own
12713        // inline prefix logic (rather than delegating) drifts loudly
12714        // here on the first prefix the free function accepts and the
12715        // method doesn't.
12716        for shape_set in [
12717            WIT_HTTP_SHAPE_PREFIXES,
12718            WIT_PUBSUB_SHAPE_PREFIXES,
12719            WIT_STORE_SHAPE_PREFIXES,
12720        ] {
12721            for prefix in shape_set {
12722                let c = WitContract {
12723                    de: "cart".into(),
12724                    para: "catalog".into(),
12725                    wit: format!("{prefix}x"),
12726                    endpoint: None,
12727                    subject: None,
12728                    slot: None,
12729                };
12730                assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
12731                assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
12732                assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
12733                assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
12734            }
12735        }
12736        // Capability-arm delegation sweep: two representative
12737        // Capability-shaped `:wit` values (a bare non-prefix-matching
12738        // WIT world, the deliberately-shaped empty string
12739        // [`WitContract::is_capability`]'s docstring calls out as
12740        // syntactically Capability). Extends the free-function
12741        // delegation pin onto the fourth arm so a future
12742        // [`WitContract::is_capability`] rewrite that grew an inline
12743        // prefix-set scan (rather than delegating through
12744        // [`wit_shape_is_capability`]) drifts loudly here on the first
12745        // Capability-shaped sample.
12746        for wit in ["custom:capability-only", ""] {
12747            let c = WitContract {
12748                de: "cart".into(),
12749                para: "catalog".into(),
12750                wit: wit.into(),
12751                endpoint: None,
12752                subject: None,
12753                slot: None,
12754            };
12755            assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
12756        }
12757    }
12758
12759    #[test]
12760    fn wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis() {
12761        // 4-way partition-witness pin on the raw `&str` axis: for every
12762        // canonical prefix in the three payload-arm accept-sets,
12763        // exactly one of the four [`wit_shape_is_http`] /
12764        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
12765        // [`wit_shape_is_capability`] free functions returns `true` and
12766        // the other three return `false` — the four-arm partition
12767        // witness that locks the free-function WIT-shape-classifier
12768        // family into a partition of the `:contratos :wit` axis
12769        // load-bearing. Peer of the sibling [`WitContract`]-surface
12770        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
12771        // partition pin — extends the discipline onto the raw `&str`
12772        // axis so any future arm addition (a hypothetical
12773        // `wasi:sockets/*` transport-layer shape, an `oci:*`
12774        // capability-import carrier per the sibling
12775        // [`wit_shape_matches`] docstring's trajectory bullet) that
12776        // landed on one of the payload-arm free functions without
12777        // shrinking [`wit_shape_is_capability`]'s accept-set surfaces
12778        // here as two arms returning `true` simultaneously at
12779        // caixa-core build time rather than a silent per-consumer
12780        // misclassification at renderer emit time.
12781        for shape_set in [
12782            WIT_HTTP_SHAPE_PREFIXES,
12783            WIT_PUBSUB_SHAPE_PREFIXES,
12784            WIT_STORE_SHAPE_PREFIXES,
12785        ] {
12786            for prefix in shape_set {
12787                let wit = format!("{prefix}x");
12788                let hits = [
12789                    wit_shape_is_http(&wit),
12790                    wit_shape_is_pubsub(&wit),
12791                    wit_shape_is_store(&wit),
12792                    wit_shape_is_capability(&wit),
12793                ]
12794                .iter()
12795                .filter(|&&b| b)
12796                .count();
12797                assert_eq!(
12798                    hits,
12799                    1,
12800                    "raw-&str WIT-shape 4-way predicate partition must \
12801                     admit exactly one arm per canonical prefix; got {hits} \
12802                     hits at wit={wit:?} (is_http={}, is_pubsub={}, is_store={}, \
12803                     is_capability={})",
12804                    wit_shape_is_http(&wit),
12805                    wit_shape_is_pubsub(&wit),
12806                    wit_shape_is_store(&wit),
12807                    wit_shape_is_capability(&wit),
12808                );
12809            }
12810        }
12811        // Capability-arm sweep on the raw `&str` axis: two
12812        // representative Capability-shaped `:wit` values (a bare non-
12813        // prefix-matching WIT world, the deliberately-shaped empty
12814        // string the pure classifier still admits per
12815        // [`wit_shape_is_capability`]'s docstring). Both must land on
12816        // the fourth arm exclusively so the partition witness holds
12817        // across the full 4-arm closure on the raw `&str` axis.
12818        for wit in ["custom:capability-only", ""] {
12819            let hits = [
12820                wit_shape_is_http(wit),
12821                wit_shape_is_pubsub(wit),
12822                wit_shape_is_store(wit),
12823                wit_shape_is_capability(wit),
12824            ]
12825            .iter()
12826            .filter(|&&b| b)
12827            .count();
12828            assert_eq!(
12829                hits, 1,
12830                "raw-&str WIT-shape 4-way predicate partition must \
12831                 admit exactly one arm on Capability-shaped wit={wit:?}"
12832            );
12833            assert!(
12834                wit_shape_is_capability(wit),
12835                "wit={wit:?} must project onto the Capability arm on the raw-&str axis"
12836            );
12837        }
12838    }
12839
12840    #[test]
12841    fn wit_shape_is_capability_composes_through_payload_arm_predicate_negation() {
12842        // Composition-witness pin: [`wit_shape_is_capability`] is the
12843        // exact-inverse disjunction of the sibling payload-arm free-
12844        // function trio [`wit_shape_is_http`] / [`wit_shape_is_pubsub`]
12845        // / [`wit_shape_is_store`]. A future reimplementation that
12846        // grew its own prefix-set scan (e.g. inlining a fourth
12847        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does
12848        // not own today) rather than delegating to the sibling trio
12849        // would drift loudly here — the composition contract binds the
12850        // fourth-arm free-function predicate to the exact-inverse of
12851        // the three payload-arm free-function predicates, so any
12852        // rebrand of any prefix-set const flows through
12853        // [`wit_shape_is_capability`] by construction without a
12854        // coordinated per-consumer rewrite. Peer of the sibling
12855        // [`WitContract`]-surface
12856        // [`wit_contract_is_capability_composes_through_shape_predicate_negation`]
12857        // composition pin — extends the discipline onto the raw
12858        // `&str` axis.
12859        let mut cases: Vec<String> = Vec::new();
12860        for shape_set in [
12861            WIT_HTTP_SHAPE_PREFIXES,
12862            WIT_PUBSUB_SHAPE_PREFIXES,
12863            WIT_STORE_SHAPE_PREFIXES,
12864        ] {
12865            for prefix in shape_set {
12866                cases.push(format!("{prefix}x"));
12867            }
12868        }
12869        cases.push("custom:capability-only".to_string());
12870        cases.push(String::new());
12871        for wit in cases {
12872            assert_eq!(
12873                wit_shape_is_capability(&wit),
12874                !wit_shape_is_http(&wit) && !wit_shape_is_pubsub(&wit) && !wit_shape_is_store(&wit),
12875                "wit_shape_is_capability must equal \
12876                 !wit_shape_is_http() && !wit_shape_is_pubsub() && !wit_shape_is_store() \
12877                 at wit={wit:?}"
12878            );
12879        }
12880    }
12881
12882    #[test]
12883    fn wit_shape_classifier_family_is_const_fn() {
12884        // Fail-before-pass-after pin on the 4-arm free-function WIT-
12885        // shape classifier family's `const`-eval posture. Each of the
12886        // four peer classifiers ([`wit_shape_is_http`] /
12887        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
12888        // [`wit_shape_is_capability`]) and the underlying combinator
12889        // [`wit_shape_matches`] must be `pub const fn` — any future
12890        // accidental downgrade to non-`const` fails the `const fn`
12891        // wrappers below at caixa-core build time with E0015
12892        // (`cannot call non-const function`), strictly stronger than
12893        // a runtime `assert!` and strictly stronger than the module-
12894        // scope `const _: () = assert!(…)` pins immediately after the
12895        // classifier declarations (those anchor specific accept-set
12896        // truth-table entries; this pin anchors the `const` posture
12897        // itself via `const fn` wrappers that are only well-formed
12898        // when the callee is itself `const fn`).
12899        //
12900        // Verified fail-before-pass-after by locally reverting
12901        // `pub const fn` → `pub fn` on each classifier and observing
12902        // E0015 at every corresponding wrapper call site (build
12903        // error, no test-time surface), then restoring `pub const fn`
12904        // and observing the pin pass at test time. Peer of the
12905        // sibling M3
12906        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
12907        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
12908        // M2
12909        // [`child_spec_restart_accessor_is_const_fn`] /
12910        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
12911        // and M3
12912        // [`placement_estrategia_accessor_is_const_fn`] /
12913        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
12914        // sibling `const`-eval-surface-pass axes.
12915        const fn matches_via_const_fn(wit: &str, prefixes: &[&str]) -> bool {
12916            wit_shape_matches(wit, prefixes)
12917        }
12918        const fn http_via_const_fn(wit: &str) -> bool {
12919            wit_shape_is_http(wit)
12920        }
12921        const fn pubsub_via_const_fn(wit: &str) -> bool {
12922            wit_shape_is_pubsub(wit)
12923        }
12924        const fn store_via_const_fn(wit: &str) -> bool {
12925            wit_shape_is_store(wit)
12926        }
12927        const fn capability_via_const_fn(wit: &str) -> bool {
12928            wit_shape_is_capability(wit)
12929        }
12930        // Sweep one canonical accept-set sample per arm plus the
12931        // payload-less/empty capability samples, asserting the
12932        // wrapper and direct dispatches agree byte-for-byte across
12933        // the closed 4-arm partition.
12934        let cases: [(&str, bool, bool, bool, bool); 6] = [
12935            ("wasi:http/proxy", true, false, false, false),
12936            ("http:incoming", true, false, false, false),
12937            ("nats:events", false, true, false, false),
12938            ("kafka:topic", false, true, false, false),
12939            ("wasi:keyvalue/store", false, false, true, false),
12940            ("kv:cache", false, false, true, false),
12941        ];
12942        for (wit, is_http, is_pubsub, is_store, _is_capability) in cases {
12943            assert_eq!(
12944                matches_via_const_fn(wit, WIT_HTTP_SHAPE_PREFIXES),
12945                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
12946                "wit_shape_matches const fn wrapper disagrees at wit={wit:?}",
12947            );
12948            assert_eq!(http_via_const_fn(wit), wit_shape_is_http(wit));
12949            assert_eq!(pubsub_via_const_fn(wit), wit_shape_is_pubsub(wit));
12950            assert_eq!(store_via_const_fn(wit), wit_shape_is_store(wit));
12951            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
12952            assert_eq!(wit_shape_is_http(wit), is_http);
12953            assert_eq!(wit_shape_is_pubsub(wit), is_pubsub);
12954            assert_eq!(wit_shape_is_store(wit), is_store);
12955        }
12956        // Payload-less capability arm (the 4th partition arm).
12957        let capability_samples: [&str; 3] =
12958            ["wasi:filesystem/preopens", "custom:capability-only", ""];
12959        for wit in capability_samples {
12960            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
12961            assert!(wit_shape_is_capability(wit));
12962            assert!(!wit_shape_is_http(wit));
12963            assert!(!wit_shape_is_pubsub(wit));
12964            assert!(!wit_shape_is_store(wit));
12965        }
12966    }
12967
12968    #[test]
12969    fn wit_shape_matches_composes_through_bytes_starts_with_across_boundary_lengths() {
12970        // Composition-witness pin: [`wit_shape_matches`] agrees with
12971        // the reference `prefixes.iter().any(|p| wit.starts_with(p))`
12972        // dispatch (the prior non-`const` implementation) across
12973        // boundary lengths — empty `wit`, empty prefix, one-byte
12974        // slack, prefix longer than `wit`, one-byte trailing slack.
12975        // The rewrite to a byte-level manual starts_with loop (the
12976        // enabler for the `pub const fn` posture) must not change any
12977        // truth-table entry on the canonical accept-set — this pin
12978        // sweeps a targeted boundary corpus and asserts byte-for-byte
12979        // agreement, locking the const-fn rewrite's semantics against
12980        // the prior iterator body by construction.
12981        let prefixes = &["wasi:http/", "http:"][..];
12982        let cases: [(&str, bool); 12] = [
12983            ("wasi:http/proxy", true),
12984            ("wasi:http/", true), // exact-length match on prefix
12985            ("wasi:http", false), // one byte short
12986            ("http:", true),
12987            ("http:incoming", true),
12988            ("http", false), // one byte short
12989            ("", false),
12990            ("wasi:https/proxy", false),
12991            ("nats:events", false),
12992            ("HTTPS:", false), // uppercase — no case-fold in classifier
12993            ("wasi:HTTP/proxy", false),
12994            ("wasi:http", false),
12995        ];
12996        for (wit, expected) in cases {
12997            assert_eq!(
12998                wit_shape_matches(wit, prefixes),
12999                expected,
13000                "wit_shape_matches disagrees with reference at wit={wit:?}",
13001            );
13002            // Byte-equal to the iterator body it replaced.
13003            let via_iter = prefixes.iter().any(|p| wit.starts_with(p));
13004            assert_eq!(
13005                wit_shape_matches(wit, prefixes),
13006                via_iter,
13007                "wit_shape_matches must byte-equal iter().any(starts_with) at wit={wit:?}",
13008            );
13009        }
13010        // Empty prefix set → always false regardless of `wit`.
13011        let empty: &[&str] = &[];
13012        assert!(!wit_shape_matches("", empty));
13013        assert!(!wit_shape_matches("wasi:http/proxy", empty));
13014        // Empty prefix inside a non-empty set → always true (every
13015        // string starts with the empty string, matching the
13016        // iterator body's semantics on `str::starts_with("")`).
13017        let contains_empty: &[&str] = &["nats:", ""];
13018        assert!(wit_shape_matches("", contains_empty));
13019        assert!(wit_shape_matches("wasi:http/proxy", contains_empty));
13020    }
13021
13022    #[test]
13023    fn wit_contract_is_capability_partitions_the_wit_shape_space() {
13024        // 4-way partition-witness pin: for every canonical prefix in
13025        // the payload-arm accept-sets, exactly one of the four
13026        // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
13027        // [`WitContract::is_store`] / [`WitContract::is_capability`]
13028        // predicates returns `true` and the other three return `false`
13029        // — the four-arm partition witness that locks the substrate's
13030        // WIT-shape-space closure on the pre-projection axis load-
13031        // bearing. A future arm addition (a hypothetical fourth
13032        // payload-shape prefix set, a `wasi:sockets/*` transport-layer
13033        // shape) that landed on one of the payload-arm predicates
13034        // without shrinking [`WitContract::is_capability`]'s accept-set
13035        // would surface here as two arms returning `true` simultaneously
13036        // — a partition-witness break the pin catches at caixa-core
13037        // build time rather than a silent per-consumer misclassification
13038        // at renderer emit time. Peer of the sibling `WitTarget`-side
13039        // [`tests::wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`]
13040        // partition-witness pin on the post-projection payload-scalar
13041        // arm-set — extends the discipline onto the pre-projection
13042        // 4-arm shape-space.
13043        for shape_set in [
13044            WIT_HTTP_SHAPE_PREFIXES,
13045            WIT_PUBSUB_SHAPE_PREFIXES,
13046            WIT_STORE_SHAPE_PREFIXES,
13047        ] {
13048            for prefix in shape_set {
13049                let c = WitContract {
13050                    de: "cart".into(),
13051                    para: "catalog".into(),
13052                    wit: format!("{prefix}x"),
13053                    endpoint: None,
13054                    subject: None,
13055                    slot: None,
13056                };
13057                let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
13058                    .iter()
13059                    .filter(|&&b| b)
13060                    .count();
13061                assert_eq!(
13062                    hits,
13063                    1,
13064                    "WitContract WIT-shape 4-way predicate partition must \
13065                     admit exactly one arm per canonical prefix; got {hits} \
13066                     hits at wit={:?} (is_http={}, is_pubsub={}, is_store={}, \
13067                     is_capability={})",
13068                    c.wit,
13069                    c.is_http(),
13070                    c.is_pubsub(),
13071                    c.is_store(),
13072                    c.is_capability(),
13073                );
13074            }
13075        }
13076        // Capability-arm sweep: two representative capability shapes
13077        // (a bare WIT world outside the three payload-arm prefix sets,
13078        // and the deliberately-shaped empty string that
13079        // [`crate::render::is_wit_world_ref`] rejects at
13080        // [`WitContract::target`] time but which the pure classifier
13081        // still admits — see the method docstring's "purely syntactic
13082        // classification" note). Both must land on the fourth arm
13083        // exclusively, so the partition witness holds across the full
13084        // 4-arm closure.
13085        for wit in ["custom:capability-only", ""] {
13086            let c = WitContract {
13087                de: "cart".into(),
13088                para: "catalog".into(),
13089                wit: wit.into(),
13090                endpoint: None,
13091                subject: None,
13092                slot: None,
13093            };
13094            let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
13095                .iter()
13096                .filter(|&&b| b)
13097                .count();
13098            assert_eq!(
13099                hits, 1,
13100                "WitContract WIT-shape 4-way predicate partition must \
13101                 admit exactly one arm on Capability-shaped wit={wit:?}"
13102            );
13103            assert!(
13104                c.is_capability(),
13105                "wit={wit:?} must project onto the Capability arm"
13106            );
13107        }
13108    }
13109
13110    #[test]
13111    fn wit_contract_is_capability_composes_through_shape_predicate_negation() {
13112        // Composition-witness pin: [`WitContract::is_capability`] is the
13113        // exact-inverse disjunction of the sibling payload-arm predicate
13114        // trio [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
13115        // [`WitContract::is_store`]. A future reimplementation that
13116        // grew its own prefix-set scan (e.g. inlining a fourth
13117        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does not
13118        // own today) rather than delegating to the sibling trio would
13119        // drift loudly here — the composition contract binds the
13120        // fourth-arm predicate to the exact-inverse of the three
13121        // payload-arm predicates, so any rebrand of any prefix-set const
13122        // flows through this method by construction without a
13123        // coordinated per-consumer rewrite. Sweeps the union of the
13124        // three payload-arm prefix sets plus two Capability-shaped
13125        // shapes (a bare non-prefix-matching WIT world, the deliberately-
13126        // empty string the pure classifier still admits per the method
13127        // docstring's "purely syntactic classification" note).
13128        let mut cases: Vec<String> = Vec::new();
13129        for shape_set in [
13130            WIT_HTTP_SHAPE_PREFIXES,
13131            WIT_PUBSUB_SHAPE_PREFIXES,
13132            WIT_STORE_SHAPE_PREFIXES,
13133        ] {
13134            for prefix in shape_set {
13135                cases.push(format!("{prefix}x"));
13136            }
13137        }
13138        cases.push("custom:capability-only".to_string());
13139        cases.push(String::new());
13140        for wit in cases {
13141            let c = WitContract {
13142                de: "cart".into(),
13143                para: "catalog".into(),
13144                wit: wit.clone(),
13145                endpoint: None,
13146                subject: None,
13147                slot: None,
13148            };
13149            assert_eq!(
13150                c.is_capability(),
13151                !c.is_http() && !c.is_pubsub() && !c.is_store(),
13152                "WitContract::is_capability must equal \
13153                 !is_http() && !is_pubsub() && !is_store() at wit={wit:?}"
13154            );
13155        }
13156    }
13157
13158    #[test]
13159    fn wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant() {
13160        // Cross-projection-witness pin: whenever [`WitContract::target`]
13161        // succeeds, the pre-projection [`WitContract::is_capability`]
13162        // classification agrees with the post-projection
13163        // [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
13164        // predicate — the 4-arm typed partition on the substrate's
13165        // typed-view surface (7f6aa98 IsVariant lift) and the peer 4-arm
13166        // partition on the pre-projection axis line up by construction.
13167        // A future divergence between the two axes (a peer
13168        // [`WitTarget`] variant addition that landed on the typed-view
13169        // surface without a peer prefix-set + [`WitContract`] predicate
13170        // extension, or vice versa) would surface here at caixa-core
13171        // build time rather than a silent per-consumer split at renderer
13172        // emit time. Peer of the sibling pre-/post-projection
13173        // agreement pins the payload-carrier trio
13174        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
13175        // [`WitContract::slot`] on pre-projection; [`WitTarget::http_endpoint`]
13176        // / [`WitTarget::pubsub_subject`] / [`WitTarget::store_slot`] on
13177        // post-projection — b11bb49 trio lift) already carry across the
13178        // three payload arms — this pin closes the pair on the fourth
13179        // payload-less arm.
13180        let http = WitContract {
13181            de: "cart".into(),
13182            para: "catalog".into(),
13183            wit: "wasi:http/proxy".into(),
13184            endpoint: Some("/x".into()),
13185            subject: None,
13186            slot: None,
13187        };
13188        assert!(!http.is_capability());
13189        assert!(!http.target().unwrap().is_capability());
13190
13191        let nats = WitContract {
13192            de: "cart".into(),
13193            para: "catalog".into(),
13194            wit: "nats:pub-sub".into(),
13195            endpoint: None,
13196            subject: Some("events.x".into()),
13197            slot: None,
13198        };
13199        assert!(!nats.is_capability());
13200        assert!(!nats.target().unwrap().is_capability());
13201
13202        let kv = WitContract {
13203            de: "cart".into(),
13204            para: "catalog".into(),
13205            wit: "wasi:keyvalue/store".into(),
13206            endpoint: None,
13207            subject: None,
13208            slot: Some("checkout/$orderId".into()),
13209        };
13210        assert!(!kv.is_capability());
13211        assert!(!kv.target().unwrap().is_capability());
13212
13213        let cap = WitContract {
13214            de: "cart".into(),
13215            para: "catalog".into(),
13216            wit: "custom:capability-only".into(),
13217            endpoint: None,
13218            subject: None,
13219            slot: None,
13220        };
13221        assert!(cap.is_capability());
13222        assert!(cap.target().unwrap().is_capability());
13223    }
13224
13225    #[test]
13226    fn wit_contract_pre_projection_accessor_family_is_const_fn() {
13227        // Fail-before-pass-after pin on the [`WitContract`] pre-
13228        // projection accessor family's `const`-eval-surface posture.
13229        // Each of the three per-`:contratos` byte-string scalar
13230        // accessors ([`WitContract::source`] / [`WitContract::destination`]
13231        // / [`WitContract::world_ref`], each projecting through
13232        // `String::as_str` — const-stable since Rust 1.87, well within
13233        // the workspace MSRV) and each of the four peer WIT-shape
13234        // predicates ([`WitContract::is_http`] /
13235        // [`WitContract::is_pubsub`] / [`WitContract::is_store`] /
13236        // [`WitContract::is_capability`], each composing
13237        // `wit_shape_is_<arm>(self.world_ref())` on the `pub const fn`
13238        // free-function classifier family the sibling
13239        // [`wit_shape_classifier_family_is_const_fn`] pin already
13240        // anchors on the raw `&str → bool` axis) must be `pub const fn`
13241        // — any future accidental downgrade to non-`const` fails the
13242        // `const fn` wrappers below at caixa-core build time with E0015
13243        // (`cannot call non-const function`), strictly stronger than a
13244        // runtime `assert!` and strictly stronger than a
13245        // module-scope `const _: () = assert!(…)` pin (which cannot be
13246        // formed on a `&WitContract` fixture because the type's
13247        // `String` / `Option<String>` carriers rule out `const`-context
13248        // construction; the `const fn` wrapper is the load-bearing
13249        // shape that side-steps the destructor-in-const restriction on
13250        // the value axis while still pinning the `const`-fn posture on
13251        // the callee).
13252        //
13253        // Peer of the sibling free-function classifier pin
13254        // [`wit_shape_classifier_family_is_const_fn`] (d46420c) on the
13255        // raw `&str → bool` axis — this pin extends the same
13256        // `const`-eval-surface discipline onto the peer method surface
13257        // that composes through those free-function classifiers, and
13258        // simultaneously onto the underlying per-`:contratos`
13259        // byte-string scalar-accessor trio each predicate reads
13260        // through. Sibling of the peer M3
13261        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
13262        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
13263        // M2
13264        // [`child_spec_restart_accessor_is_const_fn`] /
13265        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
13266        // and M3
13267        // [`placement_estrategia_accessor_is_const_fn`] /
13268        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
13269        // sibling `const`-eval-surface-pass axes.
13270        const fn source_via_const_fn(c: &WitContract) -> &str {
13271            c.source()
13272        }
13273        const fn destination_via_const_fn(c: &WitContract) -> &str {
13274            c.destination()
13275        }
13276        const fn world_ref_via_const_fn(c: &WitContract) -> &str {
13277            c.world_ref()
13278        }
13279        const fn is_http_via_const_fn(c: &WitContract) -> bool {
13280            c.is_http()
13281        }
13282        const fn is_pubsub_via_const_fn(c: &WitContract) -> bool {
13283            c.is_pubsub()
13284        }
13285        const fn is_store_via_const_fn(c: &WitContract) -> bool {
13286            c.is_store()
13287        }
13288        const fn is_capability_via_const_fn(c: &WitContract) -> bool {
13289            c.is_capability()
13290        }
13291        // Sweep one canonical accept-set sample per WIT-shape arm plus
13292        // a payload-less capability sample, asserting the wrapper and
13293        // direct dispatches agree byte-for-byte across the closed
13294        // 4-arm partition on both the scalar-accessor trio and the
13295        // WIT-shape-predicate family.
13296        for (wit, is_http, is_pubsub, is_store, is_capability) in [
13297            ("wasi:http/proxy", true, false, false, false),
13298            ("http:incoming", true, false, false, false),
13299            ("nats:events", false, true, false, false),
13300            ("kafka:topic", false, true, false, false),
13301            ("wasi:keyvalue/store", false, false, true, false),
13302            ("kv:cache", false, false, true, false),
13303            ("custom:capability-only", false, false, false, true),
13304            ("", false, false, false, true),
13305        ] {
13306            let c = WitContract {
13307                de: "cart".into(),
13308                para: "catalog".into(),
13309                wit: wit.into(),
13310                endpoint: None,
13311                subject: None,
13312                slot: None,
13313            };
13314            assert_eq!(source_via_const_fn(&c), c.source());
13315            assert_eq!(destination_via_const_fn(&c), c.destination());
13316            assert_eq!(world_ref_via_const_fn(&c), c.world_ref());
13317            assert_eq!(is_http_via_const_fn(&c), c.is_http());
13318            assert_eq!(is_pubsub_via_const_fn(&c), c.is_pubsub());
13319            assert_eq!(is_store_via_const_fn(&c), c.is_store());
13320            assert_eq!(is_capability_via_const_fn(&c), c.is_capability());
13321            assert_eq!(c.source(), "cart");
13322            assert_eq!(c.destination(), "catalog");
13323            assert_eq!(c.world_ref(), wit);
13324            assert_eq!(c.is_http(), is_http);
13325            assert_eq!(c.is_pubsub(), is_pubsub);
13326            assert_eq!(c.is_store(), is_store);
13327            assert_eq!(c.is_capability(), is_capability);
13328        }
13329    }
13330
13331    #[test]
13332    fn wit_contract_identity_projection_accessor_is_const_fn() {
13333        // Fail-before-pass-after pin on the [`WitContract::identity`]
13334        // six-arm composite-projection accessor's `const`-eval-surface
13335        // posture. The accessor projects the typed edge's six identity
13336        // arms (`:de` / `:para` / `:wit` / `:endpoint` / `:subject` /
13337        // `:slot`) as a borrowed [`ContratoIdentity<'_>`] six-tuple —
13338        // every callee is itself `pub const fn` ([`WitContract::source`]
13339        // / [`WitContract::destination`] / [`WitContract::world_ref`]
13340        // through `String::as_str`, const-stable since Rust 1.87;
13341        // [`WitContract::endpoint`] / [`WitContract::subject`] /
13342        // [`WitContract::slot`] through the sibling `match &self
13343        // .<field> { Some(s) => Some(s.as_str()), None => None }` shape
13344        // 0650f64 closed the const-eval surface on) and the tuple
13345        // constructor from borrowed-reference / `Option`-of-borrowed-
13346        // reference arms is trivially const. Any future accidental
13347        // downgrade fails the `identity_via_const_fn` wrapper at
13348        // caixa-core build time with E0015 (`cannot call non-const
13349        // method`), strictly stronger than a runtime `assert!` and
13350        // strictly stronger than a module-scope `const _: () =
13351        // assert!(…)` pin (which cannot be formed on a `&WitContract`
13352        // fixture because the type's `String` / `Option<String>`
13353        // carriers rule out `const`-context value construction; the
13354        // `const fn` wrapper is the load-bearing shape that side-steps
13355        // the destructor-in-const restriction on the value axis while
13356        // still pinning the `const`-fn posture on the callee — mirror
13357        // of the sibling
13358        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
13359        // pin's discipline verbatim on the peer scalar-accessor
13360        // surface).
13361        //
13362        // Peer of the sibling
13363        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
13364        // (279823b) pin on the six per-`:contratos` scalar-accessor
13365        // callees this composite-projection reads through — where that
13366        // pin anchors the const-eval surface at the six individual
13367        // scalar-accessor arms, this pin extends the same posture onto
13368        // the composite six-tuple projection every consumer that dedups
13369        // typed edges on the [`ContratoIdentity`] axis keys off (the
13370        // [`AplicacaoSpec::validate`]-side duplicate-`:contratos`
13371        // scanner + its BTreeMap dedup key; a future per-Aplicacao CR
13372        // materializer's per-edge identity-based admission webhook; a
13373        // future L7 policy-emitter that shards CNPs by identity-tuple
13374        // rather than by name). Same fail-before-pass-after wrapper
13375        // discipline as the peer M2 / M3 accessor-family pins on the
13376        // sibling `const`-eval-surface passes.
13377        const fn identity_via_const_fn(c: &WitContract) -> ContratoIdentity<'_> {
13378            c.identity()
13379        }
13380        // Sweep one canonical WIT-shape sample per payload-carrier arm
13381        // plus a payload-less capability sample so the pin exercises
13382        // both `Some(_)`-carrying and `None`-carrying arms on all three
13383        // `Option<String>` payload-carrier axes (`:endpoint` / `:subject`
13384        // / `:slot`) — every wrapper dispatch must agree byte-for-byte
13385        // with the direct method call on every arm of the closed WIT-
13386        // shape partition.
13387        for (wit, endpoint, subject, slot) in [
13388            ("wasi:http/proxy", Some("/checkout"), None, None),
13389            ("http:incoming", Some("/api"), None, None),
13390            ("nats:events", None, Some("orders.placed"), None),
13391            ("kafka:topic", None, Some("orders.stream"), None),
13392            ("wasi:keyvalue/store", None, None, Some("carts/{id}")),
13393            ("kv:cache", None, None, Some("session/{token}")),
13394            ("custom:capability-only", None, None, None),
13395        ] {
13396            let c = WitContract {
13397                de: "cart".into(),
13398                para: "catalog".into(),
13399                wit: wit.into(),
13400                endpoint: endpoint.map(str::to_string),
13401                subject: subject.map(str::to_string),
13402                slot: slot.map(str::to_string),
13403            };
13404            assert_eq!(identity_via_const_fn(&c), c.identity());
13405            assert_eq!(
13406                c.identity(),
13407                ("cart", "catalog", wit, endpoint, subject, slot,),
13408            );
13409        }
13410    }
13411
13412    #[test]
13413    fn m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn() {
13414        // Fail-before-pass-after pin on the four M3 mesh-slot
13415        // `String → &str` scalar accessors ([`Membro::nome`] /
13416        // [`Membro::versao_requirement`] on the per-`:membros` axis,
13417        // [`Entrada::hostname`] / [`Entrada::destination`] on the
13418        // per-`:entrada` axis) — each projects the typed slot's
13419        // [`String`] storage through the `pub const fn`
13420        // [`String::as_str`] (const-stable since Rust 1.87, well
13421        // within the workspace MSRV) and any future accidental
13422        // downgrade to non-`const` fails the corresponding
13423        // `<name>_via_const_fn` wrapper at caixa-core build time with
13424        // E0015 (`cannot call non-const method`), strictly stronger
13425        // than a runtime `assert!` and strictly stronger than a
13426        // module-scope `const _: () = assert!(…)` pin (which cannot
13427        // be formed on `&Membro` / `&Entrada` fixtures because the
13428        // types' `String` carriers rule out `const`-context value
13429        // construction; the `const fn` wrapper is the load-bearing
13430        // shape that side-steps the destructor-in-const restriction
13431        // on the value axis while still pinning the `const`-fn
13432        // posture on the callee — mirror of the sibling
13433        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
13434        // (279823b) pin on the per-`:contratos` axis). Peer of the
13435        // sibling per-M2/M3/universal-axis `String → &str` accessor
13436        // family pins on the sibling `const`-eval-surface passes
13437        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
13438        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
13439        // typed-newtype wrapper,
13440        // [`crate::supervisor::ChildSpec::nome`] /
13441        // [`crate::supervisor::ChildSpec::versao_requirement`] at the
13442        // M2 supervisor-tree axis,
13443        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
13444        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
13445        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
13446        // axis, and the sibling per-`:contratos`
13447        // [`WitContract::source`] / [`WitContract::destination`] /
13448        // [`WitContract::world_ref`] trio at 279823b).
13449        const fn membro_nome_via_const_fn(m: &Membro) -> &str {
13450            m.nome()
13451        }
13452        const fn membro_versao_via_const_fn(m: &Membro) -> &str {
13453            m.versao_requirement()
13454        }
13455        const fn entrada_hostname_via_const_fn(e: &Entrada) -> &str {
13456            e.hostname()
13457        }
13458        const fn entrada_destination_via_const_fn(e: &Entrada) -> &str {
13459            e.destination()
13460        }
13461        for (caixa, versao) in [
13462            ("cart", "^0.1"),
13463            ("catalog-v2", "~0.2.3"),
13464            ("checkout", "*"),
13465        ] {
13466            let m = Membro {
13467                caixa: caixa.into(),
13468                versao: versao.into(),
13469            };
13470            assert_eq!(membro_nome_via_const_fn(&m), m.nome());
13471            assert_eq!(membro_versao_via_const_fn(&m), m.versao_requirement());
13472            assert_eq!(m.nome(), caixa);
13473            assert_eq!(m.versao_requirement(), versao);
13474        }
13475        for (host, para) in [
13476            ("cart.example.com", "cart"),
13477            ("api.checkout.io", "checkout"),
13478        ] {
13479            let e = Entrada {
13480                host: host.into(),
13481                para: para.into(),
13482                paths: vec![],
13483                port: DEFAULT_SERVICO_PORT,
13484            };
13485            assert_eq!(entrada_hostname_via_const_fn(&e), e.hostname());
13486            assert_eq!(entrada_destination_via_const_fn(&e), e.destination());
13487            assert_eq!(e.hostname(), host);
13488            assert_eq!(e.destination(), para);
13489        }
13490    }
13491
13492    #[test]
13493    fn m3_option_string_scalar_accessor_family_is_const_fn() {
13494        // Fail-before-pass-after pin on the five M3 mesh-slot
13495        // `Option<String> → Option<&str>` scalar accessors
13496        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
13497        // [`WitContract::slot`] on the per-`:contratos` HTTP /
13498        // pub-sub / key-value payload-carrier trio,
13499        // [`Placement::shard_key`] / [`Placement::affinity`] on the
13500        // per-`:placement` Akka-sharding-key + Adaptive-compression-
13501        // hint pair). Each accessor destructures the typed slot's
13502        // `Option<String>` storage through the `match &self.<field> {
13503        // Some(s) => Some(s.as_str()), None => None }` shape —
13504        // routing through [`String::as_str`] (const-stable since Rust
13505        // 1.87, well within the workspace MSRV) rather than the
13506        // non-const [`Option::as_deref`] the pre-lift bodies carried
13507        // — and any future accidental downgrade to non-`const` fails
13508        // the corresponding `<name>_via_const_fn` wrapper at
13509        // caixa-core build time with E0015 (`cannot call non-const
13510        // method`), strictly stronger than a runtime `assert!` and
13511        // strictly stronger than a module-scope `const _: () =
13512        // assert!(…)` pin (which cannot be formed on `&WitContract`
13513        // / `&Placement` fixtures because the types' `String` /
13514        // `Option<String>` carriers rule out `const`-context value
13515        // construction; the `const fn` wrapper is the load-bearing
13516        // shape that side-steps the destructor-in-const restriction
13517        // on the value axis while still pinning the `const`-fn
13518        // posture on the callee — mirror of the sibling
13519        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
13520        // (279823b) and
13521        // [`m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn`]
13522        // (29c5d7e) pins on the peer `String → &str` axes at the same
13523        // structs).
13524        //
13525        // Peer of the sibling per-`Caixa` `Option<String> →
13526        // Option<&str>` accessor family pin
13527        // [`crate::manifest::tests::caixa_option_string_scalar_accessor_family_is_const_fn`]
13528        // on the top-level manifest's optional universal-axis surface
13529        // (`:licenca` / `:repositorio` / `:descricao` / `:edicao` /
13530        // `:restart-window`).
13531        const fn wit_endpoint_via_const_fn(w: &WitContract) -> Option<&str> {
13532            w.endpoint()
13533        }
13534        const fn wit_subject_via_const_fn(w: &WitContract) -> Option<&str> {
13535            w.subject()
13536        }
13537        const fn wit_slot_via_const_fn(w: &WitContract) -> Option<&str> {
13538            w.slot()
13539        }
13540        const fn placement_shard_key_via_const_fn(p: &Placement) -> Option<&str> {
13541            p.shard_key()
13542        }
13543        const fn placement_affinity_via_const_fn(p: &Placement) -> Option<&str> {
13544            p.affinity()
13545        }
13546        // Sweep every closed shape-arm partition on the
13547        // per-`:contratos` payload-carrier trio: HTTP (`:endpoint`
13548        // Some, sibling pair None), pub-sub (`:subject` Some, sibling
13549        // pair None), key-value (`:slot` Some, sibling pair None),
13550        // and Capability (all three None) so each accessor's
13551        // Some/None arm carries a pin through the const dispatch.
13552        for (wit, endpoint, subject, slot) in [
13553            ("wasi:http/proxy", Some("/api"), None, None),
13554            ("nats:pub-sub", None, Some("orders.paid"), None),
13555            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
13556            ("custom:capability-only", None, None, None),
13557        ] {
13558            let c = WitContract {
13559                de: "cart".into(),
13560                para: "catalog".into(),
13561                wit: wit.into(),
13562                endpoint: endpoint.map(str::to_string),
13563                subject: subject.map(str::to_string),
13564                slot: slot.map(str::to_string),
13565            };
13566            assert_eq!(wit_endpoint_via_const_fn(&c), c.endpoint());
13567            assert_eq!(wit_subject_via_const_fn(&c), c.subject());
13568            assert_eq!(wit_slot_via_const_fn(&c), c.slot());
13569            assert_eq!(c.endpoint(), endpoint);
13570            assert_eq!(c.subject(), subject);
13571            assert_eq!(c.slot(), slot);
13572        }
13573        // Sweep both `Some`/`None` arms on each per-`:placement`
13574        // optional-scalar so the shard-key + affinity pair carries a
13575        // const-dispatch pin on both arms.
13576        for (shard_key, affinity) in [
13577            (Some("tenantId"), Some("data-locality")),
13578            (Some("$tenantId"), None),
13579            (None, Some("low-latency")),
13580            (None, None),
13581        ] {
13582            let p = Placement {
13583                estrategia: PlacementStrategy::default(),
13584                clusters: vec![],
13585                affinity: affinity.map(str::to_string),
13586                shard_key: shard_key.map(str::to_string),
13587            };
13588            assert_eq!(placement_shard_key_via_const_fn(&p), p.shard_key());
13589            assert_eq!(placement_affinity_via_const_fn(&p), p.affinity());
13590            assert_eq!(p.shard_key(), shard_key);
13591            assert_eq!(p.affinity(), affinity);
13592        }
13593    }
13594
13595    #[test]
13596    fn m3_placement_entrada_slice_return_accessor_pair_is_const_fn() {
13597        // Fail-before-pass-after pin on the two M3-mesh-slot inner-
13598        // composite `Vec → &[String]` slice-return accessors on
13599        // [`Placement::clusters`] and [`Entrada::paths`]. Each
13600        // destructures the typed slot's `Vec<String>` storage through
13601        // the `pub const fn` [`Vec::as_slice`] (const-stable since Rust
13602        // 1.66, well within the workspace MSRV) — any future accidental
13603        // downgrade to non-`const` fails the corresponding
13604        // `<name>_via_const_fn` wrapper at caixa-core build time with
13605        // E0015 (`cannot call non-const method`), strictly stronger
13606        // than a runtime `assert!`. Sibling of the peer
13607        // [`m3_aplicacao_spec_reference_return_accessor_family_is_const_fn`]
13608        // pin on the outer-`AplicacaoSpec` reference-return family
13609        // (`:membros` / `:contratos` slice-return + `:politicas` /
13610        // `:placement` / `:entrada` composite-reference), and of the
13611        // peer M2 slice-return axis pins
13612        // [`crate::supervisor::tests::supervisor_children_slice_return_accessor_is_const_fn`]
13613        // (on `SupervisorSpec::children`) and
13614        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
13615        // (on `UpgradeFromEntry::instructions`). Together the four
13616        // pins close the last unlifted reference-return accessor
13617        // family across the substrate primitive.
13618        const fn placement_clusters_via_const_fn(p: &Placement) -> &[String] {
13619            p.clusters()
13620        }
13621        const fn entrada_paths_via_const_fn(e: &Entrada) -> &[String] {
13622            e.paths()
13623        }
13624        // Sweep both the empty-Vec (no author-declared entries) and
13625        // the populated-Vec arms on every slice-return accessor so
13626        // each carries a const-dispatch pin on both arms.
13627        let p_empty = Placement {
13628            estrategia: PlacementStrategy::default(),
13629            clusters: vec![],
13630            affinity: None,
13631            shard_key: None,
13632        };
13633        let p_full = Placement {
13634            estrategia: PlacementStrategy::default(),
13635            clusters: vec!["prod-a".into(), "prod-b".into()],
13636            affinity: None,
13637            shard_key: None,
13638        };
13639        assert_eq!(
13640            placement_clusters_via_const_fn(&p_empty),
13641            p_empty.clusters()
13642        );
13643        assert_eq!(placement_clusters_via_const_fn(&p_full), p_full.clusters());
13644        assert!(p_empty.clusters().is_empty());
13645        assert_eq!(p_full.clusters(), &["prod-a", "prod-b"]);
13646        let e_empty = Entrada {
13647            host: "web.example.com".into(),
13648            para: "web".into(),
13649            paths: vec![],
13650            port: DEFAULT_SERVICO_PORT,
13651        };
13652        let e_full = Entrada {
13653            host: "web.example.com".into(),
13654            para: "web".into(),
13655            paths: vec!["/api".into(), "/health".into()],
13656            port: DEFAULT_SERVICO_PORT,
13657        };
13658        assert_eq!(entrada_paths_via_const_fn(&e_empty), e_empty.paths());
13659        assert_eq!(entrada_paths_via_const_fn(&e_full), e_full.paths());
13660        assert!(e_empty.paths().is_empty());
13661        assert_eq!(e_full.paths(), &["/api", "/health"]);
13662    }
13663
13664    #[test]
13665    fn m3_aplicacao_spec_reference_return_accessor_family_is_const_fn() {
13666        // Fail-before-pass-after pin on the five outer-`AplicacaoSpec`
13667        // reference-return accessors — the two `Vec → &[T]` slice-
13668        // return accessors on [`AplicacaoSpec::membros`] and
13669        // [`AplicacaoSpec::contratos`] (each routes through the
13670        // `pub const fn` [`Vec::as_slice`], const-stable since Rust
13671        // 1.66), the two `&Composite` composite-reference accessors
13672        // on [`AplicacaoSpec::politicas`] and
13673        // [`AplicacaoSpec::placement`] (each routes through a raw
13674        // `&self.<field>` borrow, trivially const), and the one
13675        // `Option<&Composite>` optional-composite-reference accessor
13676        // on [`AplicacaoSpec::entrada`] (routes through the
13677        // `pub const fn` [`Option::as_ref`], const-stable since Rust
13678        // 1.83). Any future accidental downgrade to non-`const` fails
13679        // the corresponding `<name>_via_const_fn` wrapper at caixa-
13680        // core build time with E0015 (`cannot call non-const
13681        // method`), strictly stronger than a runtime `assert!`.
13682        // Sibling of the peer inner-composite pin
13683        // [`m3_placement_entrada_slice_return_accessor_pair_is_const_fn`]
13684        // on the `Placement::clusters` + `Entrada::paths` slice-
13685        // return pair, and of the peer M2 axis pins on
13686        // [`crate::supervisor::SupervisorSpec::children`] and
13687        // [`crate::upgrade::UpgradeFromEntry::instructions`].
13688        const fn aplicacao_membros_via_const_fn(s: &AplicacaoSpec) -> &[Membro] {
13689            s.membros()
13690        }
13691        const fn aplicacao_contratos_via_const_fn(s: &AplicacaoSpec) -> &[WitContract] {
13692            s.contratos()
13693        }
13694        const fn aplicacao_politicas_via_const_fn(s: &AplicacaoSpec) -> &MeshPolicy {
13695            s.politicas()
13696        }
13697        const fn aplicacao_placement_via_const_fn(s: &AplicacaoSpec) -> &Placement {
13698            s.placement()
13699        }
13700        const fn aplicacao_entrada_via_const_fn(s: &AplicacaoSpec) -> Option<&Entrada> {
13701            s.entrada()
13702        }
13703        // Construct both a minimal "no :entrada" (internal-only
13704        // mesh) and a full "with :entrada" (external-gateway)
13705        // fixture so the family pins both the `None`-arm (author-
13706        // omitted `:entrada`) and the `Some`-arm (author-declared
13707        // `:entrada`) on the optional-composite axis.
13708        let membro = Membro {
13709            caixa: "web".into(),
13710            versao: "^0.1".into(),
13711        };
13712        let entrada_full = Entrada {
13713            host: "web.example.com".into(),
13714            para: "web".into(),
13715            paths: vec!["/api".into()],
13716            port: DEFAULT_SERVICO_PORT,
13717        };
13718        let internal_only = AplicacaoSpec {
13719            membros: vec![membro.clone()],
13720            contratos: vec![],
13721            politicas: MeshPolicy::default(),
13722            placement: Placement::default(),
13723            entrada: None,
13724        };
13725        let with_entrada = AplicacaoSpec {
13726            membros: vec![membro],
13727            contratos: vec![],
13728            politicas: MeshPolicy::default(),
13729            placement: Placement::default(),
13730            entrada: Some(entrada_full),
13731        };
13732        assert_eq!(
13733            aplicacao_membros_via_const_fn(&internal_only),
13734            internal_only.membros()
13735        );
13736        assert_eq!(
13737            aplicacao_membros_via_const_fn(&with_entrada),
13738            with_entrada.membros()
13739        );
13740        assert_eq!(
13741            aplicacao_contratos_via_const_fn(&internal_only),
13742            internal_only.contratos()
13743        );
13744        assert!(std::ptr::eq(
13745            aplicacao_politicas_via_const_fn(&internal_only),
13746            internal_only.politicas(),
13747        ));
13748        assert!(std::ptr::eq(
13749            aplicacao_placement_via_const_fn(&internal_only),
13750            internal_only.placement(),
13751        ));
13752        assert!(aplicacao_entrada_via_const_fn(&internal_only).is_none());
13753        match (
13754            aplicacao_entrada_via_const_fn(&with_entrada),
13755            with_entrada.entrada(),
13756        ) {
13757            (Some(a), Some(b)) => assert!(std::ptr::eq(a, b)),
13758            _ => panic!(
13759                "aplicacao_entrada_via_const_fn must agree with \
13760                 AplicacaoSpec::entrada on the Some-arm reference"
13761            ),
13762        }
13763    }
13764
13765    #[test]
13766    fn target_projected_returns_byte_equal_typed_view_across_all_four_arms() {
13767        // Load-bearing contract pin: on every canonical
13768        // `(:wit, :endpoint/:subject/:slot)` shape the substrate admits,
13769        // [`WitContract::target_projected`] returns byte-equal to
13770        // [`WitContract::target`]`().unwrap()` — the post-validation
13771        // projection accessor is a thin panicking wrapper over the
13772        // pre-validation validator, no extra work in the projection
13773        // path. Any future divergence (a validator-side normalization
13774        // the projection doesn't route through, an accessor-side
13775        // caching layer the validator doesn't populate) would surface
13776        // here at caixa-core build time rather than a silent per-consumer
13777        // split at renderer emit time. Sweeps the closed 4-arm
13778        // [`WitTarget`] partition ([`WitTarget::Http`] /
13779        // [`WitTarget::PubSub`] / [`WitTarget::Store`] /
13780        // [`WitTarget::Capability`]) so every arm carries a byte-equality
13781        // pin on the two-accessor pair.
13782        for (wit, endpoint, subject, slot) in [
13783            ("wasi:http/proxy", Some("/x"), None, None),
13784            ("nats:pub-sub", None, Some("events.x"), None),
13785            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
13786            ("custom:capability-only", None, None, None),
13787        ] {
13788            let c = WitContract {
13789                de: "cart".into(),
13790                para: "catalog".into(),
13791                wit: wit.into(),
13792                endpoint: endpoint.map(str::to_string),
13793                subject: subject.map(str::to_string),
13794                slot: slot.map(str::to_string),
13795            };
13796            assert_eq!(
13797                c.target_projected(),
13798                c.target().unwrap(),
13799                "target_projected must return byte-equal to target().unwrap() at wit={wit:?}"
13800            );
13801        }
13802    }
13803
13804    #[test]
13805    #[should_panic(expected = "validated by typed_view")]
13806    fn target_projected_panics_with_canonical_message_on_unvalidated_contract() {
13807        // Panic-path pin: [`WitContract::target_projected`] threads the
13808        // canonical [`WitContract::PROJECTED_INVARIANT_MSG`] byte-string
13809        // through its expect-panic when called on a contract whose
13810        // (`:wit`, payload) shape has not been crossed by
13811        // [`AplicacaoSpec::validate`] — a contract with a structurally-
13812        // invalid `:wit` (hyphen-for-colon typo) that would surface
13813        // [`AplicacaoError::ContratoWitInvalid`] at the validator gate.
13814        // A future rebrand on the panic-message axis would land at one
13815        // caixa-core edit on [`WitContract::PROJECTED_INVARIANT_MSG`]
13816        // and this pin's [`should_panic(expected = …)`] literal would
13817        // migrate alongside — the pin catches drift between the const
13818        // and the accessor's `expect(…)` call by construction.
13819        let c = WitContract {
13820            de: "cart".into(),
13821            para: "catalog".into(),
13822            // Hyphen-for-colon typo: `WitContract::target` returns
13823            // [`AplicacaoError::ContratoWitInvalid`] on this shape,
13824            // driving the [`WitContract::target_projected`] expect-panic.
13825            wit: "wasi-http/proxy".into(),
13826            endpoint: Some("/x".into()),
13827            subject: None,
13828            slot: None,
13829        };
13830        let _ = c.target_projected();
13831    }
13832
13833    #[test]
13834    fn target_projected_invariant_msg_matches_prior_inline_call_site_literal() {
13835        // Byte-equivalence pin: [`WitContract::PROJECTED_INVARIANT_MSG`]
13836        // carries the exact byte-string the two prior open-coded
13837        // `.target().expect("validated by typed_view")` production
13838        // consumers threaded through inline before this lift converged
13839        // them onto [`WitContract::target_projected`] — the caixa-mesh
13840        // per-`(:de, :para)` CNP L7 introspection branch at
13841        // `caixa-mesh/src/lib.rs:2825` and the caixa-feira `feira app
13842        // graph` per-`:contratos` payload-column printer at
13843        // `caixa-feira/src/cmd/app.rs:110`. Locks the panic-message
13844        // byte-string load-bearing so a well-meaning const-side rebrand
13845        // that didn't carry a matched pin migration would surface here
13846        // at caixa-core build time rather than a silent per-consumer
13847        // panic-message drift at cluster-apply time. Peer of the
13848        // sibling [`WitTarget::CAPABILITY_LABEL`] /
13849        // [`WitTarget::CAPABILITY_EXPECTED`] /
13850        // [`WitTarget::CAPABILITY_GRAPH_LABEL`] byte-equivalence pins on
13851        // the paired payload-less-arm scalar-const family.
13852        assert_eq!(
13853            WitContract::PROJECTED_INVARIANT_MSG,
13854            "validated by typed_view"
13855        );
13856    }
13857
13858    #[test]
13859    fn empty_wit_takes_precedence_over_invalid() {
13860        // Ordering pin: `EmptyWit` is the more self-locating
13861        // diagnostic on `""` and must lead — the value-shape gate is
13862        // only reached after the empty-check fires. Mirrors
13863        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
13864        // the peer payload axis.
13865        let mut s = three_member_spec();
13866        s.contratos.push(WitContract {
13867            de: "payment".into(),
13868            para: "catalog".into(),
13869            wit: String::new(),
13870            endpoint: None,
13871            subject: None,
13872            slot: None,
13873        });
13874        let err = s.validate().unwrap_err();
13875        assert!(
13876            matches!(err, AplicacaoError::EmptyWit { .. }),
13877            "got {err:?}"
13878        );
13879    }
13880
13881    #[test]
13882    fn wit_invalid_fires_before_payload_shape_arm() {
13883        // Ordering pin: a malformed `:wit` surfaces *its own*
13884        // diagnostic (which names the offending wit verbatim) before
13885        // any payload-field check — a contrato whose wit is
13886        // structurally invalid AND carries a wrong target field
13887        // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
13888        // because the dispatch on the wit is what decides which
13889        // payload field is "right" in the first place. Without this
13890        // ordering, the author would see "wrong target field" for a
13891        // wit that hasn't even been parsed, which doesn't name the
13892        // root cause.
13893        let mut s = three_member_spec();
13894        s.contratos.push(WitContract {
13895            de: "payment".into(),
13896            para: "catalog".into(),
13897            // Hyphen-for-colon typo + endpoint set: pre-gate this
13898            // raised `ContratoWrongTarget { expected: "none" }` (the
13899            // Capability arm rejecting the endpoint), masking the
13900            // real authoring mistake (the wit isn't `wasi:http/proxy`).
13901            wit: "wasi-http/proxy".into(),
13902            endpoint: Some("/x".into()),
13903            subject: None,
13904            slot: None,
13905        });
13906        let err = s.validate().unwrap_err();
13907        assert!(
13908            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
13909                if wit == "wasi-http/proxy"),
13910            "got {err:?}"
13911        );
13912    }
13913
13914    #[test]
13915    fn wit_invalid_diagnostic_carries_offending_wit() {
13916        // Diagnostic-shape pin — the offending `:wit` + `:de` +
13917        // `:para` + a non-empty reason flow through verbatim so the
13918        // author can grep their caixa.lisp for the offending contrato
13919        // block and fix it in one edit. Same shape as
13920        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
13921        let err = contrato_wit_err("WASI:HTTP/proxy");
13922        match err {
13923            AplicacaoError::ContratoWitInvalid {
13924                de,
13925                para,
13926                wit,
13927                reason,
13928            } => {
13929                assert_eq!(de, "payment");
13930                assert_eq!(para, "catalog");
13931                assert_eq!(wit, "WASI:HTTP/proxy");
13932                assert!(!reason.is_empty(), "reason field must be non-empty");
13933            }
13934            other => panic!("expected ContratoWitInvalid, got {other:?}"),
13935        }
13936    }
13937
13938    // ── :contratos :subject value-shape gate ─────────────────────────────
13939    //
13940    // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
13941    // suites on the peer payload axes. Until this gate landed
13942    // `WitContract::target()` only refused the empty string; a
13943    // structurally invalid subject silently passed validate and the
13944    // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
13945    // Subject'` on publish / subscribe, or as a silent message drop,
13946    // far from the source caixa.lisp. Every authoring footgun the
13947    // NATS server's subject parser would catch on admission now
13948    // becomes a caixa-build-time `ContratoSubjectInvalid` with the
13949    // offending `:subject` + `:de` + `:para` named verbatim. Same
13950    // diagnostic shape as `ContratoEndpointInvalid` /
13951    // `ContratoWitInvalid` on the peer payload axes; same shared
13952    // predicate (`crate::render::is_nats_subject`) ensures drift
13953    // between any two axes' rule enforcement is a build error at the
13954    // predicate, not piecemeal across renderers.
13955
13956    fn contrato_subject_err(subject: &str) -> AplicacaoError {
13957        // Fresh spec per call so the new contract doesn't collide on
13958        // identity with `three_member_spec`'s pre-existing entries.
13959        // The new edge uses `(payment, catalog)` — a pair the fixture
13960        // doesn't already declare — with `:wit "nats:pub-sub"` and the
13961        // varying `:subject`, so the subject-shape gate fires cleanly
13962        // after the wit-shape gate (which `"nats:pub-sub"` passes).
13963        let mut s = three_member_spec();
13964        s.contratos.push(WitContract {
13965            de: "payment".into(),
13966            para: "catalog".into(),
13967            wit: "nats:pub-sub".into(),
13968            endpoint: None,
13969            subject: Some(subject.into()),
13970            slot: None,
13971        });
13972        s.validate().unwrap_err()
13973    }
13974
13975    #[test]
13976    fn rejects_pubsub_contrato_subject_with_whitespace() {
13977        // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
13978        // landed at the NATS server as a malformed subject the parser
13979        // rejects with `-ERR 'Invalid Subject'`. Now caught at the
13980        // source caixa.lisp.
13981        let err = contrato_subject_err("foo bar");
13982        assert!(
13983            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
13984                if subject == "foo bar" && reason.contains("whitespace")),
13985            "got {err:?}"
13986        );
13987    }
13988
13989    #[test]
13990    fn rejects_pubsub_contrato_subject_with_control_char() {
13991        let err = contrato_subject_err("foo\x01bar");
13992        assert!(
13993            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
13994                if subject == "foo\x01bar" && reason.contains("control character")),
13995            "got {err:?}"
13996        );
13997    }
13998
13999    #[test]
14000    fn rejects_pubsub_contrato_subject_with_non_ascii() {
14001        // Un-percent-encoded non-ASCII byte — the canonical "I copied
14002        // the subject from a doc with smart quotes / accented
14003        // characters" footgun.
14004        let err = contrato_subject_err("foo.caf\u{e9}");
14005        assert!(
14006            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14007                if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
14008            "got {err:?}"
14009        );
14010    }
14011
14012    #[test]
14013    fn rejects_pubsub_contrato_subject_with_leading_dot() {
14014        // Empty leading token — NATS rejects.
14015        let err = contrato_subject_err(".foo");
14016        assert!(
14017            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14018                if subject == ".foo" && reason.contains("must not start with `.`")),
14019            "got {err:?}"
14020        );
14021    }
14022
14023    #[test]
14024    fn rejects_pubsub_contrato_subject_with_trailing_dot() {
14025        // Empty trailing token — NATS rejects. The remediation
14026        // (use `>` instead) is in the reason string.
14027        let err = contrato_subject_err("foo.");
14028        assert!(
14029            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14030                if subject == "foo." && reason.contains("must not end with `.`")),
14031            "got {err:?}"
14032        );
14033    }
14034
14035    #[test]
14036    fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
14037        // The canonical "I forgot to fill in the middle segment"
14038        // typo — `"foo..bar"`. NATS rejects empty tokens.
14039        let err = contrato_subject_err("foo..bar");
14040        assert!(
14041            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14042                if subject == "foo..bar" && reason.contains("consecutive `.`")),
14043            "got {err:?}"
14044        );
14045    }
14046
14047    #[test]
14048    fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
14049        // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
14050        // as the final segment. Pre-gate this passed as a typed edge
14051        // and surfaced at runtime as a NATS subscribe rejection.
14052        let err = contrato_subject_err("foo.>.bar");
14053        assert!(
14054            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14055                if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
14056            "got {err:?}"
14057        );
14058    }
14059
14060    #[test]
14061    fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
14062        // `foo*.bar` — NATS wildcards are standalone tokens. The
14063        // remediation is in the reason string.
14064        let err = contrato_subject_err("foo*.bar");
14065        assert!(
14066            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14067                if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
14068            "got {err:?}"
14069        );
14070    }
14071
14072    #[test]
14073    fn rejects_pubsub_contrato_subject_with_invalid_char() {
14074        // `foo,bar` — comma is not a valid NATS subject character.
14075        // Pinned separately from the wildcard arms so the invalid-
14076        // character diagnostic is in force.
14077        let err = contrato_subject_err("foo,bar");
14078        assert!(
14079            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14080                if subject == "foo,bar" && reason.contains("invalid character")),
14081            "got {err:?}"
14082        );
14083    }
14084
14085    #[test]
14086    fn rejects_pubsub_contrato_subject_too_long() {
14087        // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
14088        // The legitimate-shape arms all pass (one all-`a` token, no
14089        // `.`, no wildcards); only the cap arm fires. Surfaces the
14090        // paste-from-binary / accidental-multi-line-blob landing
14091        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
14092        // on the peer axis.
14093        let big = "a".repeat(257);
14094        assert_eq!(big.len(), 257);
14095        let err = contrato_subject_err(&big);
14096        assert!(
14097            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14098                if subject == &big && reason.contains("max length of 256")),
14099            "got {err:?}"
14100        );
14101    }
14102
14103    #[test]
14104    fn pubsub_contrato_subject_max_length_validates() {
14105        // 256-byte subject — exactly the cap. Boundary pin: drift in
14106        // the cap surfaces here and at
14107        // `rejects_pubsub_contrato_subject_too_long` simultaneously,
14108        // mirroring `http_contrato_endpoint_max_length_validates` and
14109        // `wit_max_length_validates` on the peer axes.
14110        let big = "a".repeat(256);
14111        assert_eq!(big.len(), 256);
14112        let mut s = three_member_spec();
14113        s.contratos.push(WitContract {
14114            de: "payment".into(),
14115            para: "catalog".into(),
14116            wit: "nats:pub-sub".into(),
14117            endpoint: None,
14118            subject: Some(big),
14119            slot: None,
14120        });
14121        s.validate().unwrap();
14122    }
14123
14124    #[test]
14125    fn pubsub_contrato_subject_accepts_canonical_forms() {
14126        // Positive-set sweep: every canonical NATS subject shape the
14127        // substrate-side `is_nats_subject` predicate accepts (the
14128        // multi-dot `events.order.charged`, the snake_case / kebab-
14129        // case / mixed-case tokens, the digit-bearing tokens, the
14130        // single-token wildcard `*` at every segment position, and
14131        // the trailing `>` multi-token wildcard) must remain a valid
14132        // contrato subject too. Drift between this list and the
14133        // substrate-side `nats_subject_accepts_canonical_forms` sweep
14134        // surfaces at the shared predicate — one source of truth.
14135        // Uses a fresh `(payment, catalog)` edge so none of the swept
14136        // subjects collide with the pre-existing entries in
14137        // `three_member_spec`.
14138        for subject in [
14139            "checkout.events.charge.failed",
14140            "rio.events.order.charged",
14141            "orders",
14142            "orders.123",
14143            "snake_case.token",
14144            "kebab-case.token",
14145            "MixedCase.Token",
14146            "orders.*.charged",
14147            "*.events.*",
14148            "orders.>",
14149        ] {
14150            let mut s = three_member_spec();
14151            s.contratos.push(WitContract {
14152                de: "payment".into(),
14153                para: "catalog".into(),
14154                wit: "nats:pub-sub".into(),
14155                endpoint: None,
14156                subject: Some(subject.into()),
14157                slot: None,
14158            });
14159            s.validate()
14160                .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
14161        }
14162    }
14163
14164    #[test]
14165    fn contrato_subject_empty_takes_precedence_over_invalid() {
14166        // Ordering pin: `ContratoSubjectEmpty` is the more self-
14167        // locating diagnostic on `""` and must lead — the value-shape
14168        // gate is only reached after the empty-check fires. Mirrors
14169        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
14170        // the peer payload axis.
14171        let mut s = three_member_spec();
14172        s.contratos.push(WitContract {
14173            de: "payment".into(),
14174            para: "catalog".into(),
14175            wit: "nats:pub-sub".into(),
14176            endpoint: None,
14177            subject: Some(String::new()),
14178            slot: None,
14179        });
14180        let err = s.validate().unwrap_err();
14181        assert!(
14182            matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
14183            "got {err:?}"
14184        );
14185    }
14186
14187    #[test]
14188    fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
14189        // Diagnostic-shape pin — the offending `:subject` + `:de` +
14190        // `:para` + a non-empty reason flow through verbatim so the
14191        // author can grep their caixa.lisp for the offending contrato
14192        // block and fix it in one edit. Same shape as
14193        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
14194        // and `wit_invalid_diagnostic_carries_offending_wit`.
14195        let err = contrato_subject_err("foo..bar");
14196        match err {
14197            AplicacaoError::ContratoSubjectInvalid {
14198                de,
14199                para,
14200                subject,
14201                reason,
14202            } => {
14203                assert_eq!(de, "payment");
14204                assert_eq!(para, "catalog");
14205                assert_eq!(subject, "foo..bar");
14206                assert!(!reason.is_empty(), "reason field must be non-empty");
14207            }
14208            other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
14209        }
14210    }
14211
14212    #[test]
14213    fn target_view_pubsub_subject_passes_through_to_typed_view() {
14214        // The compounding theorem on the pub-sub axis: every
14215        // `WitTarget::PubSub { subject }` returned by `target()` carries
14216        // a NATS-server-accepted subject. Renderers downstream of
14217        // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
14218        // NATS Stream/Consumer CR emitter, the future `feira app graph`
14219        // view's subject labeller) can rely on this without re-checking
14220        // — the type system carries the proof. Mirrors
14221        // `target_view_payload_is_guaranteed_nonempty_after_target_call`
14222        // on the peer axes.
14223        let nats = WitContract {
14224            de: "a".into(),
14225            para: "b".into(),
14226            wit: "nats:pub-sub".into(),
14227            endpoint: None,
14228            subject: Some("orders.events.*.charged".into()),
14229            slot: None,
14230        };
14231        match nats.target().unwrap() {
14232            WitTarget::PubSub { subject } => {
14233                assert_eq!(subject, "orders.events.*.charged");
14234            }
14235            other => panic!("expected PubSub, got {other:?}"),
14236        }
14237    }
14238
14239    // ── :contratos :slot value-shape gate ────────────────────────────────
14240    //
14241    // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
14242    // (63e18a0) value-shape suites on the peer payload axes. Until this
14243    // gate landed `WitContract::target()` only refused the empty string
14244    // for the Store arm; a structurally invalid slot (raw whitespace,
14245    // control character, non-ASCII byte, paste-from-binary multi-line
14246    // blob) silently passed validate and surfaced at runtime as a
14247    // per-backend kv write rejection or a silent next-read corruption,
14248    // far from the source caixa.lisp with no field naming which
14249    // `:contratos` edge carried the typo. Every authoring footgun the
14250    // kv backend intersection-floor would catch on write now becomes a
14251    // caixa-build-time `ContratoSlotInvalid` with the offending
14252    // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
14253    // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
14254    // peer payload axes; same shared predicate
14255    // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
14256    // any two axes' rule enforcement is a build error at the
14257    // predicate, not piecemeal across renderers. Closes the typed
14258    // payload-axis value-shape trajectory across all three legs of the
14259    // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
14260
14261    fn contrato_slot_err(slot: &str) -> AplicacaoError {
14262        // Fresh spec per call so the new contract doesn't collide on
14263        // identity with `three_member_spec`'s pre-existing entries
14264        // and doesn't close a synchronous cycle the cycle detector
14265        // would reject before the slot-shape gate fires. The new edge
14266        // uses `(payment, catalog)` — a pair the fixture doesn't
14267        // already declare in either direction (the fixture carries
14268        // `cart -> catalog` and `cart -> payment`, so `payment ->
14269        // catalog` doesn't form a cycle on the sync subgraph) — with
14270        // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
14271        // slot-shape gate fires cleanly after the wit-shape gate
14272        // (which `"wasi:keyvalue/store"` passes). Same edge pair the
14273        // peer `contrato_subject_err` helper uses (63e18a0).
14274        let mut s = three_member_spec();
14275        s.contratos.push(WitContract {
14276            de: "payment".into(),
14277            para: "catalog".into(),
14278            wit: "wasi:keyvalue/store".into(),
14279            endpoint: None,
14280            subject: None,
14281            slot: Some(slot.into()),
14282        });
14283        s.validate().unwrap_err()
14284    }
14285
14286    #[test]
14287    fn rejects_store_contrato_slot_with_whitespace() {
14288        // Fail-before-pass-after pin — pre-gate `"check out/$order"`
14289        // silently landed at the kv backend with whitespace whose
14290        // runtime behavior varies unpredictably across backends (etcd
14291        // accepts, Redis accepts then breaks on next CLI op, DynamoDB
14292        // rejects on write). Now caught at the source caixa.lisp.
14293        let err = contrato_slot_err("check out/$order");
14294        assert!(
14295            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
14296                if slot == "check out/$order" && reason.contains("whitespace")),
14297            "got {err:?}"
14298        );
14299    }
14300
14301    #[test]
14302    fn rejects_store_contrato_slot_with_tab() {
14303        // Tab byte arm-pinned separately from the space arm so a
14304        // future relaxation that admits one but not the other surfaces
14305        // here.
14306        let err = contrato_slot_err("check\tout");
14307        assert!(
14308            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
14309                if slot == "check\tout" && reason.contains("whitespace")),
14310            "got {err:?}"
14311        );
14312    }
14313
14314    #[test]
14315    fn rejects_store_contrato_slot_with_control_char() {
14316        // SOH (0x01) — distinct from the whitespace arm. Redis admits
14317        // and corrupts on RESP protocol framing; DynamoDB rejects on
14318        // write.
14319        let err = contrato_slot_err("checkout/\x01order");
14320        assert!(
14321            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
14322                if slot == "checkout/\x01order" && reason.contains("control character")),
14323            "got {err:?}"
14324        );
14325    }
14326
14327    #[test]
14328    fn rejects_store_contrato_slot_with_newline() {
14329        // Embedded newline — the canonical "the paste-from-binary slug
14330        // spans multiple lines" footgun. Distinct from the whitespace
14331        // arm because `\n` is a control character (0x0A).
14332        let err = contrato_slot_err("checkout\norder");
14333        assert!(
14334            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
14335                if slot == "checkout\norder" && reason.contains("control character")),
14336            "got {err:?}"
14337        );
14338    }
14339
14340    #[test]
14341    fn rejects_store_contrato_slot_with_non_ascii() {
14342        // Un-percent-encoded non-ASCII byte — the canonical "I copied
14343        // the slot from a doc with accented characters" footgun. Each
14344        // kv backend re-encodes non-ASCII differently (etcd preserves
14345        // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
14346        // rejects), so the typed slot's value set is the intersection-
14347        // floor every backend admits identically (printable ASCII).
14348        let err = contrato_slot_err("ch\u{e9}ckout/$order");
14349        assert!(
14350            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
14351                if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
14352            "got {err:?}"
14353        );
14354    }
14355
14356    #[test]
14357    fn rejects_store_contrato_slot_too_long() {
14358        // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
14359        // legitimate-shape arms all pass (a single all-`a` token, no
14360        // separators); only the cap arm fires. Surfaces the paste-
14361        // from-binary / accidental-multi-line-blob landing footgun.
14362        // Mirrors `rejects_pubsub_contrato_subject_too_long` and
14363        // `rejects_http_contrato_endpoint_too_long` on the peer
14364        // payload axes.
14365        let big = "a".repeat(513);
14366        assert_eq!(big.len(), 513);
14367        let err = contrato_slot_err(&big);
14368        assert!(
14369            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
14370                if slot == &big && reason.contains("max length of 512")),
14371            "got {err:?}"
14372        );
14373    }
14374
14375    #[test]
14376    fn store_contrato_slot_max_length_validates() {
14377        // 512-byte slot — exactly the cap. Boundary pin: drift in the
14378        // cap surfaces here and at `rejects_store_contrato_slot_too_long`
14379        // simultaneously, mirroring
14380        // `pubsub_contrato_subject_max_length_validates` and
14381        // `http_contrato_endpoint_max_length_validates` on the peer
14382        // payload axes.
14383        let big = "a".repeat(512);
14384        assert_eq!(big.len(), 512);
14385        let mut s = three_member_spec();
14386        s.contratos.push(WitContract {
14387            de: "payment".into(),
14388            para: "catalog".into(),
14389            wit: "wasi:keyvalue/store".into(),
14390            endpoint: None,
14391            subject: None,
14392            slot: Some(big),
14393        });
14394        s.validate().unwrap();
14395    }
14396
14397    #[test]
14398    fn store_contrato_slot_accepts_canonical_forms() {
14399        // Positive-set sweep: every canonical kv slot template the
14400        // substrate-side `is_wasi_keyvalue_slot` predicate accepts
14401        // (single-token identifiers, path-namespaced `$`-templates,
14402        // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
14403        // snake_case / kebab-case / MixedCase tokens, digit-bearing
14404        // tokens, percent-encoded fragments) must remain valid
14405        // contrato slots too. Drift between this list and the
14406        // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
14407        // surfaces at the shared predicate — one source of truth.
14408        // Uses a fresh `(payment, catalog)` edge so none of the swept
14409        // slots collide with the pre-existing entries in
14410        // `three_member_spec`.
14411        for slot in [
14412            "checkout",
14413            "checkout/$orderId",
14414            "users:{tenant}/{id}",
14415            "session.<sid>",
14416            "session.tokens.<sid>",
14417            "snake_case_key",
14418            "kebab-case-key",
14419            "MixedCase",
14420            "shard0",
14421            "v2/key",
14422            "users/caf%C3%A9",
14423        ] {
14424            let mut s = three_member_spec();
14425            s.contratos.push(WitContract {
14426                de: "payment".into(),
14427                para: "catalog".into(),
14428                wit: "wasi:keyvalue/store".into(),
14429                endpoint: None,
14430                subject: None,
14431                slot: Some(slot.into()),
14432            });
14433            s.validate()
14434                .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
14435        }
14436    }
14437
14438    #[test]
14439    fn contrato_slot_empty_takes_precedence_over_invalid() {
14440        // Ordering pin: `ContratoSlotEmpty` is the more self-locating
14441        // diagnostic on `""` and must lead — the value-shape gate is
14442        // only reached after the empty-check fires. Mirrors
14443        // `contrato_subject_empty_takes_precedence_over_invalid` and
14444        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
14445        // the peer payload axes.
14446        let mut s = three_member_spec();
14447        s.contratos.push(WitContract {
14448            de: "payment".into(),
14449            para: "catalog".into(),
14450            wit: "wasi:keyvalue/store".into(),
14451            endpoint: None,
14452            subject: None,
14453            slot: Some(String::new()),
14454        });
14455        let err = s.validate().unwrap_err();
14456        assert!(
14457            matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
14458            "got {err:?}"
14459        );
14460    }
14461
14462    #[test]
14463    fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
14464        // Diagnostic-shape pin — the offending `:slot` + `:de` +
14465        // `:para` + a non-empty reason flow through verbatim so the
14466        // author can grep their caixa.lisp for the offending contrato
14467        // block and fix it in one edit. Same shape as
14468        // `contrato_subject_invalid_diagnostic_carries_offending_subject`
14469        // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
14470        // on the peer payload axes.
14471        let err = contrato_slot_err("check out/$order");
14472        match err {
14473            AplicacaoError::ContratoSlotInvalid {
14474                de,
14475                para,
14476                slot,
14477                reason,
14478            } => {
14479                assert_eq!(de, "payment");
14480                assert_eq!(para, "catalog");
14481                assert_eq!(slot, "check out/$order");
14482                assert!(!reason.is_empty(), "reason field must be non-empty");
14483            }
14484            other => panic!("expected ContratoSlotInvalid, got {other:?}"),
14485        }
14486    }
14487
14488    #[test]
14489    fn target_view_store_slot_passes_through_to_typed_view() {
14490        // The compounding theorem on the store axis: every
14491        // `WitTarget::Store { slot }` returned by `target()` carries a
14492        // kv-backend-accepted slot template. Renderers downstream of
14493        // `typed_view()` (the future per-Servico `:capabilities
14494        // wasi:keyvalue/store` axis emitter, the future `feira app
14495        // graph` view's slot labeller, the future kv-provider CR
14496        // materializer) can rely on this without re-checking — the
14497        // type system carries the proof. Mirrors
14498        // `target_view_pubsub_subject_passes_through_to_typed_view` on
14499        // the peer payload axis.
14500        let store = WitContract {
14501            de: "a".into(),
14502            para: "b".into(),
14503            wit: "wasi:keyvalue/store".into(),
14504            endpoint: None,
14505            subject: None,
14506            slot: Some("checkout/$orderId".into()),
14507        };
14508        match store.target().unwrap() {
14509            WitTarget::Store { slot } => {
14510                assert_eq!(slot, "checkout/$orderId");
14511            }
14512            other => panic!("expected Store, got {other:?}"),
14513        }
14514    }
14515
14516    #[test]
14517    fn rejects_self_loop_in_synchronous_contratos() {
14518        // A synchronous self-edge (`cart → cart` over HTTP) is now
14519        // rejected by the dedicated `ContratoSelfLoop` gate — a precise
14520        // "this edge is degenerate" diagnostic — rather than incidentally
14521        // by the cycle detector framing it as a `["cart", "cart"]`
14522        // multi-node deadlock.
14523        let mut s = three_member_spec();
14524        s.contratos.push(contract_http("cart", "cart", "/loop"));
14525        let err = s.validate().unwrap_err();
14526        match err {
14527            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
14528                assert_eq!(caixa, "cart");
14529                assert_eq!(wit, "wasi:http/proxy");
14530            }
14531            other => panic!("expected ContratoSelfLoop, got {other:?}"),
14532        }
14533    }
14534
14535    #[test]
14536    fn rejects_self_loop_in_pubsub_contratos() {
14537        // The cycle detector excludes pub-sub edges (acyclic by
14538        // construction), so before the explicit gate a `nats:pub-sub`
14539        // self-edge silently validated and rendered a self-allow CNP.
14540        // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
14541        let mut s = three_member_spec();
14542        s.contratos.push(WitContract {
14543            de: "payment".into(),
14544            para: "payment".into(),
14545            wit: "nats:pub-sub".into(),
14546            endpoint: None,
14547            subject: Some("rio.events.payment".into()),
14548            slot: None,
14549        });
14550        let err = s.validate().unwrap_err();
14551        match err {
14552            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
14553                assert_eq!(caixa, "payment");
14554                assert_eq!(wit, "nats:pub-sub");
14555            }
14556            other => panic!("expected ContratoSelfLoop, got {other:?}"),
14557        }
14558    }
14559
14560    #[test]
14561    fn self_loop_fires_before_payload_shape_check() {
14562        // The structural "this edge can't exist" error precedes the
14563        // narrower payload-shape diagnostics: a self-edge carrying an
14564        // otherwise-malformed endpoint still reports ContratoSelfLoop,
14565        // not ContratoEndpointInvalid.
14566        let mut s = three_member_spec();
14567        s.contratos.push(WitContract {
14568            de: "cart".into(),
14569            para: "cart".into(),
14570            wit: "wasi:http/proxy".into(),
14571            endpoint: Some("not-absolute".into()),
14572            subject: None,
14573            slot: None,
14574        });
14575        match s.validate().unwrap_err() {
14576            AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
14577            other => panic!("expected ContratoSelfLoop, got {other:?}"),
14578        }
14579    }
14580
14581    #[test]
14582    fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
14583        // A self-edge naming a non-member reports the more fundamental
14584        // ContratoMemberMissing first (the member doesn't exist), so the
14585        // self-loop gate is reached only once both endpoints resolve.
14586        let mut s = three_member_spec();
14587        s.contratos.push(contract_http("ghost", "ghost", "/loop"));
14588        match s.validate().unwrap_err() {
14589            AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
14590            other => panic!("expected ContratoMemberMissing, got {other:?}"),
14591        }
14592    }
14593
14594    #[test]
14595    fn rejects_two_node_synchronous_cycle() {
14596        let mut s = three_member_spec();
14597        // existing edges: cart → catalog, cart → payment
14598        // adding catalog → cart closes a 2-cycle on the HTTP subgraph
14599        s.contratos
14600            .push(contract_http("catalog", "cart", "/refresh"));
14601        let err = s.validate().unwrap_err();
14602        match err {
14603            AplicacaoError::ContratoCycle { cycle } => {
14604                // Cycle traversal should mention both endpoints, with
14605                // the back-edge target appearing as both first and last
14606                // element to close the loop.
14607                assert!(cycle.len() >= 3);
14608                assert_eq!(cycle.first(), cycle.last());
14609                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
14610                assert!(body.contains("cart"));
14611                assert!(body.contains("catalog"));
14612            }
14613            other => panic!("expected ContratoCycle, got {other:?}"),
14614        }
14615    }
14616
14617    #[test]
14618    fn rejects_three_node_synchronous_cycle() {
14619        let mut s = three_member_spec();
14620        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
14621        s.contratos = vec![
14622            contract_http("catalog", "cart", "/x"),
14623            contract_http("cart", "payment", "/y"),
14624            contract_http("payment", "catalog", "/z"),
14625        ];
14626        let err = s.validate().unwrap_err();
14627        match err {
14628            AplicacaoError::ContratoCycle { cycle } => {
14629                assert_eq!(cycle.first(), cycle.last());
14630                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
14631                assert_eq!(body.len(), 3);
14632                assert!(body.contains("cart"));
14633                assert!(body.contains("catalog"));
14634                assert!(body.contains("payment"));
14635            }
14636            other => panic!("expected ContratoCycle, got {other:?}"),
14637        }
14638    }
14639
14640    #[test]
14641    fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
14642        // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
14643        // "acyclic by construction" — so a cycle whose closing edge
14644        // is pub-sub should NOT raise ContratoCycle.
14645        let mut s = three_member_spec();
14646        s.contratos = vec![
14647            contract_http("catalog", "cart", "/x"),
14648            contract_http("cart", "payment", "/y"),
14649            // Closing edge is pub-sub — async; not a sync deadlock.
14650            WitContract {
14651                de: "payment".into(),
14652                para: "catalog".into(),
14653                wit: "nats:pub-sub".into(),
14654                endpoint: None,
14655                subject: Some("checkout.events.charge.completed".into()),
14656                slot: None,
14657            },
14658        ];
14659        s.validate().expect("pub-sub edge breaks the sync cycle");
14660    }
14661
14662    #[test]
14663    fn store_edge_counts_as_synchronous_for_cycle_detection() {
14664        // wasi:keyvalue/store is request/response; a cycle through one
14665        // *is* a sync deadlock, just like HTTP.
14666        let mut s = three_member_spec();
14667        s.contratos = vec![
14668            contract_http("catalog", "cart", "/x"),
14669            WitContract {
14670                de: "cart".into(),
14671                para: "catalog".into(),
14672                wit: "wasi:keyvalue/store".into(),
14673                endpoint: None,
14674                subject: None,
14675                slot: Some("session/$id".into()),
14676            },
14677        ];
14678        let err = s.validate().unwrap_err();
14679        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
14680    }
14681
14682    #[test]
14683    fn capability_edge_counts_as_synchronous_for_cycle_detection() {
14684        // Capability-only edges (unknown WIT shape, no payload) default
14685        // to synchronous — safer; authors with truly async capability
14686        // semantics can model them as pub-sub explicitly.
14687        let mut s = three_member_spec();
14688        s.contratos = vec![
14689            contract_http("catalog", "cart", "/x"),
14690            WitContract {
14691                de: "cart".into(),
14692                para: "catalog".into(),
14693                wit: "custom:exchange".into(),
14694                endpoint: None,
14695                subject: None,
14696                slot: None,
14697            },
14698        ];
14699        let err = s.validate().unwrap_err();
14700        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
14701    }
14702
14703    #[test]
14704    fn long_acyclic_chain_validates() {
14705        // A long sync chain (no back-edges) must validate even when
14706        // every node is reachable from the first.
14707        let mut s = three_member_spec();
14708        s.membros = vec![
14709            membro("a", "^0.1"),
14710            membro("b", "^0.1"),
14711            membro("c", "^0.1"),
14712            membro("d", "^0.1"),
14713            membro("e", "^0.1"),
14714        ];
14715        s.contratos = vec![
14716            contract_http("a", "b", "/1"),
14717            contract_http("b", "c", "/2"),
14718            contract_http("c", "d", "/3"),
14719            contract_http("d", "e", "/4"),
14720        ];
14721        s.entrada.as_mut().unwrap().para = "a".into();
14722        s.validate().unwrap();
14723    }
14724
14725    #[test]
14726    fn diamond_acyclic_validates() {
14727        // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
14728        let mut s = three_member_spec();
14729        s.membros = vec![
14730            membro("a", "^0.1"),
14731            membro("b", "^0.1"),
14732            membro("c", "^0.1"),
14733            membro("d", "^0.1"),
14734        ];
14735        s.contratos = vec![
14736            contract_http("a", "b", "/1"),
14737            contract_http("a", "c", "/2"),
14738            contract_http("b", "d", "/3"),
14739            contract_http("c", "d", "/4"),
14740        ];
14741        s.entrada.as_mut().unwrap().para = "a".into();
14742        s.validate().unwrap();
14743    }
14744
14745    // ── duplicate-`:contratos` build-error gate ──────────────────────────
14746
14747    #[test]
14748    fn rejects_duplicate_http_contrato() {
14749        // Fail-before-pass-after pin: the fixture's `cart → catalog`
14750        // HTTP edge appears once. Push an identical entry — same
14751        // (de, para, wit, endpoint) — and validate() must reject it.
14752        // Until this gate landed the typed surface accepted the
14753        // duplicate silently and caixa-mesh's `cilium_network_policies`
14754        // emitted two ``CiliumNetworkPolicy`` objects with identical
14755        // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
14756        // admission rejects on `kubectl apply` far from the source.
14757        let mut s = three_member_spec();
14758        s.contratos
14759            .push(contract_http("cart", "catalog", "/products/:id"));
14760        let err = s.validate().unwrap_err();
14761        assert!(
14762            matches!(
14763                err,
14764                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
14765                    if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
14766            ),
14767            "got {err:?}"
14768        );
14769    }
14770
14771    #[test]
14772    fn rejects_duplicate_pubsub_contrato() {
14773        // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
14774        // edges with identical (de, para, subject) are degenerate;
14775        // pin that the typed surface refuses both at validate time.
14776        let mut s = three_member_spec();
14777        let pubsub = WitContract {
14778            de: "payment".into(),
14779            para: "cart".into(),
14780            wit: "nats:pub-sub".into(),
14781            endpoint: None,
14782            subject: Some("checkout.events.charge.failed".into()),
14783            slot: None,
14784        };
14785        s.contratos.push(pubsub.clone());
14786        s.contratos.push(pubsub);
14787        let err = s.validate().unwrap_err();
14788        assert!(
14789            matches!(
14790                err,
14791                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
14792                    if de == "payment" && para == "cart" && wit == "nats:pub-sub"
14793            ),
14794            "got {err:?}"
14795        );
14796    }
14797
14798    #[test]
14799    fn rejects_duplicate_store_contrato() {
14800        // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
14801        // edges with identical (de, para, slot) collapse to one mesh-
14802        // policy edge; pin the build error.
14803        let mut s = three_member_spec();
14804        let store = WitContract {
14805            de: "cart".into(),
14806            para: "payment".into(),
14807            wit: "wasi:keyvalue/store".into(),
14808            endpoint: None,
14809            subject: None,
14810            slot: Some("checkout/$orderId".into()),
14811        };
14812        // Drop the conflicting HTTP `cart → payment` edge from the
14813        // fixture so the duplicate-store pair is the only one
14814        // distinguishable on this pair.
14815        s.contratos
14816            .retain(|c| !(c.de == "cart" && c.para == "payment"));
14817        s.contratos.push(store.clone());
14818        s.contratos.push(store);
14819        let err = s.validate().unwrap_err();
14820        assert!(
14821            matches!(
14822                err,
14823                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
14824                    if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
14825            ),
14826            "got {err:?}"
14827        );
14828    }
14829
14830    #[test]
14831    fn rejects_duplicate_capability_contrato() {
14832        // Same gate on the pure-capability axis (no payload selector).
14833        // Two contracts with identical (de, para, wit) and no
14834        // endpoint/subject/slot are duplicate edges; pin so a future
14835        // `target_label` change can't accidentally collapse the
14836        // capability arm into a None-shaped key that compares equal
14837        // to a populated one.
14838        let mut s = three_member_spec();
14839        let capability = WitContract {
14840            de: "cart".into(),
14841            para: "catalog".into(),
14842            wit: "pleme:cap/audit".into(),
14843            endpoint: None,
14844            subject: None,
14845            slot: None,
14846        };
14847        s.contratos.push(capability.clone());
14848        s.contratos.push(capability);
14849        let err = s.validate().unwrap_err();
14850        match err {
14851            AplicacaoError::ContratoDuplicate {
14852                de,
14853                para,
14854                wit,
14855                target,
14856            } => {
14857                assert_eq!(de, "cart");
14858                assert_eq!(para, "catalog");
14859                assert_eq!(wit, "pleme:cap/audit");
14860                assert!(
14861                    target.contains("capability"),
14862                    "capability-edge duplicate diagnostic must surface the \
14863                     no-payload shape (got target = {target:?})"
14864                );
14865            }
14866            other => panic!("expected ContratoDuplicate, got {other:?}"),
14867        }
14868    }
14869
14870    #[test]
14871    fn accepts_distinct_http_paths_between_same_pair() {
14872        // Negative pin: two HTTP contracts cart → catalog at distinct
14873        // endpoints (`/products/:id` and `/search`) are *not*
14874        // duplicates — they're distinct typed edges differing on the
14875        // payload axis. The duplicate-gate must not over-match here,
14876        // since the cart-calls-catalog-on-multiple-paths shape is the
14877        // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
14878        // example: cart calls catalog at /products/:id, payment at
14879        // /charge — same shape extends to two paths on one para).
14880        let mut s = three_member_spec();
14881        s.contratos
14882            .push(contract_http("cart", "catalog", "/search"));
14883        s.validate()
14884            .expect("distinct endpoints between same (de, para) must validate");
14885    }
14886
14887    #[test]
14888    fn accepts_same_endpoint_on_different_pairs() {
14889        // Negative pin: the same `/charge` endpoint reused on two
14890        // different (de, para) pairs is two distinct edges, not a
14891        // duplicate. Pinning this shape so the gate's identity key
14892        // includes both `de` and `para` (not just `(wit, endpoint)`).
14893        let mut s = three_member_spec();
14894        s.contratos
14895            .push(contract_http("payment", "catalog", "/charge"));
14896        s.validate()
14897            .expect("same endpoint reused on distinct (de, para) must validate");
14898    }
14899
14900    #[test]
14901    fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
14902        // Pin the diagnostic shape: the duplicate-edge error names
14903        // *which* target field carried the conflict, so the author
14904        // doesn't have to re-grep the source caixa.lisp to find it.
14905        // Same self-locating diagnostic discipline as
14906        // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
14907        let mut s = three_member_spec();
14908        s.contratos
14909            .push(contract_http("cart", "catalog", "/products/:id"));
14910        let err = s.validate().unwrap_err();
14911        let msg = format!("{err}");
14912        assert!(
14913            msg.contains("\"/products/:id\""),
14914            "duplicate-contrato diagnostic must name the offending \
14915             :endpoint payload (got: {msg:?})"
14916        );
14917        assert!(
14918            msg.contains("cart") && msg.contains("catalog"),
14919            "diagnostic must name both endpoints of the duplicate edge \
14920             (got: {msg:?})"
14921        );
14922    }
14923
14924    #[test]
14925    fn duplicate_contrato_gate_runs_after_membership_check() {
14926        // Order pin: a duplicate contract whose `:de` is *also* not in
14927        // `:membros` surfaces the membership error first — the
14928        // missing-member diagnostic is more locating than the
14929        // duplicate-edge one (the author has to fix the membership
14930        // before the duplicate is meaningful). Same ordering
14931        // discipline as `membros_validation_runs_before_contratos_membership_check`.
14932        let mut s = three_member_spec();
14933        s.contratos.push(contract_http("phantom", "catalog", "/x"));
14934        s.contratos.push(contract_http("phantom", "catalog", "/x"));
14935        let err = s.validate().unwrap_err();
14936        assert!(
14937            matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
14938            "membership-missing must fire before duplicate-edge (got {err:?})"
14939        );
14940    }
14941
14942    #[test]
14943    fn duplicate_contrato_gate_runs_after_target_shape_check() {
14944        // Order pin: a contract with a malformed target (e.g. an HTTP
14945        // wit world with an empty :endpoint) surfaces the target-shape
14946        // error first, not the duplicate one. Even when two such
14947        // malformed entries are identical, the per-contract `target()`
14948        // check fires inside the loop *before* the duplicate-key
14949        // insert, so the diagnostic remains the most-locating one.
14950        let mut s = three_member_spec();
14951        let malformed = WitContract {
14952            de: "cart".into(),
14953            para: "catalog".into(),
14954            wit: "wasi:http/proxy".into(),
14955            endpoint: Some(String::new()),
14956            subject: None,
14957            slot: None,
14958        };
14959        s.contratos.push(malformed.clone());
14960        s.contratos.push(malformed);
14961        let err = s.validate().unwrap_err();
14962        assert!(
14963            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
14964            "endpoint-empty must fire before duplicate-edge (got {err:?})"
14965        );
14966    }
14967
14968    #[test]
14969    fn wit_target_label_pins_per_variant_format() {
14970        // Label format is the single source of truth every duplicate-
14971        // `:contratos` diagnostic + every future `feira app graph`
14972        // consumer routes through. Pin the shape per variant so a
14973        // future edit to `WitTarget::label` (e.g. a JSON emitter that
14974        // strips the leading `:`, or a rename from `endpoint` →
14975        // `path`) surfaces as a red-red test rather than as a silent
14976        // downstream diagnostic drift. Together with the exhaustive
14977        // `match` on `WitTarget` inside `label()`, adding a future
14978        // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
14979        // peer, per-edge WIT registry variants) is a compile error at
14980        // the label site — not a fall-through into the `Capability`
14981        // "no payload" default the prior raw-field-probe helper
14982        // silently landed on.
14983        assert_eq!(
14984            WitTarget::Http {
14985                endpoint: "/charge",
14986            }
14987            .label(),
14988            "\
14989:endpoint \"/charge\""
14990        );
14991        assert_eq!(
14992            WitTarget::PubSub {
14993                subject: "events.checkout.paid",
14994            }
14995            .label(),
14996            "\
14997:subject \"events.checkout.paid\""
14998        );
14999        assert_eq!(
15000            WitTarget::Store {
15001                slot: "checkout/$order",
15002            }
15003            .label(),
15004            "\
15005:slot \"checkout/$order\""
15006        );
15007        assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
15008        // Capability-arm label routes through the lifted
15009        // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
15010        // declaration per arm, next to the variant" discipline the
15011        // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
15012        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
15013        // consts already carry extends to the payload-less arm; the
15014        // byte-string equality pin below plus this label-routes-
15015        // through-the-const pin make a future rebrand on either the
15016        // const declaration or the `label()` template a build error
15017        // here rather than a downstream consumer surprise.
15018        assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
15019        assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
15020    }
15021
15022    #[test]
15023    fn wit_target_display_routes_through_label_helper() {
15024        // Fail-before-pass-after pin on the fourth (and only remaining)
15025        // typed-shape-discriminator axis to converge onto the
15026        // three-path-convergence discipline the sibling M3
15027        // [`PlacementStrategy`] (0a2f653) and M2
15028        // [`crate::supervisor::RestartStrategy`] /
15029        // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
15030        // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
15031        // through [`WitTarget::label`], so every consumer reaching for
15032        // `format!("{v}")` on a typed payload target lands on the same
15033        // stable author-facing byte-string [`WitTarget::label`] returns
15034        // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
15035        // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
15036        // `:contratos` gate seeds via [`WitTarget::label`] at
15037        // aplicacao.rs:5491 already threads through.
15038        //
15039        // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
15040        // through to the `Debug` derive's structural output
15041        // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
15042        // rather than the [`WitTarget::label`] helper's stable byte-
15043        // string (`:endpoint "/charge"` — the author-facing `:contratos`
15044        // keyword form). Every future consumer that reaches for
15045        // `format!("{target}")` — the canonical shape every user-facing
15046        // pretty-print site on the sibling typed-enum axes
15047        // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
15048        // [`crate::supervisor::RestartPolicy`]) already uses — would
15049        // silently land under a different byte-string than the
15050        // [`WitTarget::label`] callers that the duplicate-`:contratos`
15051        // diagnostic already threads through, with the mismatch
15052        // surfacing as a downstream diagnostic / graph / audit line
15053        // reading one spelling while the substrate's own gate emitted
15054        // another.
15055        //
15056        // Pin the routing here so a future
15057        // `impl std::fmt::Display for WitTarget<'_>` reimplementation
15058        // that hand-rolls the per-arm formatting instead of delegating
15059        // to [`WitTarget::label`] fails at caixa-core build time.
15060        for variant in [
15061            WitTarget::Http {
15062                endpoint: "/charge",
15063            },
15064            WitTarget::PubSub {
15065                subject: "events.checkout.paid",
15066            },
15067            WitTarget::Store {
15068                slot: "checkout/$order",
15069            },
15070            WitTarget::Capability,
15071        ] {
15072            assert_eq!(
15073                variant.to_string(),
15074                variant.label(),
15075                "WitTarget::{variant:?} Display must route through \
15076                 WitTarget::label (single source of truth: the lifted \
15077                 payload_pair 4-arm dispatch the label helper already \
15078                 threads through)"
15079            );
15080        }
15081    }
15082
15083    #[test]
15084    fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
15085        // Consumer-side pin on the three-path convergence:
15086        // [`std::fmt::Display`] agrees byte-for-byte with the
15087        // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
15088        // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
15089        // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
15090        // Pre-lift the two paths were structurally independent — the
15091        // substrate-side gate reached for `target_view.label()` while a
15092        // future downstream diagnostic / graph / audit line reaching
15093        // for `format!("{target}")` would silently land on the `Debug`
15094        // derive's structural output. Pin the two paths byte-for-byte
15095        // here so any future variant addition (M4 `Rest`/`Grpc` split
15096        // of [`WitTarget::Http`], `Queue`-shaped peer of
15097        // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
15098        // match error at [`WitTarget::payload_pair`] rather than a
15099        // silent per-consumer dispatch miss.
15100        for variant in [
15101            WitTarget::Http {
15102                endpoint: "/charge",
15103            },
15104            WitTarget::PubSub {
15105                subject: "events.checkout.paid",
15106            },
15107            WitTarget::Store {
15108                slot: "checkout/$order",
15109            },
15110            WitTarget::Capability,
15111        ] {
15112            assert_eq!(
15113                format!("{variant}"),
15114                variant.label(),
15115                "WitTarget::{variant:?} Display byte-string must match \
15116                 the AplicacaoError::ContratoDuplicate `target:` carrier \
15117                 the AplicacaoSpec::validate duplicate-`:contratos` gate \
15118                 seeds via WitTarget::label — three-path convergence: \
15119                 Display + label + payload_pair all resolve to the same \
15120                 per-arm byte-string"
15121            );
15122        }
15123    }
15124
15125    #[test]
15126    fn wit_target_payload_pair_pins_per_variant() {
15127        // Pin the per-arm `(field-name, payload)` pair single-sourced
15128        // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
15129        // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
15130        // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
15131        // and [`WitTarget::field_name`] (returns the first component)
15132        // route through. Until this lift landed [`WitTarget::label`]
15133        // dispatched on the same three arms with a per-arm
15134        // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
15135        // paired [`WitTarget::HTTP_FIELD_NAME`] /
15136        // [`WitTarget::PUBSUB_FIELD_NAME`] /
15137        // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
15138        // canonical "same shape, written N times" duplication
15139        // THEORY.md §I.3.5 promotes to a build-time concern. A future
15140        // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
15141        // [`WitTarget::Http`], `Queue`-shaped peer of
15142        // [`WitTarget::Store`]) is one match-arm edit at
15143        // [`WitTarget::payload_pair`], visible here as a compile-time
15144        // exhaustiveness error on both this pin and the label-format
15145        // pin above.
15146        assert_eq!(
15147            WitTarget::Http {
15148                endpoint: "/charge"
15149            }
15150            .payload_pair(),
15151            Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
15152        );
15153        assert_eq!(
15154            WitTarget::PubSub {
15155                subject: "events.x",
15156            }
15157            .payload_pair(),
15158            Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
15159        );
15160        assert_eq!(
15161            WitTarget::Store {
15162                slot: "checkout/$order",
15163            }
15164            .payload_pair(),
15165            Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
15166        );
15167        assert_eq!(WitTarget::Capability.payload_pair(), None);
15168    }
15169
15170    #[test]
15171    fn wit_target_field_name_pins_per_variant() {
15172        // Pin the per-arm author-facing `:contratos` payload field
15173        // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
15174        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
15175        // + returned by [`WitTarget::field_name`]. Every downstream
15176        // consumer (the [`WitContract::target`] gate's `expected:`
15177        // scalar, the [`WitTarget::label`] template's keyword prefix,
15178        // the `feira app graph` verb's `endpoint=…` prefix) routes
15179        // through the same three peer consts, so a rename on the
15180        // author-surface `(defcaixa … :contratos ((:de … :para …
15181        // :wit … :endpoint …)))` field lands in exactly one place.
15182        assert_eq!(
15183            WitTarget::Http {
15184                endpoint: "/charge"
15185            }
15186            .field_name(),
15187            Some(WitTarget::HTTP_FIELD_NAME),
15188        );
15189        assert_eq!(
15190            WitTarget::PubSub {
15191                subject: "events.x",
15192            }
15193            .field_name(),
15194            Some(WitTarget::PUBSUB_FIELD_NAME),
15195        );
15196        assert_eq!(
15197            WitTarget::Store {
15198                slot: "checkout/$order",
15199            }
15200            .field_name(),
15201            Some(WitTarget::STORE_FIELD_NAME),
15202        );
15203        // Capability arm carries no payload field — the diagnostic
15204        // never reports `expected: "capability"` because the gate's
15205        // Capability arm accepts no payload at all (it fires the
15206        // "expected: none" WrongTarget error instead), so the field-
15207        // name method returns None here rather than a placeholder.
15208        assert_eq!(WitTarget::Capability.field_name(), None);
15209
15210        // Peer const scalar values pinned so a rename on either side
15211        // (author-surface field name in the `(defcaixa …)` DSL, or
15212        // the diagnostic's `expected:` scalar) can't drift without
15213        // failing here first.
15214        assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
15215        assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
15216        assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
15217    }
15218
15219    #[test]
15220    fn wit_target_payload_pins_per_variant() {
15221        // Pin the per-arm payload scalar single-sourced onto the
15222        // [`WitTarget::payload_pair`] 4-arm dispatch and surfaced through
15223        // [`WitTarget::payload`] — the peer per-half projection to
15224        // [`WitTarget::field_name`] on the paired sub-selector axis. The
15225        // three payload-carrying arms round-trip their author-declared
15226        // scalar verbatim (`Http` → `Some("/charge")`, `PubSub` →
15227        // `Some("events.x")`, `Store` → `Some("checkout/$order")`) and
15228        // the payload-less [`WitTarget::Capability`] arm returns `None`.
15229        // Same shape as the sibling `wit_target_field_name_pins_per_variant`
15230        // (c6ec2af) pin on the Component-0 projection axis, extended
15231        // onto the Component-1 projection axis so both per-half readers
15232        // on the paired dispatch carry their own byte-shape pin.
15233        assert_eq!(
15234            WitTarget::Http {
15235                endpoint: "/charge",
15236            }
15237            .payload(),
15238            Some("/charge"),
15239        );
15240        assert_eq!(
15241            WitTarget::PubSub {
15242                subject: "events.x",
15243            }
15244            .payload(),
15245            Some("events.x"),
15246        );
15247        assert_eq!(
15248            WitTarget::Store {
15249                slot: "checkout/$order",
15250            }
15251            .payload(),
15252            Some("checkout/$order"),
15253        );
15254        assert_eq!(WitTarget::Capability.payload(), None);
15255    }
15256
15257    #[test]
15258    fn wit_target_payload_matches_payload_pair_second_component_per_variant() {
15259        // Per-variant equivalence pin: for every arm of [`WitTarget`],
15260        // `.payload()` equals `.payload_pair().map(|(_, p)| p)`
15261        // byte-for-byte. Guards the drift surface where a future refactor
15262        // that split one accessor off the shared match onto its own
15263        // dispatch — a well-meaning "inline the pair back into per-half
15264        // fields for one crate-internal caller who only wanted one half"
15265        // or a scratch `impl` shadowing the derived projection — would
15266        // silently desynchronize [`WitTarget::payload`] from the
15267        // authoritative [`WitTarget::payload_pair`] dispatch, and every
15268        // downstream consumer that thinks "the payload half of the pair"
15269        // would drift from the diagnostic / graph consumers reading the
15270        // same match through [`WitTarget::label`] / [`WitTarget::graph_label`].
15271        // Sibling to the peer [`caixa_flux::GitRefSpec`] `ref_value`
15272        // per-half projection pin (`gitrefspec_ref_pair_projects_
15273        // ref_field_name_and_ref_value_per_variant`, 655a1c0) on the
15274        // FluxCD source-controller `spec.ref.<field>` axis — same "one
15275        // paired dispatch, both per-half projections agree byte-for-
15276        // byte" discipline extended onto the M3 `:contratos` payload-
15277        // arm surface.
15278        for variant in [
15279            WitTarget::Http {
15280                endpoint: "/charge",
15281            },
15282            WitTarget::PubSub {
15283                subject: "events.checkout.paid",
15284            },
15285            WitTarget::Store {
15286                slot: "checkout/$order",
15287            },
15288            WitTarget::Capability,
15289        ] {
15290            let via_projection = variant.payload();
15291            let via_pair = variant.payload_pair().map(|(_, p)| p);
15292            assert_eq!(
15293                via_projection, via_pair,
15294                "WitTarget::{variant:?} payload() must equal \
15295                 payload_pair().map(|(_, p)| p) byte-for-byte — a \
15296                 regression that splits the two per-half projections off \
15297                 their shared match would silently desynchronize the \
15298                 payload accessor from the paired dispatch every \
15299                 diagnostic / graph consumer reads through",
15300            );
15301        }
15302    }
15303
15304    #[test]
15305    fn wit_target_http_endpoint_pins_per_variant() {
15306        // Pin the per-arm HTTP-endpoint scalar single-sourced onto the
15307        // [`WitTarget::http_endpoint`] 2-arm dispatch — the
15308        // substrate-primitive per-arm post-projection accessor every
15309        // L7-HTTP-facing consumer routes through, sibling to the peer
15310        // WitContract pre-projection [`WitContract::endpoint`] (7020470)
15311        // scalar accessor on the raw-field axis. The [`WitTarget::Http`]
15312        // arm round-trips its author-declared endpoint verbatim as
15313        // `Some("/charge")`; the three sibling arms
15314        // ([`WitTarget::PubSub`] / [`WitTarget::Store`] /
15315        // [`WitTarget::Capability`]) each return `None` because they
15316        // carry no HTTP endpoint by definition. Same fail-before-pass-
15317        // after per-variant discipline as the sibling
15318        // `wit_target_payload_pins_per_variant` (5d6dc92) /
15319        // `wit_target_field_name_pins_per_variant` (c6ec2af) /
15320        // `wit_target_payload_pair_pins_per_variant` (6788ed6) pins on
15321        // the peer pan-arm / per-half projection axes — extended onto
15322        // the per-arm HTTP-shape post-projection axis so a future
15323        // [`WitTarget`] variant addition (a `Rest`/`Grpc` split of
15324        // [`WitTarget::Http`], a `Queue`-shaped peer of
15325        // [`WitTarget::Store`]) trips a compile-time exhaustiveness
15326        // error on the sibling [`WitTarget::http_endpoint`] match arms
15327        // whose payload the L7-HTTP-shape accept-set is meant to bound.
15328        assert_eq!(
15329            WitTarget::Http {
15330                endpoint: "/charge",
15331            }
15332            .http_endpoint(),
15333            Some("/charge"),
15334        );
15335        assert_eq!(
15336            WitTarget::PubSub {
15337                subject: "events.checkout.paid",
15338            }
15339            .http_endpoint(),
15340            None,
15341        );
15342        assert_eq!(
15343            WitTarget::Store {
15344                slot: "checkout/$order",
15345            }
15346            .http_endpoint(),
15347            None,
15348        );
15349        assert_eq!(WitTarget::Capability.http_endpoint(), None);
15350    }
15351
15352    #[test]
15353    fn wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere() {
15354        // Per-variant coherence pin: for every arm of [`WitTarget`],
15355        // `.http_endpoint()` equals `.payload()` on the [`WitTarget::Http`]
15356        // arm (both project the same author-declared request-path
15357        // scalar), and returns `None` on every sibling arm regardless of
15358        // whether [`WitTarget::payload`] itself returns `Some` (PubSub /
15359        // Store carry their own payload the pan-arm accessor surfaces,
15360        // but that payload is not an HTTP endpoint — the per-arm
15361        // accessor must not leak it through the HTTP-shape channel).
15362        // Guards the drift surface where a future refactor that
15363        // conflated the per-arm HTTP projection with the pan-arm
15364        // [`WitTarget::payload`] projection — a well-meaning "one
15365        // accessor for the L7 branch, one for the graph" collapse that
15366        // routes both through the same 4-arm dispatch — would silently
15367        // widen the L7-HTTP-shape accept-set onto pub-sub / store
15368        // payloads at the caixa-mesh L7 emit branch, admitting a
15369        // `nats:pub-sub` edge's `:subject` as a Cilium L7 HTTP `path:`
15370        // rule with the operator-side apply-time symptom (Cilium's
15371        // eBPF data-plane rejects every ingress edge whose L7 filter
15372        // doesn't match the wire-format HTTP request line) far from
15373        // the source refactor. Sibling to the peer
15374        // `wit_target_payload_matches_payload_pair_second_component_
15375        // per_variant` (5d6dc92) coherence pin on the pan-arm axis —
15376        // extended onto the per-arm HTTP specialization axis so both
15377        // the pan-arm and the per-arm projections carry their own
15378        // byte-shape coherence witness against the substrate's typed
15379        // arm-family accept-set.
15380        for variant in [
15381            WitTarget::Http {
15382                endpoint: "/charge",
15383            },
15384            WitTarget::PubSub {
15385                subject: "events.checkout.paid",
15386            },
15387            WitTarget::Store {
15388                slot: "checkout/$order",
15389            },
15390            WitTarget::Capability,
15391        ] {
15392            let per_arm = variant.http_endpoint();
15393            let pan_arm = variant.payload();
15394            if variant.is_http() {
15395                assert_eq!(
15396                    per_arm, pan_arm,
15397                    "WitTarget::{variant:?} http_endpoint() must equal \
15398                     payload() on the Http arm — a per-arm-vs-pan-arm \
15399                     split would silently drift the L7 emit branch's \
15400                     path-scalar source from the graph verb's payload \
15401                     scalar source",
15402                );
15403            } else {
15404                assert_eq!(
15405                    per_arm, None,
15406                    "WitTarget::{variant:?} http_endpoint() must return \
15407                     None on non-Http arms — a leak that surfaced a \
15408                     pub-sub :subject or a key/value :slot through the \
15409                     HTTP-endpoint accessor would silently widen the \
15410                     Cilium L7 HTTP `path:` rule accept-set onto \
15411                     protocol shapes Cilium's eBPF data-plane can't \
15412                     introspect",
15413                );
15414            }
15415        }
15416    }
15417
15418    #[test]
15419    fn wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant() {
15420        // Per-variant coherence pin: for every arm of [`WitTarget`],
15421        // `.http_endpoint().is_some()` iff `.is_http()`. Guards the
15422        // drift surface where a future extension of the
15423        // [`WitTarget::http_endpoint`] accessor's accept-set (e.g. a
15424        // `Rest`/`Grpc` split of [`WitTarget::Http`] that widened the
15425        // accessor to cover both peers) landed without a paired
15426        // extension of the [`gen_platform::IsVariant`]-derived
15427        // `is_http()` predicate's accept-set, or vice versa — a
15428        // regression that split the "which arms count as HTTP-shaped
15429        // for L7-path emission?" answer between two dispatch surfaces
15430        // the substrate ships. Sibling to the peer
15431        // `wit_target_field_name_pins_per_variant` (c6ec2af) discipline
15432        // on the paired dispatch axis — extended onto the per-arm
15433        // predicate-vs-accessor coherence axis so the gen-platform
15434        // IsVariant predicate and the substrate-lifted per-arm
15435        // accessor carry one shared answer to "is this the HTTP arm?".
15436        for variant in [
15437            WitTarget::Http {
15438                endpoint: "/charge",
15439            },
15440            WitTarget::PubSub {
15441                subject: "events.checkout.paid",
15442            },
15443            WitTarget::Store {
15444                slot: "checkout/$order",
15445            },
15446            WitTarget::Capability,
15447        ] {
15448            assert_eq!(
15449                variant.http_endpoint().is_some(),
15450                variant.is_http(),
15451                "WitTarget::{variant:?} http_endpoint().is_some() must \
15452                 equal is_http() — a drift would split the L7 emit \
15453                 branch's arm-set gate from the substrate-derived \
15454                 shape-discrimination predicate on the same axis",
15455            );
15456        }
15457    }
15458
15459    #[test]
15460    fn wit_target_pubsub_subject_pins_per_variant() {
15461        // Fail-before-pass-after pin: the substrate-canonical per-arm
15462        // pub-sub-subject scalar accessor [`WitTarget::pubsub_subject`]
15463        // is the single dispatch every future pub-sub-facing consumer
15464        // routes through, sibling to the peer [`WitContract::subject`]
15465        // (63e18a0) pre-projection scalar accessor on the raw-field
15466        // axis and to the peer [`WitTarget::http_endpoint`] (5d6dc92)
15467        // post-projection per-arm accessor on the sibling HTTP-shape
15468        // axis. The [`WitTarget::PubSub`] arm round-trips its
15469        // author-declared subject verbatim as
15470        // `Some("events.checkout.paid")`; the three sibling arms each
15471        // return `None` because they carry no NATS-shaped subject by
15472        // definition. Same fail-before-pass-after per-variant discipline
15473        // as the sibling `wit_target_http_endpoint_pins_per_variant`
15474        // pin on the peer per-arm axis — extended onto the per-arm
15475        // pub-sub-shape post-projection axis so a future [`WitTarget`]
15476        // variant addition (a `Rest`/`Grpc` split of [`WitTarget::Http`],
15477        // a `Queue`-shaped peer of [`WitTarget::Store`]) trips a
15478        // compile-time exhaustiveness error on the sibling
15479        // [`WitTarget::pubsub_subject`] match arms whose payload the
15480        // pub-sub-shape accept-set is meant to bound.
15481        assert_eq!(
15482            WitTarget::PubSub {
15483                subject: "events.checkout.paid",
15484            }
15485            .pubsub_subject(),
15486            Some("events.checkout.paid"),
15487        );
15488        assert_eq!(
15489            WitTarget::Http {
15490                endpoint: "/charge",
15491            }
15492            .pubsub_subject(),
15493            None,
15494        );
15495        assert_eq!(
15496            WitTarget::Store {
15497                slot: "checkout/$order",
15498            }
15499            .pubsub_subject(),
15500            None,
15501        );
15502        assert_eq!(WitTarget::Capability.pubsub_subject(), None);
15503    }
15504
15505    #[test]
15506    fn wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere() {
15507        // Per-variant coherence pin: for every arm of [`WitTarget`],
15508        // `.pubsub_subject()` equals `.payload()` on the
15509        // [`WitTarget::PubSub`] arm (both project the same
15510        // author-declared subject scalar), and returns `None` on every
15511        // sibling arm regardless of whether [`WitTarget::payload`]
15512        // itself returns `Some` (Http / Store carry their own payload
15513        // the pan-arm accessor surfaces, but that payload is not a
15514        // pub-sub subject — the per-arm accessor must not leak it
15515        // through the pub-sub-shape channel). Sibling to the peer
15516        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
15517        // coherence pin on the per-arm HTTP-shape axis — extended onto
15518        // the per-arm pub-sub specialization axis so both per-arm
15519        // projections carry their own byte-shape coherence witness
15520        // against the substrate's typed arm-family accept-set.
15521        for variant in [
15522            WitTarget::Http {
15523                endpoint: "/charge",
15524            },
15525            WitTarget::PubSub {
15526                subject: "events.checkout.paid",
15527            },
15528            WitTarget::Store {
15529                slot: "checkout/$order",
15530            },
15531            WitTarget::Capability,
15532        ] {
15533            let per_arm = variant.pubsub_subject();
15534            let pan_arm = variant.payload();
15535            if variant.is_pubsub() {
15536                assert_eq!(
15537                    per_arm, pan_arm,
15538                    "WitTarget::{variant:?} pubsub_subject() must equal \
15539                     payload() on the PubSub arm — a per-arm-vs-pan-arm \
15540                     split would silently drift the pub-sub-shape emit \
15541                     branch's subject-scalar source from the graph verb's \
15542                     payload scalar source",
15543                );
15544            } else {
15545                assert_eq!(
15546                    per_arm, None,
15547                    "WitTarget::{variant:?} pubsub_subject() must return \
15548                     None on non-PubSub arms — a leak that surfaced an \
15549                     HTTP :endpoint or a key/value :slot through the \
15550                     pub-sub-subject accessor would silently widen the \
15551                     downstream NATS-shape accept-set onto protocol \
15552                     shapes NATS servers can't route",
15553                );
15554            }
15555        }
15556    }
15557
15558    #[test]
15559    fn wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant() {
15560        // Per-variant coherence pin: for every arm of [`WitTarget`],
15561        // `.pubsub_subject().is_some()` iff `.is_pubsub()`. Guards the
15562        // drift surface where a future extension of the
15563        // [`WitTarget::pubsub_subject`] accessor's accept-set landed
15564        // without a paired extension of the [`gen_platform::IsVariant`]-
15565        // derived `is_pubsub()` predicate's accept-set, or vice versa
15566        // — a regression that split the "which arms count as pub-sub-
15567        // shaped for subject emission?" answer between two dispatch
15568        // surfaces the substrate ships. Sibling to the peer
15569        // `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
15570        // pin on the per-arm HTTP-shape axis — extended onto the
15571        // per-arm pub-sub predicate-vs-accessor coherence axis so the
15572        // gen-platform IsVariant predicate and the substrate-lifted
15573        // per-arm accessor carry one shared answer to "is this the
15574        // PubSub arm?".
15575        for variant in [
15576            WitTarget::Http {
15577                endpoint: "/charge",
15578            },
15579            WitTarget::PubSub {
15580                subject: "events.checkout.paid",
15581            },
15582            WitTarget::Store {
15583                slot: "checkout/$order",
15584            },
15585            WitTarget::Capability,
15586        ] {
15587            assert_eq!(
15588                variant.pubsub_subject().is_some(),
15589                variant.is_pubsub(),
15590                "WitTarget::{variant:?} pubsub_subject().is_some() must \
15591                 equal is_pubsub() — a drift would split the pub-sub \
15592                 emit branch's arm-set gate from the substrate-derived \
15593                 shape-discrimination predicate on the same axis",
15594            );
15595        }
15596    }
15597
15598    #[test]
15599    fn wit_target_store_slot_pins_per_variant() {
15600        // Fail-before-pass-after pin: the substrate-canonical per-arm
15601        // key/value-store-slot scalar accessor [`WitTarget::store_slot`]
15602        // is the single dispatch every future store-facing consumer
15603        // routes through, sibling to the peer [`WitContract::slot`]
15604        // pre-projection scalar accessor on the raw-field axis and to
15605        // the peer [`WitTarget::http_endpoint`] (5d6dc92) +
15606        // [`WitTarget::pubsub_subject`] post-projection per-arm
15607        // accessors on the sibling per-payload-arm axes. The
15608        // [`WitTarget::Store`] arm round-trips its author-declared
15609        // slot verbatim as `Some("checkout/$order")`; the three
15610        // sibling arms each return `None` because they carry no
15611        // WASI-key/value slot by definition. Same fail-before-pass-
15612        // after per-variant discipline as the sibling
15613        // `wit_target_http_endpoint_pins_per_variant` +
15614        // `wit_target_pubsub_subject_pins_per_variant` pins on the
15615        // peer per-arm axes — extended onto the per-arm store-shape
15616        // post-projection axis so a future [`WitTarget`] variant
15617        // addition trips a compile-time exhaustiveness error on the
15618        // sibling [`WitTarget::store_slot`] match arms whose payload
15619        // the store-shape accept-set is meant to bound.
15620        assert_eq!(
15621            WitTarget::Store {
15622                slot: "checkout/$order",
15623            }
15624            .store_slot(),
15625            Some("checkout/$order"),
15626        );
15627        assert_eq!(
15628            WitTarget::Http {
15629                endpoint: "/charge",
15630            }
15631            .store_slot(),
15632            None,
15633        );
15634        assert_eq!(
15635            WitTarget::PubSub {
15636                subject: "events.checkout.paid",
15637            }
15638            .store_slot(),
15639            None,
15640        );
15641        assert_eq!(WitTarget::Capability.store_slot(), None);
15642    }
15643
15644    #[test]
15645    fn wit_target_store_slot_matches_payload_on_store_arm_and_is_none_elsewhere() {
15646        // Per-variant coherence pin: for every arm of [`WitTarget`],
15647        // `.store_slot()` equals `.payload()` on the
15648        // [`WitTarget::Store`] arm (both project the same
15649        // author-declared slot scalar), and returns `None` on every
15650        // sibling arm regardless of whether [`WitTarget::payload`]
15651        // itself returns `Some`. Sibling to the peer
15652        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
15653        // and `wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere`
15654        // pins on the per-arm HTTP and PubSub axes — closes the
15655        // per-arm-vs-pan-arm byte-shape coherence trio across all
15656        // three payload arms.
15657        for variant in [
15658            WitTarget::Http {
15659                endpoint: "/charge",
15660            },
15661            WitTarget::PubSub {
15662                subject: "events.checkout.paid",
15663            },
15664            WitTarget::Store {
15665                slot: "checkout/$order",
15666            },
15667            WitTarget::Capability,
15668        ] {
15669            let per_arm = variant.store_slot();
15670            let pan_arm = variant.payload();
15671            if variant.is_store() {
15672                assert_eq!(
15673                    per_arm, pan_arm,
15674                    "WitTarget::{variant:?} store_slot() must equal \
15675                     payload() on the Store arm — a per-arm-vs-pan-arm \
15676                     split would silently drift the store-shape emit \
15677                     branch's slot-scalar source from the graph verb's \
15678                     payload scalar source",
15679                );
15680            } else {
15681                assert_eq!(
15682                    per_arm, None,
15683                    "WitTarget::{variant:?} store_slot() must return \
15684                     None on non-Store arms — a leak that surfaced an \
15685                     HTTP :endpoint or a NATS :subject through the \
15686                     key/value-slot accessor would silently widen the \
15687                     downstream WASI-key/value slot accept-set onto \
15688                     protocol shapes the kv backends can't route",
15689                );
15690            }
15691        }
15692    }
15693
15694    #[test]
15695    fn wit_target_store_slot_agrees_with_is_store_predicate_per_variant() {
15696        // Per-variant coherence pin: for every arm of [`WitTarget`],
15697        // `.store_slot().is_some()` iff `.is_store()`. Guards the
15698        // drift surface where a future extension of the
15699        // [`WitTarget::store_slot`] accessor's accept-set landed
15700        // without a paired extension of the [`gen_platform::IsVariant`]-
15701        // derived `is_store()` predicate's accept-set. Sibling to the
15702        // peer `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
15703        // and `wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant`
15704        // pins — closes the per-arm predicate-vs-accessor coherence
15705        // trio across all three payload arms so the gen-platform
15706        // IsVariant predicate and the substrate-lifted per-arm
15707        // accessor carry one shared answer to "is this the Store arm?".
15708        for variant in [
15709            WitTarget::Http {
15710                endpoint: "/charge",
15711            },
15712            WitTarget::PubSub {
15713                subject: "events.checkout.paid",
15714            },
15715            WitTarget::Store {
15716                slot: "checkout/$order",
15717            },
15718            WitTarget::Capability,
15719        ] {
15720            assert_eq!(
15721                variant.store_slot().is_some(),
15722                variant.is_store(),
15723                "WitTarget::{variant:?} store_slot().is_some() must \
15724                 equal is_store() — a drift would split the store-shape \
15725                 emit branch's arm-set gate from the substrate-derived \
15726                 shape-discrimination predicate on the same axis",
15727            );
15728        }
15729    }
15730
15731    #[test]
15732    fn wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set() {
15733        // Fail-before-pass-after cross-axis pin on the trio
15734        // (`http_endpoint`, `pubsub_subject`, `store_slot`): on every
15735        // payload-carrying arm of [`WitTarget`], exactly one per-arm
15736        // accessor returns `Some(payload)` and the two peers return
15737        // `None`; and on the payload-less [`WitTarget::Capability`]
15738        // arm, all three return `None`. Guards the drift surface where
15739        // a future extension of one per-arm accessor's accept-set (e.g.
15740        // a hypothetical `Rest`/`Grpc` split of [`WitTarget::Http`]
15741        // that widened `http_endpoint` to cover both peers without
15742        // narrowing the peer `pubsub_subject` / `store_slot` accept-
15743        // sets to keep the partition mutually exclusive) landed without
15744        // threading through the peer per-arm accessors — the resulting
15745        // silent overlap would land the same edge's payload on two
15746        // downstream per-shape emit branches at once, or leak a
15747        // pub-sub subject through the store-slot channel, at renderer
15748        // emit time far from the substrate primitive's arm-widening
15749        // commit. Peer of the sibling `wit_target_field_names_are_pairwise_distinct`
15750        // 3-way pin on the payload-field-name axis — extended onto the
15751        // per-arm-accessor payload-projection axis so the substrate-
15752        // owned partition invariant is load-bearing at every per-arm
15753        // consumer's read site.
15754        let payload_variants = [
15755            (
15756                WitTarget::Http {
15757                    endpoint: "/charge",
15758                },
15759                "http",
15760            ),
15761            (
15762                WitTarget::PubSub {
15763                    subject: "events.checkout.paid",
15764                },
15765                "pubsub",
15766            ),
15767            (
15768                WitTarget::Store {
15769                    slot: "checkout/$order",
15770                },
15771                "store",
15772            ),
15773        ];
15774        for (variant, own_arm_label) in payload_variants {
15775            let own_arm_hit = match own_arm_label {
15776                "http" => variant.is_http(),
15777                "pubsub" => variant.is_pubsub(),
15778                "store" => variant.is_store(),
15779                other => panic!("unknown own-arm label {other:?}"),
15780            };
15781            let per_arm_results = [
15782                ("http_endpoint", variant.http_endpoint()),
15783                ("pubsub_subject", variant.pubsub_subject()),
15784                ("store_slot", variant.store_slot()),
15785            ];
15786            let some_count = per_arm_results.iter().filter(|(_, v)| v.is_some()).count();
15787            assert_eq!(
15788                some_count, 1,
15789                "WitTarget::{variant:?} must land exactly one per-arm \
15790                 post-projection accessor's Some result — the trio \
15791                 (http_endpoint, pubsub_subject, store_slot) must \
15792                 partition the payload arm-set; got {per_arm_results:?}",
15793            );
15794            assert!(
15795                own_arm_hit,
15796                "WitTarget::{variant:?} own-arm gen-platform predicate \
15797                 must return true on its own arm — a partition failure \
15798                 upstream of this pin",
15799            );
15800            assert!(
15801                variant.payload().is_some(),
15802                "WitTarget::{variant:?} pan-arm payload() must return \
15803                 Some on every payload-carrying arm the trio partitions",
15804            );
15805        }
15806        // The payload-less Capability arm must return None on every
15807        // per-arm accessor — the partition's terminal-fallback shape.
15808        let cap = WitTarget::Capability;
15809        assert_eq!(cap.http_endpoint(), None);
15810        assert_eq!(cap.pubsub_subject(), None);
15811        assert_eq!(cap.store_slot(), None);
15812        assert_eq!(
15813            cap.payload(),
15814            None,
15815            "WitTarget::Capability pan-arm payload() must return None — \
15816             the trio's payload-less-arm coherence witness",
15817        );
15818    }
15819
15820    #[test]
15821    fn wit_target_field_names_are_pairwise_distinct() {
15822        // Distinctness pin: if any two of the three payload-field-name
15823        // scalars ever collapse (e.g. an accidental `endpoint` copy-
15824        // paste over the `subject` const), the [`WitContract::target`]
15825        // gate's diagnostic would point authors at the wrong field —
15826        // an "expected `:endpoint`" error on a pub-sub edge would
15827        // silently misroute the fix. Same cross-axis-distinctness
15828        // discipline as the peer M3 `:placement :estrategia` variant-
15829        // discriminator scalar-value pins (cc8f749) applied to the
15830        // payload-field-name axis.
15831        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
15832        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
15833        assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
15834    }
15835
15836    #[test]
15837    fn wit_target_graph_label_routes_through_payload_pair_on_payload_arms() {
15838        // Fail-before-pass-after pin: the graph-verb payload column's
15839        // per-arm `{field}={payload}` byte-string is derived through the
15840        // single [`WitTarget::payload_pair`] 4-arm dispatch on the three
15841        // payload-carrying arms, not through a hand-rolled per-arm match
15842        // that re-projects [`WitTarget::HTTP_FIELD_NAME`] /
15843        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
15844        // inline. A future variant addition — the M4-and-later per-edge
15845        // WIT registry may split [`WitTarget::Http`] into `Rest` / `Grpc`
15846        // peers, or extend [`WitTarget::Store`] with a `Queue`-shaped
15847        // peer — becomes one match-arm edit at [`WitTarget::payload_pair`],
15848        // and both [`WitTarget::label`] (duplicate-`:contratos`
15849        // diagnostic) and [`WitTarget::graph_label`] (`feira app graph`
15850        // payload column) pick up the new arm from the same dispatch.
15851        // Prior to this lift the graph verb open-coded the 4-arm match
15852        // in caixa-feira, so a variant addition would have to be threaded
15853        // through both projections in lockstep or the graph verb would
15854        // silently drop the new arm to `(capability-only)`.
15855        for variant in [
15856            WitTarget::Http {
15857                endpoint: "/charge",
15858            },
15859            WitTarget::PubSub {
15860                subject: "events.checkout.paid",
15861            },
15862            WitTarget::Store {
15863                slot: "checkout/$order",
15864            },
15865        ] {
15866            let (field, payload) = variant
15867                .payload_pair()
15868                .expect("payload arm must expose (field, payload)");
15869            assert_eq!(
15870                variant.graph_label(),
15871                format!("{field}={payload}"),
15872                "WitTarget::{variant:?} graph_label must route the \
15873                 `{{field}}={{payload}}` template through payload_pair — \
15874                 a regression to a hand-rolled per-arm match at the graph \
15875                 verb would silently disagree with a future variant \
15876                 addition landed only at payload_pair"
15877            );
15878        }
15879    }
15880
15881    #[test]
15882    fn wit_target_graph_label_returns_capability_graph_label_const_on_capability_arm() {
15883        // Fail-before-pass-after pin on the payload-less arm: the graph
15884        // verb's `(capability-only)` byte-string routes through the
15885        // lifted [`WitTarget::CAPABILITY_GRAPH_LABEL`] const on the
15886        // [`WitTarget::Capability`] arm, not through an inline
15887        // `.to_string()` literal at the caixa-feira `cmd::app::GraphArgs::run`
15888        // per-`:contratos` payload column. Peer of the sibling
15889        // [`wit_target_label_pins_per_variant_format`] Capability-arm
15890        // assertion on the [`WitTarget::CAPABILITY_LABEL`] const —
15891        // extended here onto the third payload-less-arm consumer axis
15892        // (graph verb, sibling to the duplicate-`:contratos` diagnostic
15893        // axis and the wrong-target diagnostic axis).
15894        assert_eq!(
15895            WitTarget::Capability.graph_label(),
15896            WitTarget::CAPABILITY_GRAPH_LABEL,
15897        );
15898        assert_eq!(WitTarget::CAPABILITY_GRAPH_LABEL, "(capability-only)");
15899    }
15900
15901    #[test]
15902    fn wit_target_capability_graph_label_distinct_from_capability_label() {
15903        // Cross-consumer-axis distinctness pin: the graph-verb
15904        // payload-column const [`WitTarget::CAPABILITY_GRAPH_LABEL`]
15905        // (`(capability-only)`) and the duplicate-`:contratos` diagnostic
15906        // label const [`WitTarget::CAPABILITY_LABEL`] (`(capability — no
15907        // payload)`) surface the payload-less arm on two distinct
15908        // consumer axes; a collapse (an accidental rebrand that lands
15909        // one spelling on both consts, a copy-paste that unifies them
15910        // "for consistency") would silently merge the two byte-strings
15911        // and lose the vocabulary distinction the graph verb's
15912        // compact-column form and the diagnostic's descriptive-clause
15913        // form each carry on purpose. Peer of the sibling 4-way
15914        // [`wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`]
15915        // pin on the `ContratoWrongTarget::expected` scalar-value axis —
15916        // extended here onto the cross-consumer-axis distinctness of the
15917        // two payload-less-arm consts.
15918        assert_ne!(
15919            WitTarget::CAPABILITY_GRAPH_LABEL,
15920            WitTarget::CAPABILITY_LABEL,
15921            "WitTarget::CAPABILITY_GRAPH_LABEL (graph-verb payload column) \
15922             and WitTarget::CAPABILITY_LABEL (duplicate-`:contratos` \
15923             diagnostic) must remain distinct — a collapse would silently \
15924             merge two consumer axes onto one spelling"
15925        );
15926    }
15927
15928    #[test]
15929    fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
15930        // 4-way distinctness pin extending the sibling
15931        // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
15932        // (which covers only the HTTP / PubSub / Store payload arms)
15933        // onto the fourth scalar the shared
15934        // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
15935        // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
15936        // (`"none"`), the payload-less Capability-arm rejection scalar.
15937        //
15938        // All four [`WitTarget::HTTP_FIELD_NAME`] /
15939        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
15940        // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
15941        // dispatch surface [`WitContract::target`] writes onto the
15942        // `ContratoWrongTarget::expected` field — the same `&'static
15943        // str` axis authors read as "this WIT world's shape admits
15944        // (only|not) `:<field>`". Pairwise-distinctness is the invariant
15945        // downstream consumers rely on: an `expected: "endpoint"`
15946        // diagnostic on a Capability-shaped edge tells the author to
15947        // add a `:endpoint "…"` slot to a WIT world that admits none,
15948        // silently misrouting the fix. Until this pin landed the three
15949        // payload-arm consts were distinctness-guarded by the sibling
15950        // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
15951        // scalar (d4f54f2) sat unguarded — a rebrand collision (the
15952        // author-facing vocabulary shift from `"none"` to `"endpoint"`
15953        // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
15954        // into per-shape peers) would have silently landed one
15955        // Capability-arm rejection on a payload-arm's `expected:` byte-
15956        // string and desynchronized the diagnostic from the author's
15957        // typed shape.
15958        //
15959        // Same 4-way pairwise-distinctness pin discipline as the peer
15960        // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
15961        // (cc8f749) applies on the sibling M3 closed-set typed-enum
15962        // scalar-value dispatch axis; extends the pin trajectory the
15963        // sibling `wit_target_field_names_are_pairwise_distinct`
15964        // 3-way pin opened to cover the last unguarded corner on the
15965        // `ContratoWrongTarget::expected` scalar-value axis.
15966        //
15967        // Fail-before-pass-after locally verified by mutating
15968        // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
15969        // — this pin fires as expected; restoring passes.
15970        let all = [
15971            WitTarget::HTTP_FIELD_NAME,
15972            WitTarget::PUBSUB_FIELD_NAME,
15973            WitTarget::STORE_FIELD_NAME,
15974            WitTarget::CAPABILITY_EXPECTED,
15975        ];
15976        for (i, a) in all.iter().enumerate() {
15977            for (j, b) in all.iter().enumerate() {
15978                if i != j {
15979                    assert_ne!(
15980                        a, b,
15981                        "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
15982                         STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
15983                         pairwise distinct — got duplicate {a:?} at indices \
15984                         {i} and {j}; all four scalars thread through the \
15985                         shared `AplicacaoError::ContratoWrongTarget::expected` \
15986                         &'static str axis, so a collapse silently misdirects \
15987                         the diagnostic on which typed shape the WIT world admits",
15988                    );
15989                }
15990            }
15991        }
15992    }
15993
15994    #[test]
15995    fn wit_target_is_variant_predicates_partition_the_arm_set() {
15996        // Fail-before-pass-after pin on the
15997        // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
15998        // each of the four variants exactly one of the generated
15999        // `is_http` / `is_pubsub` / `is_store` / `is_capability`
16000        // predicates returns `true` and the other three return
16001        // `false`. Prior to this derive the only production
16002        // arm-discriminator on [`WitTarget`] — the sync-cycle
16003        // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
16004        // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
16005        // the variant that expressed no compile-time link back to
16006        // the closed-set typed dispatch a future fifth
16007        // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
16008        // split of [`WitTarget::PubSub`] into shape-specific peers,
16009        // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
16010        // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
16011        // to thread through in lockstep or the DFS exclusion would
16012        // silently disagree with the peer diagnostic templates on
16013        // which arms carry sync-versus-async semantics. Peer of the
16014        // sibling [`crate::CaixaKind`] (f5bba80),
16015        // [`PlacementStrategy`] (766ec63),
16016        // [`crate::supervisor::RestartStrategy`],
16017        // [`crate::supervisor::RestartPolicy`], and
16018        // [`crate::upgrade::UpgradeInstruction`] (915a934)
16019        // `IsVariant` derives on the sibling closed-set typed-enum
16020        // discriminator axes — extends the same one-typed-dispatch-
16021        // per-variant discipline onto the last unlifted closed-set
16022        // typed-enum discriminator on the caixa surface (the M3
16023        // mesh-slot per-`:contratos` target-arm axis), closing the
16024        // arm-discriminator convergence trajectory across every
16025        // closed-set typed enum in caixa-core.
16026        let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
16027            (
16028                WitTarget::Http { endpoint: "/x" },
16029                [true, false, false, false],
16030            ),
16031            (
16032                WitTarget::PubSub {
16033                    subject: "events.x",
16034                },
16035                [false, true, false, false],
16036            ),
16037            (
16038                WitTarget::Store { slot: "kv/x" },
16039                [false, false, true, false],
16040            ),
16041            (WitTarget::Capability, [false, false, false, true]),
16042        ];
16043        for (variant, expected) in rows {
16044            let observed = [
16045                variant.is_http(),
16046                variant.is_pubsub(),
16047                variant.is_store(),
16048                variant.is_capability(),
16049            ];
16050            assert_eq!(
16051                observed, expected,
16052                "WitTarget::{variant:?} is_* predicates must partition \
16053                 the arm set (http, pubsub, store, capability); got {observed:?}"
16054            );
16055        }
16056    }
16057
16058    #[test]
16059    fn wit_target_is_variant_predicates_are_const_fn() {
16060        // The [`gen_platform::IsVariant`] derive emits `const fn`
16061        // predicates on the peer [`crate::CaixaKind`] +
16062        // [`crate::upgrade::UpgradeInstruction`] +
16063        // [`crate::supervisor::RestartStrategy`] +
16064        // [`crate::supervisor::RestartPolicy`] +
16065        // [`PlacementStrategy`] closed-set typed enums — pin the
16066        // same posture on [`WitTarget`] so a future accidental
16067        // downgrade to non-`const` (an added runtime helper reachable
16068        // only from a non-`const` context, a manual hand-rolled
16069        // `impl` that shadows the derive-generated method) trips at
16070        // caixa-core build time rather than surfacing as a downstream
16071        // `const`-context regression far from the derive declaration.
16072        //
16073        // Unlike the peer unit-variant enums (`CaixaKind` /
16074        // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
16075        // whose `const` constructors need no arguments, the three
16076        // payload-carrying [`WitTarget`] arms are const-constructed
16077        // through `&'static str` payloads — the same `'static`
16078        // lifetime the closed-set typed enum's four-arm partition
16079        // pin above already threads through.
16080        //
16081        // The pin lives inside a `const { assert!(..) }` block so the
16082        // compiler enforces both halves (arm predicate is `const`-
16083        // callable AND returns `true` for the matching arm) at
16084        // caixa-core compile time — peer to the sibling
16085        // [`crate::CaixaKind::is_*`] const-block pin on the closed-set
16086        // typed enum arm-predicate const-callability axis.
16087        const {
16088            assert!(WitTarget::Http { endpoint: "/x" }.is_http());
16089            assert!(WitTarget::PubSub { subject: "e" }.is_pubsub());
16090            assert!(WitTarget::Store { slot: "kv/x" }.is_store());
16091            assert!(WitTarget::Capability.is_capability());
16092        }
16093    }
16094
16095    #[test]
16096    fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
16097        // Consumer-side pin on the sole production converge site:
16098        // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
16099        // edges from the synchronous-subgraph DFS via the lifted
16100        // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
16101        // predicate (rebound from the prior raw
16102        // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
16103        // variant). Byte-equivalent today (`is_pubsub` is the
16104        // derive-generated `matches!(self, Self::PubSub { .. })` by
16105        // construction, the `#[is_variant(name = "pubsub")]` override
16106        // aliasing the auto-derived `is_pub_sub` back to the sibling
16107        // [`WitContract::is_pubsub`] name); pin the behavior so a
16108        // future accidental drift (a rebind onto a peer arm
16109        // predicate, a manual hand-rolled `impl` that shadows the
16110        // derive-generated method with different semantics, a peer
16111        // arm rename that shifts which variant carries sync-versus-
16112        // async semantics) trips at caixa-core test time rather than
16113        // at some downstream operator's runtime dispatch far from the
16114        // rebind commit.
16115        //
16116        // The fixture constructs a two-Servico Aplicacao with one
16117        // pub-sub edge that would close a sync-cycle if the DFS did
16118        // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
16119        // pub-sub exclusion means the DFS sees only the `b → a` HTTP
16120        // edge, which is not a cycle. A regression in the converge
16121        // (a rebind that reads the pub-sub arm as sync) would report
16122        // `AplicacaoError::ContratoCycle`.
16123        let s = AplicacaoSpec {
16124            membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
16125            contratos: vec![
16126                // Pub-sub edge: DFS must skip via is_pubsub().
16127                WitContract {
16128                    de: "a".into(),
16129                    para: "b".into(),
16130                    wit: "nats:pub-sub".into(),
16131                    endpoint: None,
16132                    subject: Some("events.x".into()),
16133                    slot: None,
16134                },
16135                // HTTP edge: DFS must include.
16136                WitContract {
16137                    de: "b".into(),
16138                    para: "a".into(),
16139                    wit: "wasi:http/proxy".into(),
16140                    endpoint: Some("/x".into()),
16141                    subject: None,
16142                    slot: None,
16143                },
16144            ],
16145            politicas: MeshPolicy::default(),
16146            placement: Placement {
16147                estrategia: PlacementStrategy::Replicated,
16148                clusters: vec!["rio".into()],
16149                affinity: None,
16150                shard_key: None,
16151            },
16152            entrada: None,
16153        };
16154        s.validate()
16155            .expect("pub-sub edge must be excluded from sync-cycle DFS");
16156    }
16157
16158    #[test]
16159    fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
16160        // Consumer-side pin: the same three peer consts thread through
16161        // both the [`WitTarget::label`] template (leading-`:` keyword
16162        // prefix in the duplicate-`:contratos` diagnostic) and the
16163        // [`WitContract::target`] gate's [`AplicacaoError::
16164        // ContratoMissingTarget`] `expected:` scalar (the field the
16165        // author needs to add). Pin both routes at once so a future
16166        // refactor can't accidentally split them onto separate string
16167        // literals — the "one place, everywhere reaches for it"
16168        // invariant the peer const set carries.
16169        let http_label = WitTarget::Http { endpoint: "/x" }.label();
16170        assert!(
16171            http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
16172            "label must lead with :{} keyword (got {http_label:?})",
16173            WitTarget::HTTP_FIELD_NAME,
16174        );
16175
16176        let mut s = three_member_spec();
16177        s.contratos.push(WitContract {
16178            de: "cart".into(),
16179            para: "catalog".into(),
16180            wit: "kafka:topic".into(),
16181            endpoint: None,
16182            subject: None,
16183            slot: None,
16184        });
16185        match s.validate().unwrap_err() {
16186            AplicacaoError::ContratoMissingTarget { expected, .. } => {
16187                assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
16188            }
16189            other => panic!("expected ContratoMissingTarget, got {other:?}"),
16190        }
16191    }
16192
16193    #[test]
16194    fn duplicate_pubsub_diagnostic_names_offending_subject() {
16195        // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
16196        // on the pub-sub target axis: the duplicate-edge diagnostic
16197        // must name the `:subject` payload verbatim (not just the
16198        // `(de, para, wit)` triple). Prior to lifting the label onto
16199        // [`WitTarget::label`] the diagnostic derived the label from
16200        // raw [`WitContract`] `Option<String>` probes — a future
16201        // `WitTarget` variant addition (M4 per-edge WIT registry)
16202        // would silently fall through to the `Capability` "no
16203        // payload" default without a compiler warning. Pinning the
16204        // pub-sub arm's format closes the second of three
16205        // payload-carrying `WitTarget` arms this diagnostic threads
16206        // through.
16207        let mut s = three_member_spec();
16208        let pubsub = WitContract {
16209            de: "payment".into(),
16210            para: "cart".into(),
16211            wit: "nats:pub-sub".into(),
16212            endpoint: None,
16213            subject: Some("events.checkout.paid".into()),
16214            slot: None,
16215        };
16216        s.contratos.push(pubsub.clone());
16217        s.contratos.push(pubsub);
16218        let err = s.validate().unwrap_err();
16219        let msg = format!("{err}");
16220        assert!(
16221            msg.contains(":subject \"events.checkout.paid\""),
16222            "duplicate-pubsub diagnostic must name the offending \
16223             :subject payload (got: {msg:?})"
16224        );
16225    }
16226
16227    #[test]
16228    fn duplicate_store_diagnostic_names_offending_slot() {
16229        // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
16230        // key-value target axis: the diagnostic must name the `:slot`
16231        // payload verbatim. Third of three payload-carrying
16232        // `WitTarget` arms this diagnostic threads through, closing
16233        // the per-arm label pin trilogy (`Http` — 6841,
16234        // `PubSub` + `Store` — this test + peer above).
16235        let mut s = three_member_spec();
16236        let store = WitContract {
16237            de: "cart".into(),
16238            para: "payment".into(),
16239            wit: "wasi:keyvalue/store".into(),
16240            endpoint: None,
16241            subject: None,
16242            slot: Some("checkout/$orderId".into()),
16243        };
16244        s.contratos
16245            .retain(|c| !(c.de == "cart" && c.para == "payment"));
16246        s.contratos.push(store.clone());
16247        s.contratos.push(store);
16248        let err = s.validate().unwrap_err();
16249        let msg = format!("{err}");
16250        assert!(
16251            msg.contains(":slot \"checkout/$orderId\""),
16252            "duplicate-store diagnostic must name the offending :slot \
16253             payload (got: {msg:?})"
16254        );
16255    }
16256
16257    #[test]
16258    fn rejects_entrada_path_without_leading_slash() {
16259        let mut s = three_member_spec();
16260        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
16261        let err = s.validate().unwrap_err();
16262        assert!(
16263            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
16264            "got {err:?}"
16265        );
16266    }
16267
16268    #[test]
16269    fn rejects_empty_entrada_path() {
16270        let mut s = three_member_spec();
16271        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), String::new()];
16272        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
16273    }
16274
16275    #[test]
16276    fn rejects_duplicate_entrada_paths() {
16277        let mut s = three_member_spec();
16278        s.entrada.as_mut().unwrap().paths = vec![
16279            "/api/cart".into(),
16280            "/api/products".into(),
16281            "/api/cart".into(),
16282        ];
16283        let err = s.validate().unwrap_err();
16284        assert!(
16285            matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
16286            "got {err:?}"
16287        );
16288    }
16289
16290    #[test]
16291    fn rejects_zero_entrada_port() {
16292        let mut s = three_member_spec();
16293        s.entrada.as_mut().unwrap().port = 0;
16294        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
16295    }
16296
16297    // ── :entrada :paths value-shape gate ─────────────────────────────
16298    //
16299    // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
16300    // sibling `:paths` axis. Every authoring footgun the K8s Gateway
16301    // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
16302    // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
16303    // time now becomes a caixa-build-time `EntradaPathInvalid` with
16304    // the offending `:paths` entry named verbatim.
16305
16306    #[test]
16307    fn rejects_entrada_path_with_query() {
16308        // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
16309        // silently passed validate and the Gateway API webhook
16310        // rejected it at apply time with no source citation.
16311        let mut s = three_member_spec();
16312        s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
16313        let err = s.validate().unwrap_err();
16314        assert!(
16315            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16316                if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
16317            "got {err:?}"
16318        );
16319    }
16320
16321    #[test]
16322    fn rejects_entrada_path_with_fragment() {
16323        let mut s = three_member_spec();
16324        s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
16325        let err = s.validate().unwrap_err();
16326        assert!(
16327            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16328                if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
16329            "got {err:?}"
16330        );
16331    }
16332
16333    #[test]
16334    fn rejects_entrada_path_with_space() {
16335        let mut s = three_member_spec();
16336        s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
16337        let err = s.validate().unwrap_err();
16338        assert!(
16339            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16340                if path == "/api/my cart" && reason.contains("whitespace")),
16341            "got {err:?}"
16342        );
16343    }
16344
16345    #[test]
16346    fn rejects_entrada_path_with_tab() {
16347        let mut s = three_member_spec();
16348        s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
16349        let err = s.validate().unwrap_err();
16350        assert!(
16351            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16352                if path == "/api/\tcart" && reason.contains("whitespace")),
16353            "got {err:?}"
16354        );
16355    }
16356
16357    #[test]
16358    fn rejects_entrada_path_with_control_char() {
16359        // 0x01 (SOH) — a non-whitespace control char surfaces the
16360        // distinct "control character" reason arm, separate from
16361        // the whitespace arm. Pinned so a future refactor that
16362        // collapses the two arms can't accidentally drop the more
16363        // self-locating diagnostic.
16364        let mut s = three_member_spec();
16365        s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
16366        let err = s.validate().unwrap_err();
16367        assert!(
16368            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16369                if path == "/api/\x01cart" && reason.contains("control character")),
16370            "got {err:?}"
16371        );
16372    }
16373
16374    #[test]
16375    fn rejects_entrada_path_with_non_ascii() {
16376        // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
16377        // unreserved-set rule rejects. The Gateway API webhook
16378        // rejects literal non-ASCII bytes; percent-encoding is the
16379        // only way to author non-ASCII in a path.
16380        let mut s = three_member_spec();
16381        s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
16382        let err = s.validate().unwrap_err();
16383        assert!(
16384            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16385                if path == "/api/café" && reason.contains("non-ASCII")),
16386            "got {err:?}"
16387        );
16388    }
16389
16390    #[test]
16391    fn rejects_entrada_path_with_consecutive_slashes() {
16392        let mut s = three_member_spec();
16393        s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
16394        let err = s.validate().unwrap_err();
16395        assert!(
16396            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16397                if path == "/api//cart" && reason.contains("consecutive `/`")),
16398            "got {err:?}"
16399        );
16400    }
16401
16402    #[test]
16403    fn rejects_entrada_path_with_dot_segment() {
16404        let mut s = three_member_spec();
16405        s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
16406        let err = s.validate().unwrap_err();
16407        assert!(
16408            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16409                if path == "/api/./cart" && reason.contains("`.` segment")),
16410            "got {err:?}"
16411        );
16412    }
16413
16414    #[test]
16415    fn rejects_entrada_path_with_trailing_dot_segment() {
16416        // The bare `/.` and the trailing `/foo/.` are both rejected
16417        // by the Gateway API webhook; pinned separately so a future
16418        // narrowing that catches only the inner form surfaces here.
16419        let mut s = three_member_spec();
16420        s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
16421        let err = s.validate().unwrap_err();
16422        assert!(
16423            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16424                if path == "/api/." && reason.contains("`.` segment")),
16425            "got {err:?}"
16426        );
16427    }
16428
16429    #[test]
16430    fn rejects_entrada_path_with_parent_segment() {
16431        let mut s = three_member_spec();
16432        s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
16433        let err = s.validate().unwrap_err();
16434        assert!(
16435            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16436                if path == "/api/../etc" && reason.contains("`..` parent-segment")),
16437            "got {err:?}"
16438        );
16439    }
16440
16441    #[test]
16442    fn rejects_entrada_path_with_trailing_parent_segment() {
16443        // Trailing `/..` — symmetric arm of the parent-segment rule,
16444        // pinned separately so a future relaxation that only checks
16445        // the inner form (`/../`) surfaces here.
16446        let mut s = three_member_spec();
16447        s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
16448        let err = s.validate().unwrap_err();
16449        assert!(
16450            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16451                if path == "/api/.." && reason.contains("`..` parent-segment")),
16452            "got {err:?}"
16453        );
16454    }
16455
16456    #[test]
16457    fn rejects_entrada_path_too_long() {
16458        // 1025-byte path — one over the Gateway API HTTPPathMatch.value
16459        // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
16460        // ASCII-alphanumeric body so only the length rule fires.
16461        let mut s = three_member_spec();
16462        let big = format!("/api/{}", "a".repeat(1020));
16463        assert_eq!(big.len(), 1025);
16464        s.entrada.as_mut().unwrap().paths = vec![big.clone()];
16465        let err = s.validate().unwrap_err();
16466        assert!(
16467            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16468                if path == &big && reason.contains("max length of 1024")),
16469            "got {err:?}"
16470        );
16471    }
16472
16473    #[test]
16474    fn entrada_path_max_length_validates() {
16475        // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
16476        // maxLength cap. Boundary pin: drift in the cap surfaces here
16477        // and at `rejects_entrada_path_too_long` simultaneously.
16478        let mut s = three_member_spec();
16479        let big = format!("/api/{}", "a".repeat(1019));
16480        assert_eq!(big.len(), 1024);
16481        s.entrada.as_mut().unwrap().paths = vec![big];
16482        s.validate().unwrap();
16483    }
16484
16485    #[test]
16486    fn entrada_accepts_canonical_paths() {
16487        // Positive-control sweep — every form the Gateway API
16488        // apiserver accepts must round-trip through validate. Covers
16489        // the root catch-all, plain paths, dot-prefixed segments
16490        // (hidden-file-style, distinct from `.` and `..` segments
16491        // which are rejected), digit-bearing segments, the canonical
16492        // route-template `:param` form (`:` is RFC 3986 reserved-set
16493        // valid in paths), trailing-slash form, percent-encoded
16494        // segments, and an interior `..` *substring* (`/foo..bar` is
16495        // not the `..` segment and is allowed).
16496        for path in [
16497            "/",
16498            "/api/cart",
16499            "/healthz",
16500            "/api/.config",
16501            "/v1/products",
16502            "/products/:id",
16503            "/api/cart/",
16504            "/api/caf%C3%A9",
16505            "/foo..bar",
16506            "/...",
16507        ] {
16508            let mut s = three_member_spec();
16509            s.entrada.as_mut().unwrap().paths = vec![path.into()];
16510            s.validate()
16511                .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
16512        }
16513    }
16514
16515    #[test]
16516    fn entrada_path_empty_takes_precedence_over_invalid() {
16517        // Ordering pin: `EntradaPathEmpty` is the more self-locating
16518        // diagnostic on `""` and must lead — `validate_entrada_path`
16519        // is only reached after the empty-check fires at the call
16520        // site. (The predicate itself defends against direct
16521        // invocation by returning the same error on `""`.)
16522        let mut s = three_member_spec();
16523        s.entrada.as_mut().unwrap().paths = vec![String::new()];
16524        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
16525    }
16526
16527    #[test]
16528    fn entrada_path_not_absolute_takes_precedence_over_invalid() {
16529        // Ordering pin: a path without a leading `/` surfaces the
16530        // narrower `EntradaPathNotAbsolute` diagnostic first; the
16531        // value-shape gate is only consulted on paths that already
16532        // satisfy the absolute-prefix invariant.
16533        let mut s = three_member_spec();
16534        // `bad path` would fire the whitespace rule under the
16535        // value-shape gate, but missing-leading-`/` is the more
16536        // self-locating diagnostic.
16537        s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
16538        let err = s.validate().unwrap_err();
16539        assert!(
16540            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
16541            "got {err:?}"
16542        );
16543    }
16544
16545    #[test]
16546    fn entrada_path_invalid_fires_before_duplicate_check() {
16547        // Ordering pin: a malformed path on the *first* entry of a
16548        // would-be duplicate pair fires the value-shape gate before
16549        // the duplicate gate, mirroring the
16550        // `placement_cluster_invalid_fires_before_duplicate_check`
16551        // (6cbb900) pattern on the peer axis.
16552        let mut s = three_member_spec();
16553        s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
16554        let err = s.validate().unwrap_err();
16555        assert!(
16556            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
16557            "got {err:?}"
16558        );
16559    }
16560
16561    #[test]
16562    fn entrada_path_diagnostic_carries_offending_path() {
16563        // Diagnostic-shape pin — the offending path + a non-empty
16564        // reason flow through verbatim so the author can grep their
16565        // caixa.lisp for `:paths` and fix it in one edit. Same shape
16566        // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
16567        let mut s = three_member_spec();
16568        s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
16569        let err = s.validate().unwrap_err();
16570        match err {
16571            AplicacaoError::EntradaPathInvalid { path, reason } => {
16572                assert_eq!(path, "/api?q=1");
16573                assert!(!reason.is_empty(), "reason field must be non-empty");
16574            }
16575            other => panic!("expected EntradaPathInvalid, got {other:?}"),
16576        }
16577    }
16578
16579    #[test]
16580    fn rejects_entrada_path_with_curly_brace_template_form() {
16581        // Per-axis pin on the shared `is_gateway_api_http_path`
16582        // reserved-byte arm: the canonical "I wrote an OpenAPI
16583        // path-template `{id}` instead of the Gateway API `:id` form"
16584        // footgun the K8s apiserver would otherwise catch at admission
16585        // time on every `HTTPRoute.spec.rules[].matches[].path.value`
16586        // landing site, far from the caixa.lisp. Surfaces as
16587        // `EntradaPathInvalid` carrying the offending path verbatim
16588        // plus the canonical `%7B`/`%7D` percent-encoding remediation
16589        // — the substrate-side `gateway_api_http_path_rejects_every_
16590        // reserved_printable_ascii_byte` predicate-level sweep pins the
16591        // full eleven-byte set; this per-axis pin confirms the
16592        // diagnostic flows through to the `EntradaPathInvalid` variant.
16593        let mut s = three_member_spec();
16594        s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
16595        let err = s.validate().unwrap_err();
16596        assert!(
16597            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16598                if path == "/api/cart/{id}"
16599                    && reason.contains("reserved character")
16600                    && reason.contains("'{'")
16601                    && reason.contains("%7B")),
16602            "got {err:?}"
16603        );
16604    }
16605
16606    #[test]
16607    fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
16608        // Per-axis peer of `rejects_entrada_path_with_curly_brace_
16609        // template_form` on the sibling `:contratos :endpoint` axis.
16610        // Same shared `is_gateway_api_http_path` reserved-byte arm
16611        // fires through `ContratoEndpointInvalid`, with the offending
16612        // endpoint + `:de` + `:para` + reason flowing through verbatim.
16613        // Pins that the lifted predicate's tightening lands on both
16614        // caller axes simultaneously — one source of truth for the
16615        // Gateway API HTTPPathMatch.value accepted set.
16616        let err = contrato_endpoint_err("/api/cart/{id}");
16617        assert!(
16618            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
16619                if endpoint == "/api/cart/{id}"
16620                    && reason.contains("reserved character")
16621                    && reason.contains("'{'")
16622                    && reason.contains("%7B")),
16623            "got {err:?}"
16624        );
16625    }
16626
16627    // ── :entrada :host value-shape gate ──────────────────────────────
16628    //
16629    // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
16630    // the sibling `:host` axis. Every authoring footgun the K8s
16631    // Gateway API v1 apiserver would catch at admission time becomes
16632    // a caixa-build-time `EntradaHostInvalid` with the offending
16633    // `:host` named verbatim. Same diagnostic shape as
16634    // `MembroVersaoInvalid` (9888b13).
16635
16636    #[test]
16637    fn rejects_entrada_host_with_scheme() {
16638        // Fail-before-pass-after pin — pre-gate codebases silently
16639        // accepted `https://…` and the apiserver rejected it at apply
16640        // time with no source citation.
16641        let mut s = three_member_spec();
16642        s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
16643        let err = s.validate().unwrap_err();
16644        assert!(
16645            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
16646                if host == "https://checkout.quero.cloud"),
16647            "got {err:?}"
16648        );
16649    }
16650
16651    #[test]
16652    fn rejects_entrada_host_with_port() {
16653        // The `:8080` port suffix is the canonical "I forgot the port
16654        // belongs in `:entrada :port`" footgun. The top-level `:` arm
16655        // (introduced after the per-label loop-only impl silently
16656        // surfaced a deep "label \"cloud:8080\" contains invalid
16657        // character ':'" leak) names the canonical fix verbatim — the
16658        // `:entrada :port` slot.
16659        let mut s = three_member_spec();
16660        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
16661        let err = s.validate().unwrap_err();
16662        assert!(
16663            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
16664                if host == "checkout.quero.cloud:8080"
16665                && reason.contains(":entrada :port")),
16666            "got {err:?}"
16667        );
16668    }
16669
16670    #[test]
16671    fn rejects_entrada_host_with_trailing_colon() {
16672        // Trailing `:` (e.g. an in-progress `:host "example.com:"`
16673        // edit) — the per-label loop would land it as a deep
16674        // "label \"com:\" must start and end with an alphanumeric"
16675        // / "contains invalid character ':'" leak. The top-level
16676        // `:` arm pre-empts with the canonical `:port` slot
16677        // diagnostic.
16678        let mut s = three_member_spec();
16679        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
16680        let err = s.validate().unwrap_err();
16681        assert!(
16682            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
16683                if host == "checkout.quero.cloud:"
16684                && reason.contains(":entrada :port")),
16685            "got {err:?}"
16686        );
16687    }
16688
16689    #[test]
16690    fn rejects_entrada_host_unbracketed_ipv6_literal() {
16691        // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
16692        // literals across the board (peer with `rejects_entrada_host_
16693        // ipv4_literal` above for the four-label-all-digit IPv4 arm).
16694        // Before this top-level `:` arm landed the per-label loop
16695        // surfaced a single-label byte-class diagnostic that named the
16696        // `:` byte but not the IP-literal prohibition. The top-level
16697        // `:` arm names both the `:port` slot and the IP-literal
16698        // prohibition verbatim, so an author whose `:host "2001:..."`
16699        // value lands here gets a self-locating fix either way.
16700        let mut s = three_member_spec();
16701        s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
16702        let err = s.validate().unwrap_err();
16703        assert!(
16704            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
16705                if host == "2001:db8::1"
16706                && reason.contains("IPv6")),
16707            "got {err:?}"
16708        );
16709    }
16710
16711    #[test]
16712    fn rejects_entrada_host_wildcard_with_port() {
16713        // Wildcard host with port suffix — the `*.` strip and the
16714        // per-label loop on `["foo", "quero", "cloud:8080"]` would
16715        // surface the deep byte-class leak. The top-level `:` arm sits
16716        // upstream of the `*.` strip, so it names the canonical `:port`
16717        // fix verbatim regardless of whether the host is wildcard-led.
16718        let mut s = three_member_spec();
16719        s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
16720        let err = s.validate().unwrap_err();
16721        assert!(
16722            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
16723                if host == "*.quero.cloud:8080"
16724                && reason.contains(":entrada :port")),
16725            "got {err:?}"
16726        );
16727    }
16728
16729    #[test]
16730    fn rejects_entrada_host_with_path() {
16731        let mut s = three_member_spec();
16732        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
16733        let err = s.validate().unwrap_err();
16734        assert!(
16735            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
16736                if host == "checkout.quero.cloud/api"),
16737            "got {err:?}"
16738        );
16739    }
16740
16741    #[test]
16742    fn rejects_entrada_host_with_uppercase() {
16743        // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
16744        // rejected, not silently lower-cased.
16745        let mut s = three_member_spec();
16746        s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
16747        let err = s.validate().unwrap_err();
16748        assert!(
16749            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16750                if reason.contains("uppercase")),
16751            "got {err:?}"
16752        );
16753    }
16754
16755    #[test]
16756    fn rejects_entrada_host_with_underscore() {
16757        // RFC 1123 allows `[a-z0-9-]` only; underscore is the
16758        // canonical "I'm thinking of HTTP cookies / SRV records" leak.
16759        let mut s = three_member_spec();
16760        s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
16761        let err = s.validate().unwrap_err();
16762        assert!(
16763            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16764                if reason.contains('_')),
16765            "got {err:?}"
16766        );
16767    }
16768
16769    #[test]
16770    fn rejects_entrada_host_ipv4_literal() {
16771        // Gateway API v1 explicitly forbids IP literals as Hostnames.
16772        let mut s = three_member_spec();
16773        s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
16774        let err = s.validate().unwrap_err();
16775        assert!(
16776            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16777                if reason.contains("IPv4")),
16778            "got {err:?}"
16779        );
16780    }
16781
16782    #[test]
16783    fn rejects_entrada_host_with_trailing_dot() {
16784        // The Gateway API regex anchors at end-of-string with no
16785        // trailing `.` allowance — the FQDN root-dot form is rejected.
16786        let mut s = three_member_spec();
16787        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
16788        let err = s.validate().unwrap_err();
16789        assert!(
16790            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
16791                if host == "checkout.quero.cloud."),
16792            "got {err:?}"
16793        );
16794    }
16795
16796    #[test]
16797    fn rejects_entrada_host_with_leading_dot() {
16798        let mut s = three_member_spec();
16799        s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
16800        let err = s.validate().unwrap_err();
16801        assert!(
16802            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16803                if reason.contains("empty label")),
16804            "got {err:?}"
16805        );
16806    }
16807
16808    #[test]
16809    fn rejects_entrada_host_with_consecutive_dots() {
16810        let mut s = three_member_spec();
16811        s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
16812        let err = s.validate().unwrap_err();
16813        assert!(
16814            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16815                if reason.contains("empty label")),
16816            "got {err:?}"
16817        );
16818    }
16819
16820    #[test]
16821    fn rejects_entrada_host_with_leading_hyphen_label() {
16822        let mut s = three_member_spec();
16823        s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
16824        let err = s.validate().unwrap_err();
16825        assert!(
16826            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16827                if reason.contains("alphanumeric")),
16828            "got {err:?}"
16829        );
16830    }
16831
16832    #[test]
16833    fn rejects_entrada_host_with_trailing_hyphen_label() {
16834        let mut s = three_member_spec();
16835        s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
16836        let err = s.validate().unwrap_err();
16837        assert!(
16838            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16839                if reason.contains("alphanumeric")),
16840            "got {err:?}"
16841        );
16842    }
16843
16844    #[test]
16845    fn rejects_entrada_host_with_inner_wildcard() {
16846        // Gateway API allows `*` only as the first label (`*.foo`);
16847        // any inner or trailing `*` is rejected.
16848        let mut s = three_member_spec();
16849        s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
16850        let err = s.validate().unwrap_err();
16851        assert!(
16852            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16853                if reason.contains("wildcard")),
16854            "got {err:?}"
16855        );
16856    }
16857
16858    #[test]
16859    fn rejects_entrada_host_bare_wildcard() {
16860        // `*.` with no domain is meaningless; Gateway API rejects it.
16861        let mut s = three_member_spec();
16862        s.entrada.as_mut().unwrap().host = "*.".into();
16863        let err = s.validate().unwrap_err();
16864        assert!(
16865            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16866                if reason.contains("wildcard")),
16867            "got {err:?}"
16868        );
16869    }
16870
16871    #[test]
16872    fn rejects_entrada_host_with_whitespace() {
16873        let mut s = three_member_spec();
16874        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
16875        let err = s.validate().unwrap_err();
16876        assert!(
16877            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16878                if reason.contains("whitespace")),
16879            "got {err:?}"
16880        );
16881    }
16882
16883    #[test]
16884    fn rejects_entrada_host_space_names_offending_byte() {
16885        // Embedded space in the `:entrada :host` axis surfaces the
16886        // byte-naming diagnostic through the lifted
16887        // `find_ascii_whitespace_byte` predicate. Peer with the
16888        // sibling `parse_rejects_leading_whitespace` pins on
16889        // `supervisor::duration_codec` (a7ae622) — same "the
16890        // diagnostic carries the offending byte's `0x{b:02x}` shape"
16891        // discipline extended from the shared duration codec to the
16892        // Gateway API v1 Hostname axis.
16893        let mut s = three_member_spec();
16894        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
16895        let err = s.validate().unwrap_err();
16896        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
16897            panic!("expected EntradaHostInvalid, got {err:?}");
16898        };
16899        assert!(
16900            reason.contains("ASCII whitespace byte"),
16901            "expected byte-naming diagnostic, got {reason:?}"
16902        );
16903        assert!(
16904            reason.contains("0x20"),
16905            "expected offending space byte 0x20, got {reason:?}"
16906        );
16907    }
16908
16909    #[test]
16910    fn rejects_entrada_host_tab_names_offending_byte() {
16911        // Embedded tab byte in the `:entrada :host` axis — the
16912        // canonical paste-from-YAML-block-scalar / paste-from-
16913        // indented-doc footgun. Pins that the lifted predicate covers
16914        // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
16915        // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
16916        // not just the leading-space case the pre-lift `.bytes().any`
16917        // arm's opaque "must not contain whitespace" reason already
16918        // covered. Peer with `parse_rejects_tab_byte` on
16919        // `supervisor::duration_codec` (a7ae622).
16920        let mut s = three_member_spec();
16921        s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
16922        let err = s.validate().unwrap_err();
16923        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
16924            panic!("expected EntradaHostInvalid, got {err:?}");
16925        };
16926        assert!(
16927            reason.contains("ASCII whitespace byte"),
16928            "expected byte-naming diagnostic, got {reason:?}"
16929        );
16930        assert!(
16931            reason.contains("0x09"),
16932            "expected offending tab byte 0x09, got {reason:?}"
16933        );
16934    }
16935
16936    #[test]
16937    fn rejects_entrada_host_lf_names_offending_byte() {
16938        // Embedded LF byte in the `:entrada :host` axis — the
16939        // canonical paste-from-shell-heredoc / paste-from-multiline-
16940        // doc footgun the caixa-mesh YAML emitter would silently
16941        // reinterpret at the Gateway API v1 HTTPRoute admission
16942        // layer (an embedded LF byte in a YAML plain scalar either
16943        // truncates the value at the emitter or crashes the parser
16944        // on the k8s-apiserver side). Pins the third representative
16945        // of the full ASCII-whitespace set through the shared
16946        // predicate.
16947        let mut s = three_member_spec();
16948        s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
16949        let err = s.validate().unwrap_err();
16950        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
16951            panic!("expected EntradaHostInvalid, got {err:?}");
16952        };
16953        assert!(
16954            reason.contains("ASCII whitespace byte"),
16955            "expected byte-naming diagnostic, got {reason:?}"
16956        );
16957        assert!(
16958            reason.contains("0x0a"),
16959            "expected offending LF byte 0x0a, got {reason:?}"
16960        );
16961    }
16962
16963    #[test]
16964    fn rejects_entrada_host_nbsp_names_offending_codepoint() {
16965        // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
16966        // axis — the canonical paste-from-typography /
16967        // paste-from-word-processor footgun. Before the non-ASCII
16968        // Unicode `White_Space` scan lifted through the shared
16969        // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
16970        // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
16971        // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
16972        // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
16973        // with the far-from-source `label "…" must start and end
16974        // with an alphanumeric` diagnostic — burying the
16975        // paste-from-typography origin under a label-shape leak.
16976        // Peer with the sibling non-ASCII-whitespace pins at
16977        // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
16978        // — 1b75b38), `limits::parse_duration`,
16979        // `limits::parse_millicores`, and the shared duration codec
16980        // — same "the diagnostic carries the offending Unicode
16981        // codepoint's `U+XXXX` shape" discipline extended from every
16982        // typed-magnitude codec to the Gateway API v1 Hostname axis.
16983        let mut s = three_member_spec();
16984        s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
16985        let err = s.validate().unwrap_err();
16986        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
16987            panic!("expected EntradaHostInvalid, got {err:?}");
16988        };
16989        assert!(
16990            reason.contains("non-ASCII Unicode whitespace character"),
16991            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
16992        );
16993        assert!(
16994            reason.contains("U+00A0"),
16995            "expected offending NBSP codepoint U+00A0, got {reason:?}"
16996        );
16997    }
16998
16999    #[test]
17000    fn rejects_entrada_host_line_separator_names_offending_codepoint() {
17001        // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
17002        // `:entrada :host` axis — the canonical paste-from-web-doc /
17003        // paste-from-published-HTML footgun. `char::is_whitespace`
17004        // returns true for `U+2028` per the Unicode `White_Space`
17005        // property, so `str::trim` at any downstream site would
17006        // silently strip it — same drift class as NBSP but on a
17007        // different codepoint region. Pins the second representative
17008        // (non-Latin-1 `char::is_whitespace` member) through the
17009        // shared predicate. Peer with
17010        // `parse_byte_size_rejects_internal_line_separator` on
17011        // `limits::parse_byte_size` (1b75b38).
17012        let mut s = three_member_spec();
17013        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
17014        let err = s.validate().unwrap_err();
17015        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
17016            panic!("expected EntradaHostInvalid, got {err:?}");
17017        };
17018        assert!(
17019            reason.contains("non-ASCII Unicode whitespace character"),
17020            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
17021        );
17022        assert!(
17023            reason.contains("U+2028"),
17024            "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
17025        );
17026    }
17027
17028    #[test]
17029    fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
17030        // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
17031        // labels in the `:entrada :host` axis — the canonical
17032        // paste-from-CJK-typography footgun (CJK IMEs default to
17033        // full-width whitespace when the space bar is pressed in
17034        // Japanese / Chinese input modes). Pins the third
17035        // representative of the non-ASCII Unicode `White_Space` set
17036        // through the shared predicate: the CJK block, distinct from
17037        // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
17038        // SEPARATOR `U+2028` — covering the same axis breadth the
17039        // sibling `parse_byte_size_rejects_trailing_ideographic_space`
17040        // (1b75b38) pins on `limits::parse_byte_size`.
17041        let mut s = three_member_spec();
17042        s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
17043        let err = s.validate().unwrap_err();
17044        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
17045            panic!("expected EntradaHostInvalid, got {err:?}");
17046        };
17047        assert!(
17048            reason.contains("non-ASCII Unicode whitespace character"),
17049            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
17050        );
17051        assert!(
17052            reason.contains("U+3000"),
17053            "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
17054        );
17055    }
17056
17057    #[test]
17058    fn rejects_entrada_host_too_long() {
17059        // Total length cap = 253; build a 254-byte host out of two
17060        // 63-byte labels + one 62-byte label + dots.
17061        let mut s = three_member_spec();
17062        let big = format!(
17063            "{}.{}.{}.{}",
17064            "a".repeat(63),
17065            "b".repeat(63),
17066            "c".repeat(63),
17067            "d".repeat(254 - 63 * 3 - 3)
17068        );
17069        assert_eq!(big.len(), 254);
17070        s.entrada.as_mut().unwrap().host = big;
17071        let err = s.validate().unwrap_err();
17072        assert!(
17073            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17074                if reason.contains("max length of 253")),
17075            "got {err:?}"
17076        );
17077    }
17078
17079    #[test]
17080    fn rejects_entrada_host_label_too_long() {
17081        let mut s = three_member_spec();
17082        // 64-byte label — one over the per-label cap.
17083        s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
17084        let err = s.validate().unwrap_err();
17085        assert!(
17086            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17087                if reason.contains("label max length of 63")),
17088            "got {err:?}"
17089        );
17090    }
17091
17092    #[test]
17093    fn entrada_host_diagnostic_carries_offending_host() {
17094        // Diagnostic-shape pin — the offending host + a non-empty
17095        // reason flow through verbatim so the author can grep their
17096        // caixa.lisp for `:host "<host>"` and fix it in one edit.
17097        let mut s = three_member_spec();
17098        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
17099        let err = s.validate().unwrap_err();
17100        match err {
17101            AplicacaoError::EntradaHostInvalid { host, reason } => {
17102                assert_eq!(host, "checkout.quero.cloud:8080");
17103                assert!(!reason.is_empty(), "reason field must be non-empty");
17104            }
17105            other => panic!("expected EntradaHostInvalid, got {other:?}"),
17106        }
17107    }
17108
17109    // Equivalence pin for the [`AplicacaoError::entrada_host_invalid`]
17110    // substrate primitive that folds the fourteen
17111    // `AplicacaoError::EntradaHostInvalid { host: host.to_string(),
17112    // reason: <expr> }` wire-up sites at [`validate_entrada_host`] onto
17113    // one dispatch — peer with the sixteen equivalence pins the
17114    // [`crate::LayoutError`] `_violation` constructor family carries in
17115    // `layout::tests::*_ctor_matches_struct_literal_wrap` (131ca0d). The
17116    // fixture host + reason are fixed `&'static str`s so both fields of
17117    // both constructed variants pin verbatim: the `host` axis is pinned
17118    // through the shared `host.to_string()` wrap (the ctor's uniform
17119    // one-slot construction) and the `reason` axis is pinned through
17120    // the shared `reason.into()` wrap (the ctor's `impl Into<String>`
17121    // routing). Any future regression on the lift (an extra field
17122    // introduced without updating the ctor, a diverging string
17123    // conversion at either arm) surfaces at this pin's diagnostic
17124    // rather than at a per-wire-up struct-literal reintroduction.
17125    #[test]
17126    fn entrada_host_invalid_ctor_matches_struct_literal_wrap() {
17127        let host = "checkout.quero.cloud:8080";
17128        let reason = "sample reason text";
17129        assert_eq!(
17130            AplicacaoError::entrada_host_invalid(host, reason),
17131            AplicacaoError::EntradaHostInvalid {
17132                host: host.to_string(),
17133                reason: reason.to_string(),
17134            },
17135            "generated constructor must produce byte-equal AplicacaoError to open-coded struct-literal wrap",
17136        );
17137    }
17138
17139    // Routing pin — the ctor's `host: &str` argument threads through
17140    // `.to_string()` verbatim on the `host` field, so the constructed
17141    // variant carries the offending host bytes without any wrapper-
17142    // side transformation (no `.to_ascii_lowercase()` normalization,
17143    // no `.trim()` strip, no truncation) — the same "diagnostic carries
17144    // the offending value verbatim so the author can grep their
17145    // caixa.lisp" discipline every peer typed-slot ctor at this
17146    // altitude carries.
17147    #[test]
17148    fn entrada_host_invalid_ctor_routes_host_through_to_string() {
17149        // Uppercase + trailing whitespace + port suffix — three
17150        // wrapper-side transformations the ctor must *not* apply.
17151        let host = " Checkout.quero.CLOUD:8080 ";
17152        let err = AplicacaoError::entrada_host_invalid(host, "sample");
17153        match err {
17154            AplicacaoError::EntradaHostInvalid { host: h, .. } => {
17155                assert_eq!(h, host, "host must thread through `.to_string()` verbatim");
17156            }
17157            other => panic!("expected EntradaHostInvalid, got {other:?}"),
17158        }
17159    }
17160
17161    // Routing pin — the ctor's `reason: impl Into<String>` accepts both
17162    // `&str` literals and `format!(…)` outputs identically and both
17163    // route through `Into::into` verbatim onto the `reason` field.
17164    // Pins both codepaths against the same host to prove the two
17165    // shapes the fourteen wire-up sites use at their per-arm diagnostic
17166    // (ten `&str` literals — some with `.to_string()` at the caller,
17167    // some without — plus four `format!(…)` outputs) each produce
17168    // byte-equal `reason` fields against the same offending host.
17169    #[test]
17170    fn entrada_host_invalid_ctor_routes_reason_through_into() {
17171        let host = "checkout.quero.cloud";
17172        // `&str` literal — the ctor's `impl Into<String>` accepts it
17173        // without a caller-side `.to_string()`.
17174        let from_literal = AplicacaoError::entrada_host_invalid(host, "literal reason text");
17175        // Owned `String` from `format!` — the peer `format!(…)`-shaped
17176        // wire-up arm.
17177        let from_format =
17178            AplicacaoError::entrada_host_invalid(host, format!("{} reason text", "literal"));
17179        // `String` from `.to_string()` on a literal — the peer
17180        // `"literal".to_string()`-shaped wire-up arm the pre-lift
17181        // sites carried.
17182        let from_to_string =
17183            AplicacaoError::entrada_host_invalid(host, "literal reason text".to_string());
17184        match (&from_literal, &from_format, &from_to_string) {
17185            (
17186                AplicacaoError::EntradaHostInvalid {
17187                    reason: r_lit,
17188                    host: h_lit,
17189                },
17190                AplicacaoError::EntradaHostInvalid {
17191                    reason: r_fmt,
17192                    host: h_fmt,
17193                },
17194                AplicacaoError::EntradaHostInvalid {
17195                    reason: r_ts,
17196                    host: h_ts,
17197                },
17198            ) => {
17199                assert_eq!(r_lit, "literal reason text");
17200                assert_eq!(r_fmt, "literal reason text");
17201                assert_eq!(r_ts, "literal reason text");
17202                assert_eq!(h_lit, host);
17203                assert_eq!(h_fmt, host);
17204                assert_eq!(h_ts, host);
17205            }
17206            _ => panic!("expected three EntradaHostInvalid variants"),
17207        }
17208        // Cross-arm equivalence — the three shapes must produce
17209        // byte-equal `AplicacaoError` values, so the fourteen wire-up
17210        // sites' mixed per-arm shapes fold onto one canonical form.
17211        assert_eq!(from_literal, from_format);
17212        assert_eq!(from_literal, from_to_string);
17213    }
17214
17215    // Equivalence pins for the six sibling
17216    // [`aplicacao_field_reason_ctors!`]-generated constructors that
17217    // fold the peer `{ <field>: String, reason: String }` variants
17218    // onto the same substrate-primitive family
17219    // `entrada_host_invalid` (17dd504) already carries pins for.
17220    // Each ctor's fixture pair (a fixed `&'static str` value and a
17221    // fixed `&'static str` reason) pins both fields verbatim so any
17222    // future regression on the macro (an extra field introduced
17223    // without updating the macro, a diverging string conversion at
17224    // either arm, a field-name typo on one variant that dropped it
17225    // off the shared shape) surfaces at the affected variant's pin
17226    // rather than at a per-wire-up struct-literal reintroduction. Peer
17227    // discipline of the sixteen `LayoutError` _violation ctor pins in
17228    // `layout::tests::*_ctor_matches_struct_literal_wrap` (131ca0d)
17229    // and the paired
17230    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
17231    // `contrato_missing_target_ctor_matches_struct_literal_wrap`
17232    // (14b81d5) / `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
17233    // (8580068) equivalence pins on the sibling `AplicacaoError`
17234    // ctor macros.
17235    #[test]
17236    fn membro_caixa_invalid_ctor_matches_struct_literal_wrap() {
17237        let caixa = "cart-svc";
17238        let reason = "sample reason text";
17239        assert_eq!(
17240            AplicacaoError::membro_caixa_invalid(caixa, reason),
17241            AplicacaoError::MembroCaixaInvalid {
17242                caixa: caixa.to_string(),
17243                reason: reason.to_string(),
17244            },
17245        );
17246    }
17247
17248    #[test]
17249    fn entrada_para_invalid_ctor_matches_struct_literal_wrap() {
17250        let para = "checkout";
17251        let reason = "sample reason text";
17252        assert_eq!(
17253            AplicacaoError::entrada_para_invalid(para, reason),
17254            AplicacaoError::EntradaParaInvalid {
17255                para: para.to_string(),
17256                reason: reason.to_string(),
17257            },
17258        );
17259    }
17260
17261    #[test]
17262    fn entrada_path_invalid_ctor_matches_struct_literal_wrap() {
17263        let path = "/api/cart";
17264        let reason = "sample reason text";
17265        assert_eq!(
17266            AplicacaoError::entrada_path_invalid(path, reason),
17267            AplicacaoError::EntradaPathInvalid {
17268                path: path.to_string(),
17269                reason: reason.to_string(),
17270            },
17271        );
17272    }
17273
17274    #[test]
17275    fn placement_cluster_invalid_ctor_matches_struct_literal_wrap() {
17276        let cluster = "rio";
17277        let reason = "sample reason text";
17278        assert_eq!(
17279            AplicacaoError::placement_cluster_invalid(cluster, reason),
17280            AplicacaoError::PlacementClusterInvalid {
17281                cluster: cluster.to_string(),
17282                reason: reason.to_string(),
17283            },
17284        );
17285    }
17286
17287    #[test]
17288    fn placement_affinity_invalid_ctor_matches_struct_literal_wrap() {
17289        let affinity = "data-locality";
17290        let reason = "sample reason text";
17291        assert_eq!(
17292            AplicacaoError::placement_affinity_invalid(affinity, reason),
17293            AplicacaoError::PlacementAffinityInvalid {
17294                affinity: affinity.to_string(),
17295                reason: reason.to_string(),
17296            },
17297        );
17298    }
17299
17300    #[test]
17301    fn shard_key_invalid_ctor_matches_struct_literal_wrap() {
17302        let shard_key = "tenantId";
17303        let reason = "sample reason text";
17304        assert_eq!(
17305            AplicacaoError::shard_key_invalid(shard_key, reason),
17306            AplicacaoError::ShardKeyInvalid {
17307                shard_key: shard_key.to_string(),
17308                reason: reason.to_string(),
17309            },
17310        );
17311    }
17312
17313    // Cross-family invariance pin — the six sibling ctors and
17314    // `entrada_host_invalid` all route `reason: impl Into<String>` +
17315    // `<field>: &str` verbatim onto their respective typed variants
17316    // through the shared [`aplicacao_field_reason_ctors!`] macro.
17317    // Sweeps a fixture pair (`&str` literal, `format!` output) against
17318    // every ctor to pin that no per-arm wrapper transformation drifted
17319    // in against the uniform macro-generated body.
17320    #[test]
17321    fn aplicacao_field_reason_ctors_route_reason_through_into_uniformly() {
17322        let via_literal = "literal reason text";
17323        let via_format = format!("{} reason text", "literal");
17324        assert_eq!(
17325            AplicacaoError::membro_caixa_invalid("m", via_literal),
17326            AplicacaoError::membro_caixa_invalid("m", via_format.clone()),
17327        );
17328        assert_eq!(
17329            AplicacaoError::entrada_para_invalid("p", via_literal),
17330            AplicacaoError::entrada_para_invalid("p", via_format.clone()),
17331        );
17332        assert_eq!(
17333            AplicacaoError::entrada_path_invalid("/a", via_literal),
17334            AplicacaoError::entrada_path_invalid("/a", via_format.clone()),
17335        );
17336        assert_eq!(
17337            AplicacaoError::placement_cluster_invalid("c", via_literal),
17338            AplicacaoError::placement_cluster_invalid("c", via_format.clone()),
17339        );
17340        assert_eq!(
17341            AplicacaoError::placement_affinity_invalid("a", via_literal),
17342            AplicacaoError::placement_affinity_invalid("a", via_format.clone()),
17343        );
17344        assert_eq!(
17345            AplicacaoError::shard_key_invalid("k", via_literal),
17346            AplicacaoError::shard_key_invalid("k", via_format.clone()),
17347        );
17348        assert_eq!(
17349            AplicacaoError::entrada_host_invalid("h", via_literal),
17350            AplicacaoError::entrada_host_invalid("h", via_format),
17351        );
17352    }
17353
17354    #[test]
17355    fn entrada_host_empty_takes_precedence_over_invalid() {
17356        // Ordering pin: `EmptyEntradaHost` is the more self-locating
17357        // diagnostic on `""` and must lead — `validate_entrada_host`
17358        // is only reached after the empty-check fires at the call
17359        // site. (The predicate itself defends against direct
17360        // invocation by returning the same error on `""`.)
17361        let mut s = three_member_spec();
17362        s.entrada.as_mut().unwrap().host = String::new();
17363        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
17364    }
17365
17366    #[test]
17367    fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
17368        // Ordering pin: a missing :para member is the more
17369        // self-locating diagnostic and fires before the host gate.
17370        let mut s = three_member_spec();
17371        let e = s.entrada.as_mut().unwrap();
17372        e.para = "ghost".into();
17373        e.host = "BAD HOST".into();
17374        let err = s.validate().unwrap_err();
17375        assert!(
17376            matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
17377            "got {err:?}"
17378        );
17379    }
17380
17381    #[test]
17382    fn entrada_host_invalid_fires_before_port_zero() {
17383        // Ordering pin: the host gate fires before the port gate so
17384        // a malformed host is named even when the port is also wrong.
17385        let mut s = three_member_spec();
17386        let e = s.entrada.as_mut().unwrap();
17387        e.host = "Checkout.quero.cloud".into();
17388        e.port = 0;
17389        let err = s.validate().unwrap_err();
17390        assert!(
17391            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
17392                if host == "Checkout.quero.cloud"),
17393            "got {err:?}"
17394        );
17395    }
17396
17397    #[test]
17398    fn entrada_accepts_canonical_hosts() {
17399        // Positive-control sweep — every form the Gateway API
17400        // apiserver accepts must round-trip through validate. Covers
17401        // a plain DNS subdomain, a leading wildcard, a single-label
17402        // host (cluster-internal), a max-length-edge label, a
17403        // hyphen-bearing label, and a Punycode IDN label.
17404        for host in [
17405            "checkout.quero.cloud",
17406            "*.quero.cloud",
17407            "checkout",
17408            // 63-byte label — exactly the per-label cap.
17409            "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
17410            "foo-bar.quero.cloud",
17411            // Punycode IDN — valid because the author pre-encoded.
17412            "xn--bcher-kva.example.com",
17413        ] {
17414            let mut s = three_member_spec();
17415            s.entrada.as_mut().unwrap().host = host.into();
17416            s.validate()
17417                .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
17418        }
17419    }
17420
17421    #[test]
17422    fn entrada_host_max_length_validates() {
17423        // 253-byte host is the cap exactly — must validate. Build a
17424        // 253-byte host out of three 63-byte labels + one 61-byte
17425        // label + 3 dots = 252 bytes, then pad one byte to 253.
17426        let mut s = three_member_spec();
17427        let host = format!(
17428            "{}.{}.{}.{}",
17429            "a".repeat(63),
17430            "b".repeat(63),
17431            "c".repeat(63),
17432            "d".repeat(253 - 63 * 3 - 3)
17433        );
17434        assert_eq!(host.len(), 253);
17435        s.entrada.as_mut().unwrap().host = host;
17436        s.validate().unwrap();
17437    }
17438
17439    #[test]
17440    fn entrada_host_total_length_cap_threads_lifted_render_const() {
17441        // Cross-crate-side pin: the aplicacao-side `:entrada :host`
17442        // total-length gate now reads the K8s Gateway API v1 Hostname
17443        // `maxLength: 253` cap from the lifted
17444        // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
17445        // of truth — the same constant every future Gateway-API-Hostname
17446        // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
17447        // materializer's per-host validator, the future per-`Certificate`
17448        // SAN emitter for cert-manager, the multi-`:entrada`
17449        // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
17450        // from. Before the lift, the aplicacao-side reader consumed a
17451        // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
17452        // 253-byte value as the peer render-side canonical bounds
17453        // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
17454        // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
17455        // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
17456        // module boundary — a future 253-byte drift on either side would
17457        // silently split into two axes' worth of admission-schema mismatch
17458        // without a build-time signal. Pin the cap through a fresh 254-
17459        // byte host that hits the total-length arm, then read the reason
17460        // for the exact byte count the shared constant carries: any future
17461        // regression on the lift (a private alias reintroduced, a hard-
17462        // coded literal at the arm, a mismatch between the aplicacao-side
17463        // and render-side canonicals) surfaces as this pin's diagnostic
17464        // failing to match, not as a per-cluster admission rejection far
17465        // from the caixa.lisp source line.
17466        let mut s = three_member_spec();
17467        let over_cap = format!(
17468            "{}.{}.{}.{}",
17469            "a".repeat(63),
17470            "b".repeat(63),
17471            "c".repeat(63),
17472            "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
17473        );
17474        assert_eq!(
17475            over_cap.len(),
17476            crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
17477        );
17478        s.entrada.as_mut().unwrap().host = over_cap;
17479        let err = s.validate().unwrap_err();
17480        match err {
17481            AplicacaoError::EntradaHostInvalid { reason, .. } => {
17482                let needle = format!(
17483                    "max length of {} bytes",
17484                    crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
17485                );
17486                assert!(
17487                    reason.contains(&needle),
17488                    "diagnostic must name the lifted \
17489                     GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
17490                );
17491            }
17492            other => panic!("expected EntradaHostInvalid, got {other:?}"),
17493        }
17494    }
17495
17496    #[test]
17497    fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
17498        // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
17499        // on the per-label-cap axis. Before the lift, the aplicacao-side
17500        // per-label arm consumed a private const alias
17501        // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
17502        // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
17503        // split from it at the module boundary — every `.`-separated
17504        // label in a Gateway API v1 Hostname is a DNS-1123 label under
17505        // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
17506        // so the private alias's 63 and the canonical const's 63 were
17507        // pinning the same underlying rule twice. Pin the cap through a
17508        // 64-byte label that hits the per-label arm, then read the reason
17509        // for the exact byte count the shared constant carries: any
17510        // future drift on either side (a private alias reintroduced, a
17511        // hard-coded literal at the arm, a mismatch between the two
17512        // 63-byte pins) surfaces at this pin's diagnostic rather than at
17513        // a per-cluster admission rejection whose "field is invalid"
17514        // opacity misframes the root cause.
17515        let mut s = three_member_spec();
17516        let over_cap_label = format!(
17517            "{}.quero.cloud",
17518            "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
17519        );
17520        s.entrada.as_mut().unwrap().host = over_cap_label;
17521        let err = s.validate().unwrap_err();
17522        match err {
17523            AplicacaoError::EntradaHostInvalid { reason, .. } => {
17524                let needle = format!(
17525                    "label max length of {} bytes",
17526                    crate::render::DNS_1123_LABEL_MAX_LEN,
17527                );
17528                assert!(
17529                    reason.contains(&needle),
17530                    "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
17531                     cap verbatim on the per-label arm, got: {reason:?}",
17532                );
17533            }
17534            other => panic!("expected EntradaHostInvalid, got {other:?}"),
17535        }
17536    }
17537
17538    #[test]
17539    fn entrada_with_empty_paths_validates() {
17540        // Empty `:paths` is the documented "match every path" form;
17541        // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
17542        let mut s = three_member_spec();
17543        s.entrada.as_mut().unwrap().paths = vec![];
17544        s.validate().unwrap();
17545    }
17546
17547    #[test]
17548    fn entrada_root_path_validates() {
17549        // The author-supplied bare-root `:entrada :paths` entry is the
17550        // same byte-shape the peer emit-side catch-all constant
17551        // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
17552        // the author's `:paths` list is empty — sweeping the test-side
17553        // probe literal onto the lifted const closes the two-axis pin
17554        // (author-side admit + emit-side canonical fallback) around
17555        // one `&'static str`, so a future rebrand of the catch-all
17556        // reaches both consumers by construction. Peer to
17557        // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
17558        // on the canonical-literal pin surface.
17559        let mut s = three_member_spec();
17560        s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
17561        s.validate().unwrap();
17562    }
17563
17564    #[test]
17565    fn placement_strategy_variants_round_trip() {
17566        for s in [
17567            PlacementStrategy::SingleNode,
17568            PlacementStrategy::Replicated,
17569            PlacementStrategy::Sharded,
17570        ] {
17571            let p = Placement {
17572                estrategia: s,
17573                clusters: vec!["rio".into()],
17574                affinity: None,
17575                // Route the paired `:shard-key` fixture-builder through the
17576                // typed cross-slot invariant predicate
17577                // [`PlacementStrategy::requires_shard_key`] rather than the
17578                // [`gen_platform::IsVariant`]-derived [`Self::is_sharded`]
17579                // arm-identity predicate — the two answer the same
17580                // question under today's closed accept-set but a future
17581                // arm addition that consumed `:shard-key` under a
17582                // non-`Sharded` name would silently mis-attach the
17583                // fixture's `:shard-key` if the builder read through the
17584                // arm-identity predicate. The cross-slot-invariant
17585                // predicate migrates through one caixa-core edit on any
17586                // future arm addition; the fixture keeps producing a
17587                // `validate()`-passing round-trip by construction.
17588                shard_key: if s.requires_shard_key() {
17589                    Some("$key".into())
17590                } else {
17591                    None
17592                },
17593            };
17594            let json = serde_json::to_string(&p).unwrap();
17595            let back: Placement = serde_json::from_str(&json).unwrap();
17596            assert_eq!(back, p);
17597        }
17598    }
17599
17600    #[test]
17601    fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
17602        // The fail-before-pass-after pin: pre-lift there was no
17603        // single-source binding between the [`PlacementStrategy`]
17604        // variant name the `Serialize` derive emits and the byte-
17605        // string every downstream cluster-side dispatcher (the
17606        // `lareira-fleet-programs` aggregator's per-entry strategy
17607        // branch, the future `app-operator` reconciler, the M3
17608        // Adaptive compression pass's per-strategy weighting) probes
17609        // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
17610        // future `#[serde(rename_all = "kebab-case")]` attribute on
17611        // the enum — or a variant rename in the source — would
17612        // silently rebrand the emitted scalar under one spelling
17613        // while every downstream dispatcher still probed the other,
17614        // with the failure surfacing at the aggregator's dispatch
17615        // step or the operator's reconcile posture (workloads coming
17616        // up under the `default()` `Replicated` arm rather than the
17617        // typed slot's declared strategy) far from the source
17618        // rebrand commit and with no field naming the drift. Pinning
17619        // the two paths (the `Serialize` derive's serialized string
17620        // AND the [`PlacementStrategy::as_str`] helper) to the same
17621        // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
17622        // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
17623        // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
17624        // makes any future drift on either endpoint fail here at
17625        // caixa-core build time.
17626        for (variant, expected) in [
17627            (
17628                PlacementStrategy::SingleNode,
17629                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
17630            ),
17631            (
17632                PlacementStrategy::Replicated,
17633                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
17634            ),
17635            (
17636                PlacementStrategy::Sharded,
17637                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
17638            ),
17639        ] {
17640            let json = serde_json::to_string(&variant).unwrap();
17641            assert_eq!(
17642                json,
17643                format!("\"{expected}\""),
17644                "PlacementStrategy::{variant:?} must serialize to {expected:?}"
17645            );
17646            assert_eq!(
17647                variant.as_str(),
17648                expected,
17649                "PlacementStrategy::{variant:?}.as_str() must return the lifted \
17650                 M3_PLACEMENT_ESTRATEGIA_* constant"
17651            );
17652        }
17653    }
17654
17655    #[test]
17656    fn m3_placement_estrategia_consts_are_pairwise_distinct() {
17657        // Cross-arm drift-detection pin on the M3
17658        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
17659        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
17660        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
17661        // scalar-value pentad: a future collapse of two canonical
17662        // variant byte-strings onto the same value (an accidental
17663        // copy-paste flip of
17664        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
17665        // read `"SingleNode"`, a per-arm rebrand that lands one const
17666        // without touching its paired peer) would silently reroute
17667        // every downstream operator's per-strategy dispatch onto the
17668        // sibling arm's reconcile branch and pass every
17669        // propagation-probe test that expected only the stale arm's
17670        // value — a `Replicated`-declared Aplicacao would come up
17671        // under the `SingleNode` primary-and-standby reconcile
17672        // posture, so every-cluster active-active workload would
17673        // silently collapse onto one-cluster-runs-at-a-time takeover
17674        // semantics against its declared strategy, with no field
17675        // naming the strategy-value drift root cause. Peer of the
17676        // sibling
17677        // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
17678        // (09ffb2d) /
17679        // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
17680        // (ccdf955) /
17681        // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
17682        // (d739850) distinctness pins on the sibling OTP-shape /
17683        // caixa-kind closed-set typed-enum discriminator axes — the
17684        // fourth (and structurally the M3 mesh-primitive-defining)
17685        // closed-set typed-enum axis to converge on the same
17686        // "pairwise-distinct-by-construction" discipline.
17687        //
17688        // Fail-before-pass-after locally verified by mutating
17689        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
17690        // also read `"SingleNode"` — this pin fires as expected;
17691        // restoring passes.
17692        let all = [
17693            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
17694            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
17695            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
17696        ];
17697        for (i, a) in all.iter().enumerate() {
17698            for (j, b) in all.iter().enumerate() {
17699                if i != j {
17700                    assert_ne!(
17701                        a, b,
17702                        "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
17703                         distinct — got duplicate {a:?} at indices {i} and {j}",
17704                    );
17705                }
17706            }
17707        }
17708    }
17709
17710    #[test]
17711    fn placement_strategy_display_routes_through_as_str_helper() {
17712        // The fail-before-pass-after pin: pre-lift the sibling
17713        // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
17714        // / [`crate::supervisor::RestartPolicy`] both carried a stable
17715        // [`std::fmt::Display`] surface via their
17716        // `#[discriminant(also_display)]` gen-platform derive, but
17717        // [`PlacementStrategy`] did not — every consumer reaching for
17718        // a strategy byte-string past the wire format had to pick
17719        // between three paths ([`PlacementStrategy::as_str`], the
17720        // `Serialize` derive's serialized string, or `format!("{v:?}")`
17721        // on the `Debug` derive), any two of which a future variant
17722        // rename or `#[serde(rename_all = "kebab-case")]` attribute
17723        // would silently desynchronize. Wiring [`std::fmt::Display`]
17724        // through [`PlacementStrategy::as_str`] closes the third path:
17725        // every `format!("{v}")` call reaches the same lifted
17726        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
17727        // and the [`PlacementStrategy::as_str`] helper already route
17728        // through, so a future variant rename lands at exactly one
17729        // place. Pin the routing here so a future
17730        // `impl std::fmt::Display for PlacementStrategy` reimplementation
17731        // that hand-rolls the arms instead of delegating to
17732        // [`PlacementStrategy::as_str`] fails at caixa-core build time.
17733        for variant in [
17734            PlacementStrategy::SingleNode,
17735            PlacementStrategy::Replicated,
17736            PlacementStrategy::Sharded,
17737        ] {
17738            assert_eq!(
17739                variant.to_string(),
17740                variant.as_str(),
17741                "PlacementStrategy::{variant:?} Display must route through \
17742                 PlacementStrategy::as_str (single source of truth: the lifted \
17743                 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
17744            );
17745        }
17746    }
17747
17748    #[test]
17749    fn placement_strategy_display_matches_serialized_wire_byte_string() {
17750        // The fail-before-pass-after pin on the second half of the
17751        // three-path convergence: `Display` (user-facing text) agrees
17752        // byte-for-byte with the `Serialize` derive's wire format
17753        // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
17754        // scalar) on every variant. Pre-lift the two paths were
17755        // structurally independent — a future
17756        // `#[serde(rename_all = "kebab-case")]` attribute on the enum
17757        // would silently rebrand the emitted wire scalar
17758        // (`single-node`, `replicated`, `sharded`) while every consumer
17759        // that pretty-prints the strategy (the M3 diagnostic templates,
17760        // the future `feira app graph` per-Aplicacao strategy line,
17761        // the future M4 CR materializer's admission-webhook rejection
17762        // body) would still emit the TitleCase form the `as_str` /
17763        // `Display` route returns, with the mismatch surfacing at
17764        // consumer parse time / operator dispatch time far from the
17765        // source rebrand commit. Pin the two paths byte-for-byte here
17766        // so any future serde-attribute or variant-rename drift is a
17767        // caixa-core-build-time test failure at this call, not a
17768        // silent per-consumer dispatch miss.
17769        for variant in [
17770            PlacementStrategy::SingleNode,
17771            PlacementStrategy::Replicated,
17772            PlacementStrategy::Sharded,
17773        ] {
17774            let wire = serde_json::to_string(&variant).unwrap();
17775            // Strip the outer `"…"` the JSON string form carries — the
17776            // wire scalar the K8s / YAML apiserver consumes is the
17777            // enclosed byte-string, not the quote wrapper.
17778            let unquoted = wire
17779                .strip_prefix('"')
17780                .and_then(|s| s.strip_suffix('"'))
17781                .expect("serialized PlacementStrategy is a JSON string");
17782            assert_eq!(
17783                variant.to_string(),
17784                unquoted,
17785                "PlacementStrategy::{variant:?} Display byte-string must match the \
17786                 Serialize derive's wire byte-string (three-path convergence: \
17787                 Display + as_str + Serialize all resolve to the same \
17788                 M3_PLACEMENT_ESTRATEGIA_* const)"
17789            );
17790        }
17791    }
17792
17793    #[test]
17794    fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
17795        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
17796        // derive on [`PlacementStrategy`]: for each of the three variants
17797        // exactly one of the generated `is_single_node` / `is_replicated`
17798        // / `is_sharded` predicates returns `true` and the other two
17799        // return `false`. Prior to this derive the three per-arm
17800        // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
17801        // (the `placement_strategy_variants_round_trip` fixture, the
17802        // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
17803        // fixture, and the
17804        // `validate_placement_reads_through_lifted_estrategia_accessor`
17805        // fixture) each open-coded a per-arm PartialEq compare against
17806        // the enum variant — three sites that expressed no compile-time
17807        // link back to the closed-set typed dispatch a future fourth
17808        // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
17809        // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
17810        // would have to thread through in lockstep or one fixture would
17811        // silently disagree with the others on which arms consume the
17812        // `:shard-key` axis. Peer of the sibling
17813        // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
17814        // / [`crate::supervisor::RestartPolicy`] /
17815        // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
17816        // the sibling closed-set typed-enum discriminator axes — extends
17817        // the same one-typed-dispatch-per-variant discipline onto the
17818        // fifth (and only remaining) closed-set typed-enum discriminator
17819        // on the caixa surface, closing the axis on the M3 mesh-slot
17820        // family.
17821        let rows: [(PlacementStrategy, [bool; 3]); 3] = [
17822            (PlacementStrategy::SingleNode, [true, false, false]),
17823            (PlacementStrategy::Replicated, [false, true, false]),
17824            (PlacementStrategy::Sharded, [false, false, true]),
17825        ];
17826        for (variant, expected) in rows {
17827            let observed = [
17828                variant.is_single_node(),
17829                variant.is_replicated(),
17830                variant.is_sharded(),
17831            ];
17832            assert_eq!(
17833                observed, expected,
17834                "PlacementStrategy::{variant:?} is_* predicates must partition \
17835                 the arm set (single_node, replicated, sharded); got {observed:?}"
17836            );
17837        }
17838    }
17839
17840    #[test]
17841    fn placement_strategy_is_variant_predicates_are_const_fn() {
17842        // The [`gen_platform::IsVariant`] derive emits `const fn`
17843        // predicates on the peer [`crate::CaixaKind`] +
17844        // [`crate::upgrade::UpgradeInstruction`] +
17845        // [`crate::supervisor::RestartStrategy`] +
17846        // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
17847        // pin the same posture on [`PlacementStrategy`] so a future
17848        // accidental downgrade to non-`const` (an added runtime helper
17849        // reachable only from a non-`const` context, a manual hand-rolled
17850        // `impl` that shadows the derive-generated method) trips at
17851        // caixa-core build time rather than surfacing as a downstream
17852        // `const`-context regression far from the derive declaration.
17853        //
17854        // The pin lives inside a `const { assert!(..) }` block so the
17855        // compiler enforces both halves (arm predicate is `const`-
17856        // callable AND returns `true` for the matching arm) at
17857        // caixa-core compile time — peer to the sibling
17858        // [`crate::CaixaKind::is_*`] + [`WitTarget::is_*`] const-block
17859        // pins on the closed-set typed enum arm-predicate const-
17860        // callability axis.
17861        const {
17862            assert!(PlacementStrategy::SingleNode.is_single_node());
17863            assert!(PlacementStrategy::Replicated.is_replicated());
17864            assert!(PlacementStrategy::Sharded.is_sharded());
17865        }
17866    }
17867
17868    #[test]
17869    fn placement_strategy_requires_shard_key_partitions_the_arm_set() {
17870        // Fail-before-pass-after pin on the substrate-lifted
17871        // [`PlacementStrategy::requires_shard_key`] cross-slot-invariant
17872        // per-arm predicate: for each variant in the closed accept-set the
17873        // predicate returns `true` iff the variant consumes the paired
17874        // [`Placement::shard_key`] axis under
17875        // [`AplicacaoSpec::validate_placement`]'s `Sharded` ↔ non-`Sharded`
17876        // partition. Today the accept-set is the singleton `{Sharded}` —
17877        // `Sharded` is the Akka-style hash-keyed distribution arm
17878        // (MESH-COMPOSITION §II.4), `SingleNode` (Erlang/OTP takeover —
17879        // §II.1) and `Replicated` (active-active) refuse the axis through
17880        // [`AplicacaoError::ShardKeyOnNonSharded`].
17881        //
17882        // Pins the per-arm truth-table so a future arm addition (an
17883        // `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint the
17884        // roadmap names, a `WeightedShard` promotion the future M5
17885        // adaptive-placement engine acknowledges) that landed a variant
17886        // without extending this predicate's arm-set would surface as a
17887        // caixa-core build-time exhaustiveness error at the
17888        // `match self { … }` arm-fan below rather than a silent per-consumer
17889        // mis-classification at renderer emit time. The paired
17890        // [`Self::is_sharded`] `gen_platform::IsVariant`-derived arm-identity
17891        // predicate stays a distinct question — arm-identity (which the
17892        // sibling
17893        // [`placement_strategy_is_variant_predicates_partition_the_arm_set`]
17894        // pin already locks) is not cross-slot-invariant consumption; today
17895        // they trip on the same singleton but the pair migrates through
17896        // one caixa-core edit on any future arm addition.
17897        //
17898        // Peer of the sibling per-arm classifier pins
17899        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
17900        // (7b97d26) on the [`WitContract`] pre-projection WIT-shape axis
17901        // and the [`WitTarget::is_capability`] `gen_platform::IsVariant`-
17902        // derived paired predicate on the post-projection typed-view axis
17903        // — same "per-arm semantic-classification predicate paired with
17904        // the arm-identity predicate the derive already emits" discipline
17905        // extended onto the M3 mesh-slot `:placement :estrategia` ↔
17906        // `:placement :shard-key` cross-slot-invariant axis.
17907        let rows: [(PlacementStrategy, bool); 3] = [
17908            (PlacementStrategy::SingleNode, false),
17909            (PlacementStrategy::Replicated, false),
17910            (PlacementStrategy::Sharded, true),
17911        ];
17912        for (variant, expected) in rows {
17913            assert_eq!(
17914                variant.requires_shard_key(),
17915                expected,
17916                "PlacementStrategy::{variant:?}.requires_shard_key() must \
17917                 be {expected} (the substrate-canonical cross-slot invariant \
17918                 on the :placement :shard-key axis; today `Sharded` is the \
17919                 singleton consuming arm — MESH-COMPOSITION §II.4)",
17920            );
17921        }
17922    }
17923
17924    #[test]
17925    fn placement_strategy_requires_shard_key_is_const_fn() {
17926        // The [`PlacementStrategy::requires_shard_key`] cross-slot-
17927        // invariant per-arm predicate is declared `#[must_use] pub const
17928        // fn` — pin the `const`-eval posture here so a future accidental
17929        // downgrade to non-`const` (an added runtime helper reachable
17930        // only from a non-`const` context, a manual hand-rolled `impl`
17931        // that shadows the current three-arm `match self { … }` dispatch)
17932        // trips at caixa-core build time rather than surfacing as a
17933        // downstream `const`-context regression far from the declaration.
17934        // Same shape as the sibling
17935        // [`placement_strategy_is_variant_predicates_are_const_fn`] pin on
17936        // the peer [`gen_platform::IsVariant`]-derived arm-identity
17937        // predicate axis, but here the load-bearing assertions live in
17938        // module-scope `const _: () = assert!(…)` items so a violation
17939        // fails at compile time (const-eval trip) rather than test time —
17940        // strictly stronger than the runtime `assert!(CONST)` pattern the
17941        // sibling pin uses, and side-steps the
17942        // `clippy::assertions_on_constants` lint the runtime pattern
17943        // otherwise accumulates on the module baseline.
17944        //
17945        // The test body simply witnesses that the module-scope items
17946        // compiled and the runtime dispatch agrees with the const-eval
17947        // dispatch on every arm — the runtime read gives the test a
17948        // failure surface (rather than an empty test body clippy would
17949        // flag as a no-op).
17950        const REQUIRES_SINGLE_NODE: bool = PlacementStrategy::SingleNode.requires_shard_key();
17951        const REQUIRES_REPLICATED: bool = PlacementStrategy::Replicated.requires_shard_key();
17952        const REQUIRES_SHARDED: bool = PlacementStrategy::Sharded.requires_shard_key();
17953        assert_eq!(
17954            [REQUIRES_SINGLE_NODE, REQUIRES_REPLICATED, REQUIRES_SHARDED,],
17955            [
17956                PlacementStrategy::SingleNode.requires_shard_key(),
17957                PlacementStrategy::Replicated.requires_shard_key(),
17958                PlacementStrategy::Sharded.requires_shard_key(),
17959            ],
17960            "runtime and const-eval dispatch on \
17961             PlacementStrategy::requires_shard_key must agree on every arm",
17962        );
17963    }
17964
17965    #[test]
17966    fn placement_estrategia_accessor_is_const_fn() {
17967        // The [`Placement::estrategia`] per-`:placement` distribution-
17968        // strategy `Copy`-return scalar accessor is declared
17969        // `#[must_use] pub const fn` — matching the peer M3 mesh-slot
17970        // `Copy`-return accessor family ([`MeshPolicy::timeout`] /
17971        // [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
17972        // [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`]
17973        // on the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`]
17974        // / [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
17975        // [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
17976        // [`RateLimit`], every one a `pub const fn`). Pin the
17977        // `const`-eval posture here so a future accidental downgrade to
17978        // non-`const` (an added runtime helper reachable only from a
17979        // non-`const` context, a slot promotion to a non-`Copy` return
17980        // that would silently drop the `const` qualifier, a manual
17981        // hand-rolled shadow) trips at caixa-core build time rather
17982        // than surfacing as a downstream `const`-context regression far
17983        // from the declaration.
17984        //
17985        // Same shape as the sibling
17986        // [`placement_strategy_requires_shard_key_is_const_fn`] pin on
17987        // the peer [`PlacementStrategy::requires_shard_key`] `const fn`
17988        // predicate axis — the load-bearing witness lives in the
17989        // module-scope `const fn` wrapper `estrategia_via_const_fn`
17990        // below: a body that calls [`Placement::estrategia`] under a
17991        // `const fn` signature is well-formed only when the callee is
17992        // itself `const fn`, so any future accidental downgrade of
17993        // [`Placement::estrategia`] to non-`const` fails at caixa-core
17994        // build time (const-eval E0015 / E0658 depending on the arm),
17995        // strictly stronger than a runtime `assert!(CONST)` and
17996        // side-stepping the destructor-in-const restriction that
17997        // blocks direct `const _: PlacementStrategy = FIXTURE.estrategia()`
17998        // items on `Placement`'s `Vec<String>` / `Option<String>`
17999        // carriers.
18000        //
18001        // The runtime body witnesses that the const-eval-shaped
18002        // wrapper agrees with a direct call on every closed-set arm.
18003        const fn estrategia_via_const_fn(p: &Placement) -> PlacementStrategy {
18004            p.estrategia()
18005        }
18006        for estrategia in [
18007            PlacementStrategy::SingleNode,
18008            PlacementStrategy::Replicated,
18009            PlacementStrategy::Sharded,
18010        ] {
18011            let placement = Placement {
18012                estrategia,
18013                clusters: Vec::new(),
18014                affinity: None,
18015                shard_key: None,
18016            };
18017            assert_eq!(
18018                estrategia_via_const_fn(&placement),
18019                placement.estrategia(),
18020                "const-fn-wrapped and direct dispatch on \
18021                 Placement::estrategia must agree for {estrategia:?}",
18022            );
18023        }
18024    }
18025
18026    #[test]
18027    fn entrada_port_accessor_is_const_fn() {
18028        // The [`Entrada::port`] per-`:entrada` L4-port `Copy`-return
18029        // scalar accessor is declared `#[must_use] pub const fn` —
18030        // matching the peer M3 mesh-slot `Copy`-return accessor family
18031        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`] /
18032        // [`MeshPolicy::mtls_required`] / [`MeshPolicy::rate_limit`] /
18033        // [`MeshPolicy::circuit_breaker`] on the parent [`MeshPolicy`],
18034        // [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
18035        // on the sibling [`CircuitBreaker`], [`RateLimit::rate`] /
18036        // [`RateLimit::window`] on the sibling [`RateLimit`], the
18037        // sibling per-`:placement` [`Placement::estrategia`] pinned by
18038        // [`placement_estrategia_accessor_is_const_fn`] above — every
18039        // one a `pub const fn`). Pin the `const`-eval posture here so
18040        // a future accidental downgrade to non-`const` (an added
18041        // runtime helper reachable only from a non-`const` context, an
18042        // `Option<u16>`-shape migration once the substrate grows
18043        // per-`:membros` heterogeneous listener ports that would
18044        // silently drop the `const` qualifier, a manual hand-rolled
18045        // shadow) trips at caixa-core build time rather than surfacing
18046        // as a downstream `const`-context regression far from the
18047        // declaration.
18048        //
18049        // Same shape as the sibling
18050        // [`placement_estrategia_accessor_is_const_fn`] pin above — the
18051        // load-bearing witness lives in the module-scope `const fn`
18052        // wrapper `port_via_const_fn`: a body that calls
18053        // [`Entrada::port`] under a `const fn` signature is well-formed
18054        // only when the callee is itself `const fn`, side-stepping the
18055        // destructor-in-const restriction that would otherwise block a
18056        // direct `const _: u16 = FIXTURE.port()` item on `Entrada`'s
18057        // `String` / `Vec<String>` carriers.
18058        //
18059        // The runtime body sweeps a representative port set spanning
18060        // the [`SERVICO_PORT_MIN`] floor, the substrate-canonical
18061        // [`DEFAULT_SERVICO_PORT`] default, and the top-edge `u16::MAX`
18062        // ceiling — the const-fn-wrapped call must agree with a direct
18063        // call on every fixture (a violation trips the test) and every
18064        // returned scalar must byte-equal the input `port` (a violation
18065        // means the accessor stopped being a raw field-return copy).
18066        const fn port_via_const_fn(e: &Entrada) -> u16 {
18067            e.port()
18068        }
18069        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, u16::MAX] {
18070            let entrada = Entrada {
18071                host: String::new(),
18072                para: String::new(),
18073                port,
18074                paths: Vec::new(),
18075            };
18076            assert_eq!(
18077                port_via_const_fn(&entrada),
18078                entrada.port(),
18079                "const-fn-wrapped and direct dispatch on Entrada::port \
18080                 must agree for port={port}",
18081            );
18082            assert_eq!(
18083                entrada.port(),
18084                port,
18085                "Entrada::port must return the storage-side u16 verbatim \
18086                 for port={port}",
18087            );
18088        }
18089    }
18090
18091    #[test]
18092    fn validate_placement_admits_paired_shape_iff_strategy_requires_shard_key() {
18093        // Load-bearing cross-slot-partition pin closing the loop between
18094        // the substrate-lifted
18095        // [`PlacementStrategy::requires_shard_key`] per-arm predicate on
18096        // the closed-set typed enum and the actual
18097        // [`AplicacaoSpec::validate_placement`] runtime behavior across
18098        // the paired `:placement :shard-key` axis: every validated
18099        // [`Placement`] past [`AplicacaoSpec::validate_placement`]
18100        // satisfies `placement.shard_key().is_some() ==
18101        // placement.estrategia().requires_shard_key()`. The four-cell
18102        // shape witness sweeps every combination of (variant in the
18103        // closed accept-set, `:shard-key` Some/None) and pins:
18104        //
18105        //   * variant.requires_shard_key() && shard_key.is_some() →
18106        //     validate() passes; the paired shape is the sole
18107        //     `requires_shard_key` arm-family accepted shape.
18108        //   * variant.requires_shard_key() && shard_key.is_none() →
18109        //     validate() fails with [`AplicacaoError::ShardedWithoutKey`];
18110        //     the paired shape is the refused missing-key shape on
18111        //     Sharded-family arms.
18112        //   * !variant.requires_shard_key() && shard_key.is_some() →
18113        //     validate() fails with
18114        //     [`AplicacaoError::ShardKeyOnNonSharded`]; the paired shape
18115        //     is the refused declared-but-inert shape on non-Sharded-
18116        //     family arms.
18117        //   * !variant.requires_shard_key() && shard_key.is_none() →
18118        //     validate() passes; the paired shape is the sole
18119        //     non-`requires_shard_key` arm-family accepted shape.
18120        //
18121        // The compile-time-exhaustive `match p.estrategia()` dispatch at
18122        // [`AplicacaoSpec::validate_placement`] preserves its structural
18123        // arm-fan (a future arm addition still surfaces a build-time
18124        // exhaustiveness error there); this pin closes the semantic loop
18125        // between the arm-fan's shape-gate cascades and the substrate-
18126        // canonical predicate every downstream consumer of the paired
18127        // shape reads through. Fail-before-pass-after locally verified by
18128        // mutating the predicate's `Sharded => true` arm to `false` — the
18129        // truthy `expects_ok` cell for `Sharded` + `Some` trips the
18130        // `validate() must pass` assertion; restoring passes. Same "close
18131        // the loop between the typed predicate and the runtime behavior"
18132        // discipline as the sibling
18133        // [`wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant`]
18134        // (7b97d26) cross-projection pin on the peer [`WitTarget`]
18135        // per-arm classifier axis.
18136        for variant in [
18137            PlacementStrategy::SingleNode,
18138            PlacementStrategy::Replicated,
18139            PlacementStrategy::Sharded,
18140        ] {
18141            for present in [false, true] {
18142                let mut spec = three_member_spec();
18143                spec.placement.estrategia = variant;
18144                spec.placement.shard_key = present.then(|| "tenantId".into());
18145                let expects_ok = variant.requires_shard_key() == present;
18146                let result = spec.validate();
18147                match (expects_ok, &result) {
18148                    (true, Ok(())) => {}
18149                    (false, Err(err)) => {
18150                        // Cross-check the refusal diagnostic names the
18151                        // right cell of the four-cell shape witness — the
18152                        // `requires_shard_key && !present` cell must trip
18153                        // [`AplicacaoError::ShardedWithoutKey`]; the
18154                        // `!requires_shard_key && present` cell must trip
18155                        // [`AplicacaoError::ShardKeyOnNonSharded`].
18156                        match (variant.requires_shard_key(), present, err) {
18157                            (true, false, AplicacaoError::ShardedWithoutKey) => {}
18158                            (
18159                                false,
18160                                true,
18161                                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. },
18162                            ) => {
18163                                assert_eq!(
18164                                    *e, variant,
18165                                    "ShardKeyOnNonSharded.estrategia must byte-equal \
18166                                     the paired PlacementStrategy",
18167                                );
18168                            }
18169                            _ => panic!(
18170                                "unexpected refusal for estrategia={variant:?} \
18171                                 present={present}: {err:?}"
18172                            ),
18173                        }
18174                    }
18175                    (true, Err(err)) => panic!(
18176                        "validate() must pass for estrategia={variant:?} \
18177                         present={present} (requires_shard_key={} == present={present}), \
18178                         got {err:?}",
18179                        variant.requires_shard_key(),
18180                    ),
18181                    (false, Ok(())) => panic!(
18182                        "validate() must fail for estrategia={variant:?} \
18183                         present={present} (requires_shard_key={} != present={present})",
18184                        variant.requires_shard_key(),
18185                    ),
18186                }
18187            }
18188        }
18189    }
18190
18191    #[test]
18192    fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
18193        // Pin the M3 diagnostic template routes through the typed
18194        // [`PlacementStrategy`] Display byte-string (rebound from the
18195        // prior `{estrategia:?}` `Debug` route). Pre-lift the two
18196        // routes emitted identical bytes (the `Debug` derive on a
18197        // unit variant emits the variant name verbatim, exactly what
18198        // `as_str` returns), but the two paths were structurally
18199        // independent — a future `#[serde(rename_all = "…")]`
18200        // attribute or variant rename would coordinate the wire /
18201        // `Display` / `as_str` triple through the lifted const but
18202        // leave the `Debug` route on the compiler-derived variant name,
18203        // silently desynchronizing the diagnostic byte-string from the
18204        // wire byte-string. Rebinding the template onto `Display`
18205        // ties the diagnostic to the same lifted
18206        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
18207        // emits — drift becomes structurally impossible. Pin the
18208        // byte-string here so a future edit that reverts the template
18209        // to `{estrategia:?}` is caught at caixa-core test time, not
18210        // at consumer dispatch time.
18211        for (variant, expected_scalar) in [
18212            (
18213                PlacementStrategy::SingleNode,
18214                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
18215            ),
18216            (
18217                PlacementStrategy::Replicated,
18218                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
18219            ),
18220            (
18221                PlacementStrategy::Sharded,
18222                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
18223            ),
18224        ] {
18225            let err = AplicacaoError::PlacementWithoutClusters {
18226                estrategia: variant,
18227            };
18228            let msg = err.to_string();
18229            assert!(
18230                msg.starts_with(&format!(":placement {expected_scalar} requires")),
18231                "PlacementWithoutClusters diagnostic for {variant:?} must open \
18232                 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
18233            );
18234        }
18235    }
18236
18237    #[test]
18238    fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
18239        // Peer of
18240        // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
18241        // on the second M3 diagnostic that carries the typed
18242        // [`PlacementStrategy`] in its `#[error(…)]` template. Both
18243        // diagnostics now route the strategy scalar through the same
18244        // [`std::fmt::Display`] surface, tying the diagnostic
18245        // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
18246        // const set the wire format also emits. The two non-Sharded
18247        // arms are exercised here (the diagnostic exists to flag a
18248        // `:shard-key` slot the current strategy will never consume);
18249        // the peer `Sharded` arm never reaches this diagnostic (the
18250        // `Sharded` strategy consumes `:shard-key` — the
18251        // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
18252        // slot instead).
18253        for (variant, expected_scalar) in [
18254            (
18255                PlacementStrategy::SingleNode,
18256                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
18257            ),
18258            (
18259                PlacementStrategy::Replicated,
18260                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
18261            ),
18262        ] {
18263            let err = AplicacaoError::ShardKeyOnNonSharded {
18264                estrategia: variant,
18265                shard_key: "$tenantId".into(),
18266            };
18267            let msg = err.to_string();
18268            assert!(
18269                msg.starts_with(&format!(":placement {expected_scalar} carries")),
18270                "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
18271                 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
18272            );
18273        }
18274    }
18275
18276    #[test]
18277    fn placement_strategy_all_enumerates_every_variant_once() {
18278        // Fail-before-pass-after pin on the [`PlacementStrategy::ALL`]
18279        // exhaustive-iteration surface: every variant appears exactly
18280        // once, and the slice length matches the arm count of the
18281        // closed set. Every consumer that walks the accepted-strategy
18282        // set (a future `feira app placement --list` CLI-side surfacing,
18283        // a future M4 admission-webhook's rejection body naming the
18284        // accepted-strategy list, the [`PlacementStrategy::from_wire`]
18285        // reverse-projection consumers that iterate the accept-set for
18286        // a "did you mean" hint) reads through this slice, so a future
18287        // variant addition (an `Anycast` mesh-anycast arm the
18288        // MESH-COMPOSITION §II.5 hint names as a trajectory item) that
18289        // grows the enum but forgets to grow [`Self::ALL`] silently
18290        // truncates every downstream consumer's accept-set at the same
18291        // pre-addition boundary — this pin fails at caixa-core build
18292        // time on the pairwise-distinct + arm-count invariants.
18293        //
18294        // Peer of the sibling [`RateLimitUnit::ALL`] (6bce03d) /
18295        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
18296        // pins on the peer closed-set typed-enum axes.
18297        let all: &[PlacementStrategy] = PlacementStrategy::ALL;
18298        assert_eq!(
18299            all.len(),
18300            3,
18301            "PlacementStrategy::ALL must enumerate every variant of the \
18302             three-arm closed set (SingleNode, Replicated, Sharded); got {all:?}"
18303        );
18304        for (i, a) in all.iter().enumerate() {
18305            for (j, b) in all.iter().enumerate() {
18306                if i != j {
18307                    assert_ne!(
18308                        a, b,
18309                        "PlacementStrategy::ALL must carry every variant exactly \
18310                         once — got duplicate {a:?} at indices {i} and {j}"
18311                    );
18312                }
18313            }
18314        }
18315        for variant in [
18316            PlacementStrategy::SingleNode,
18317            PlacementStrategy::Replicated,
18318            PlacementStrategy::Sharded,
18319        ] {
18320            assert!(
18321                all.contains(&variant),
18322                "PlacementStrategy::ALL must contain {variant:?} — a future variant \
18323                 addition that grows the enum but forgets to grow the ALL slice \
18324                 silently truncates every downstream consumer's accept-set at the \
18325                 pre-addition boundary"
18326            );
18327        }
18328    }
18329
18330    #[test]
18331    fn placement_strategy_from_wire_accepts_every_lifted_constant() {
18332        // Fail-before-pass-after pin on the forward accept-set of the
18333        // [`PlacementStrategy::from_wire`] reverse projection: every
18334        // canonical [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
18335        // constant the [`PlacementStrategy::as_str`] emitter walks
18336        // parses back to its paired variant. Any future arm addition
18337        // that grows the emitter's `as_str` match but forgets to grow
18338        // the parser's `from_str` match silently splits the two halves
18339        // of the round-trip — the wire byte-string one non-serde
18340        // consumer parses from the one the emitter wrote — with the
18341        // failure surfacing at parse time far from the rebrand commit.
18342        // Pinning the three-arm accept-set here catches the drift at
18343        // caixa-core build time.
18344        //
18345        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
18346        // + [`RateLimitUnit::from_suffix`] accept-set pins on the peer
18347        // closed-set typed-enum `str → Self` axes.
18348        for (wire, expected) in [
18349            (
18350                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
18351                PlacementStrategy::SingleNode,
18352            ),
18353            (
18354                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
18355                PlacementStrategy::Replicated,
18356            ),
18357            (
18358                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
18359                PlacementStrategy::Sharded,
18360            ),
18361        ] {
18362            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
18363                panic!(
18364                    "PlacementStrategy::from_wire({wire:?}) must accept every \
18365                     M3_PLACEMENT_ESTRATEGIA_* constant — got None for the \
18366                     lifted canonical byte-string that PlacementStrategy::{expected:?} \
18367                     serializes as under M3_PLACEMENT_KEY_ESTRATEGIA"
18368                )
18369            });
18370            assert_eq!(
18371                parsed, expected,
18372                "PlacementStrategy::from_wire({wire:?}) must return \
18373                 PlacementStrategy::{expected:?}; got PlacementStrategy::{parsed:?}"
18374            );
18375        }
18376    }
18377
18378    #[test]
18379    fn placement_strategy_from_wire_round_trips_through_as_str() {
18380        // Fail-before-pass-after pin on the closed round-trip between
18381        // the forward [`PlacementStrategy::as_str`] emitter and the
18382        // reverse [`PlacementStrategy::from_wire`] parser: for every
18383        // variant in [`PlacementStrategy::ALL`], parsing the emitter's
18384        // output must return exactly the same variant. Any per-arm
18385        // divergence — a future arm added to `as_str` but not
18386        // `from_str`, an accidental copy-paste flip in one but not the
18387        // other — silently splits the emit and parse halves and the
18388        // failure surfaces at consumer parse time far from the drift
18389        // site. The `ALL`-iterating shape means a future variant
18390        // addition picks up the coverage by construction.
18391        //
18392        // Peer of the sibling [`crate::kind::tests`] round-trip pin on
18393        // [`crate::CaixaKind::from_wire`] and the
18394        // [`super::tests::rate_limit_unit_from_suffix_round_trips_through_as_suffix`]
18395        // sibling round-trip pin on [`RateLimitUnit`].
18396        for &variant in PlacementStrategy::ALL {
18397            let wire = variant.as_str();
18398            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
18399                panic!(
18400                    "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
18401                     must be Some({variant:?}) — the two halves of the round-trip \
18402                     dispatch on the same lifted M3_PLACEMENT_ESTRATEGIA_* consts; \
18403                     got None on wire byte-string {wire:?}"
18404                )
18405            });
18406            assert_eq!(
18407                parsed, variant,
18408                "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
18409                 must round-trip to the same variant; got {parsed:?}"
18410            );
18411        }
18412    }
18413
18414    #[test]
18415    fn placement_strategy_from_wire_rejects_unknown_byte_strings() {
18416        // Fail-before-pass-after pin on the closed-set refusal
18417        // discipline of [`PlacementStrategy::from_wire`]: every
18418        // byte-string outside the three-arm accept-set returns `None`
18419        // rather than silently collapsing onto the [`Default`]
18420        // (`Replicated`) arm or an arbitrary neighbor. The refusal set
18421        // exercised here sweeps the load-bearing drift shapes: the
18422        // empty string (a stripped serde-attribute drift), an all-
18423        // whitespace string (the canonical text-editor accidental
18424        // padding shape), the lowercased kebab-case forms a future
18425        // `#[serde(rename_all = "kebab-case")]` attribute would emit
18426        // (`"single-node"`, `"replicated"`, `"sharded"` — the last two
18427        // coincidentally match the accepted canonical scalars, so only
18428        // `"single-node"` fires as a refusal, but pinning the case-
18429        // sensitivity of the accepted arms via the peer [`SingleNode`]
18430        // assertion in the round-trip pin makes the discipline
18431        // structurally clear), the lowercased single-word forms
18432        // (`"singlenode"`), the padded canonical scalar
18433        // (`" Sharded "`), the trailing-comma / trailing-newline shapes
18434        // (`"Sharded\n"`), and a pointer-different `&'static str` that
18435        // happens to alias a canonical byte-string by content but not
18436        // by identity (validated implicitly by the emitter's routing
18437        // through `crate::render::M3_PLACEMENT_ESTRATEGIA_*`, whose
18438        // identity a paired [`crate::assert_str_reexport_identity`] pin
18439        // in caixa-core's per-const declaration surface would catch).
18440        //
18441        // Peer of the sibling
18442        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
18443        // (2aa6d23) refusal pin on [`crate::CaixaKind::from_wire`].
18444        for bad in [
18445            "",
18446            " ",
18447            "\n",
18448            "\t",
18449            "single-node",
18450            "singlenode",
18451            "SingleNodes",
18452            "single_node",
18453            "single node",
18454            "SINGLENODE",
18455            "SingleNode ",
18456            " SingleNode",
18457            " Sharded ",
18458            "Sharded\n",
18459            "replicated ",
18460            "sharded",
18461            "REPLICATED",
18462            "Anycast",
18463            "Global",
18464            "?",
18465        ] {
18466            assert!(
18467                PlacementStrategy::from_wire(bad).is_none(),
18468                "PlacementStrategy::from_wire({bad:?}) must return None — the \
18469                 parser's accept-set is exactly the three PlacementStrategy::as_str \
18470                 outputs (SingleNode, Replicated, Sharded), and this byte-string \
18471                 is outside that closed set"
18472            );
18473        }
18474    }
18475
18476    #[test]
18477    fn placement_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
18478        // Fail-before-pass-after pin on the third path of the four-path
18479        // convergence: `from_str` (the reverse projection) inverts the
18480        // `Serialize` derive's wire byte-string on every variant.
18481        // Together with the pre-existing three-path convergence
18482        // (`Display` + `as_str` + `Serialize` all resolve to the same
18483        // lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const, pinned by
18484        // the peer
18485        // [`placement_strategy_display_matches_serialized_wire_byte_string`])
18486        // this closes the round-trip: the wire byte-string the
18487        // `Serialize` derive emits parses back to the same variant
18488        // through `from_str`, so any future serde-attribute or variant-
18489        // rename drift on the emit half now surfaces as a matched drift
18490        // on the parse half at caixa-core build time — the two halves
18491        // migrate as a unit through the lifted consts on any future
18492        // rename, and the round-trip cannot silently split.
18493        //
18494        // Peer of the sibling
18495        // [`placement_strategy_display_matches_serialized_wire_byte_string`]
18496        // wire-format pin — extends the three-path convergence
18497        // (`Display` + `as_str` + `Serialize`) onto the fourth path
18498        // (`from_str`), closing the `str ↔ Self` round-trip on the
18499        // M3 `:placement :estrategia` closed-set axis.
18500        for &variant in PlacementStrategy::ALL {
18501            let wire = serde_json::to_string(&variant).unwrap();
18502            let unquoted = wire
18503                .strip_prefix('"')
18504                .and_then(|s| s.strip_suffix('"'))
18505                .expect("serialized PlacementStrategy is a JSON string");
18506            let parsed = PlacementStrategy::from_wire(unquoted).unwrap_or_else(|| {
18507                panic!(
18508                    "PlacementStrategy::from_wire({unquoted:?}) must accept the \
18509                     Serialize derive's wire byte-string for \
18510                     PlacementStrategy::{variant:?} — the four-path convergence \
18511                     (Display + as_str + Serialize + from_str) resolves through \
18512                     the same lifted M3_PLACEMENT_ESTRATEGIA_* const; got None"
18513                )
18514            });
18515            assert_eq!(
18516                parsed, variant,
18517                "PlacementStrategy::from_wire of the Serialize derive's wire \
18518                 byte-string for PlacementStrategy::{variant:?} must round-trip \
18519                 to the same variant; got {parsed:?}"
18520            );
18521        }
18522    }
18523
18524    #[test]
18525    fn rejects_zero_policy_timeout() {
18526        let mut s = three_member_spec();
18527        s.politicas.timeout = Some(Duration::ZERO);
18528        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
18529    }
18530
18531    #[test]
18532    fn rejects_zero_policy_retries() {
18533        let mut s = three_member_spec();
18534        s.politicas.retries = Some(0);
18535        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
18536    }
18537
18538    #[test]
18539    fn rejects_policy_retries_above_cap() {
18540        // The fail-before-pass-after pin: `Some(11)` is structurally
18541        // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
18542        // passed validate on every pre-gate codebase because the
18543        // typed slot's only check was the zero-floor arm. The
18544        // thundering-herd amplification vector only surfaced at the
18545        // runtime substrate (Envoy / Cilium L7 retry overlay)
18546        // far from the source caixa.lisp with no field naming the
18547        // offending policy.
18548        let mut s = three_member_spec();
18549        s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
18550        assert_eq!(
18551            s.validate().unwrap_err(),
18552            AplicacaoError::PolicyRetriesExceedsCap {
18553                retries: POLICY_RETRIES_MAX + 1
18554            }
18555        );
18556    }
18557
18558    #[test]
18559    fn rejects_policy_retries_far_above_cap() {
18560        // The `u32::MAX` worst case — the four-billion-retry policy
18561        // a typo (`(:retries 4294967295)`) or struct-literal
18562        // copy-paste lands in the slot. Pin the cap arm's coverage
18563        // explicitly across the full `u32` overflow so a future
18564        // relaxation that drops the upper bound surfaces here.
18565        let mut s = three_member_spec();
18566        s.politicas.retries = Some(u32::MAX);
18567        assert_eq!(
18568            s.validate().unwrap_err(),
18569            AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
18570        );
18571    }
18572
18573    #[test]
18574    fn accepts_policy_retries_at_cap() {
18575        // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
18576        // must validate. The cap is inclusive on the top edge,
18577        // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
18578        // discipline on the sibling [`crate::LimitsSpec::memory`]
18579        // axis. Pin the boundary explicitly so a future off-by-one
18580        // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
18581        // surfaces here as a test failure rather than a silent
18582        // contract narrowing.
18583        let mut s = three_member_spec();
18584        s.politicas.retries = Some(POLICY_RETRIES_MAX);
18585        s.validate()
18586            .expect("retries == POLICY_RETRIES_MAX must validate");
18587    }
18588
18589    #[test]
18590    fn accepts_policy_retries_typical_values() {
18591        // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
18592        // every value in the validated set must pass. The
18593        // Envoy / Istio production-playbook recommendation band
18594        // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
18595        // (`maxRetries ≤ 10`) both lie within this set.
18596        for r in 1..=POLICY_RETRIES_MAX {
18597            let mut s = three_member_spec();
18598            s.politicas.retries = Some(r);
18599            s.validate()
18600                .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
18601        }
18602    }
18603
18604    #[test]
18605    fn policy_retries_zero_takes_precedence_over_cap() {
18606        // The cross-arm ordering pin: `Some(0)` is structurally
18607        // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
18608        // (cap), but the zero-floor diagnostic is the more
18609        // self-locating one (it directly names the omit-axis
18610        // remediation), so the validate gate must fire on zero
18611        // first. Pin the order so a future refactor that reorders
18612        // the arms surfaces here as a test failure rather than a
18613        // silent diagnostic regression. Same shape every other
18614        // zero-then-shape ordering on this surface uses
18615        // ([`AplicacaoError::PolicyTimeoutZero`] then
18616        // [`AplicacaoError::PolicyTimeoutNotCanonical`];
18617        // [`AplicacaoError::PolicyBreakerZeroWindow`] then
18618        // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
18619        let mut s = three_member_spec();
18620        s.politicas.retries = Some(0);
18621        assert_eq!(
18622            s.validate().unwrap_err(),
18623            AplicacaoError::PolicyRetriesZero,
18624            "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
18625        );
18626    }
18627
18628    #[test]
18629    fn policy_retries_cap_diagnostic_carries_offending_value() {
18630        // The diagnostic-shape pin: the offending `u32` is carried
18631        // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
18632        // variant so the surfaced error message names the value the
18633        // author wrote (`":politicas :retries (47) exceeds the
18634        // mesh-policy ceiling …"`), not just the cap. Same
18635        // self-locating diagnostic shape every other typed-cap arm
18636        // on this surface carries
18637        // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
18638        // offending byte count verbatim).
18639        let mut s = three_member_spec();
18640        s.politicas.retries = Some(47);
18641        let err = s.validate().unwrap_err();
18642        assert!(
18643            matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
18644            "got {err:?}"
18645        );
18646        let msg = err.to_string();
18647        assert!(
18648            msg.contains("47"),
18649            ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
18650        );
18651    }
18652
18653    #[test]
18654    fn policy_retries_cap_is_aws_app_mesh_aligned() {
18655        // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
18656        // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
18657        // schema cap — the only upstream mesh-policy schema that
18658        // documents an explicit hard cap. Pinning the literal value
18659        // here surfaces a future drift (a relaxation to 20, a
18660        // tightening to 5) as a deliberate test edit, not a silent
18661        // contract narrowing.
18662        assert_eq!(POLICY_RETRIES_MAX, 10);
18663    }
18664
18665    #[test]
18666    fn rejects_circuit_breaker_zero_max_failures() {
18667        let mut s = three_member_spec();
18668        s.politicas.circuit_breaker = Some(CircuitBreaker {
18669            max_failures: 0,
18670            window: Duration::from_secs(60),
18671        });
18672        assert_eq!(
18673            s.validate().unwrap_err(),
18674            AplicacaoError::PolicyBreakerZeroFailures
18675        );
18676    }
18677
18678    #[test]
18679    fn rejects_circuit_breaker_max_failures_above_cap() {
18680        // The fail-before-pass-after pin: `1001` is structurally one
18681        // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
18682        // silently passed validate on every pre-gate codebase
18683        // because the typed slot's only check was the zero-floor
18684        // arm. The breaker-no-op vector only surfaced at the runtime
18685        // substrate (Envoy / Cilium L7 outlier-detection overlay)
18686        // far from the source caixa.lisp with no field naming the
18687        // offending policy.
18688        let mut s = three_member_spec();
18689        s.politicas.circuit_breaker = Some(CircuitBreaker {
18690            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
18691            window: Duration::from_secs(60),
18692        });
18693        assert_eq!(
18694            s.validate().unwrap_err(),
18695            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
18696                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
18697            }
18698        );
18699    }
18700
18701    #[test]
18702    fn rejects_circuit_breaker_max_failures_far_above_cap() {
18703        // The `u32::MAX` worst case — the four-billion-failure
18704        // threshold a typo (`(:max-failures 4294967295)`) or a
18705        // struct-literal copy-paste lands in the slot. Pin the cap
18706        // arm's coverage explicitly across the full `u32` overflow
18707        // so a future relaxation that drops the upper bound surfaces
18708        // here.
18709        let mut s = three_member_spec();
18710        s.politicas.circuit_breaker = Some(CircuitBreaker {
18711            max_failures: u32::MAX,
18712            window: Duration::from_secs(60),
18713        });
18714        assert_eq!(
18715            s.validate().unwrap_err(),
18716            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
18717                max_failures: u32::MAX,
18718            }
18719        );
18720    }
18721
18722    #[test]
18723    fn accepts_circuit_breaker_max_failures_at_cap() {
18724        // The boundary value — exactly
18725        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
18726        // cap is inclusive on the top edge, matching the
18727        // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
18728        // discipline on the sibling capped axes. Pin the boundary
18729        // explicitly so a future off-by-one tightening
18730        // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
18731        // surfaces here as a test failure rather than a silent
18732        // contract narrowing.
18733        let mut s = three_member_spec();
18734        s.politicas.circuit_breaker = Some(CircuitBreaker {
18735            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
18736            window: Duration::from_secs(60),
18737        });
18738        s.validate()
18739            .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
18740    }
18741
18742    #[test]
18743    fn accepts_circuit_breaker_max_failures_typical_values() {
18744        // The documented production-playbook band positive-control
18745        // sweep — every value Hystrix / Istio / Envoy / Polly /
18746        // Resilience4j recommend (5..=50) must pass, plus a sweep
18747        // through the hyperscale band (100, 500, 1000) the cap
18748        // accepts. Pin the inclusive validated set explicitly so a
18749        // future tightening of the ceiling surfaces here.
18750        //
18751        // Clears the fixture's `:retries` (which is `Some(3)`) so this
18752        // per-axis sweep is pure: the sibling cross-axis
18753        // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
18754        // gate rejects any `max_failures <= retries` pair, so the
18755        // `max_failures = 1` boundary at the head of the sweep would
18756        // otherwise trip on the fixture-inherited retry policy rather
18757        // than the per-axis boundary this test names. Same discipline
18758        // the sibling per-axis `accepts_circuit_breaker_window_*`
18759        // sweeps take against the fixture's `:timeout` for the
18760        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`]
18761        // cross-axis arm.
18762        for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
18763            let mut s = three_member_spec();
18764            s.politicas.retries = None;
18765            s.politicas.circuit_breaker = Some(CircuitBreaker {
18766                max_failures: n,
18767                window: Duration::from_secs(60),
18768            });
18769            s.validate()
18770                .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
18771        }
18772    }
18773
18774    #[test]
18775    fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
18776        // The cross-arm ordering pin: `0` is structurally outside
18777        // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
18778        // (cap), but the zero-floor diagnostic is the more
18779        // self-locating one (it directly names the omit-axis
18780        // remediation), so the validate gate must fire on zero
18781        // first. Same shape every other zero-then-shape ordering on
18782        // this surface uses
18783        // ([`AplicacaoError::PolicyRetriesZero`] then
18784        // [`AplicacaoError::PolicyRetriesExceedsCap`];
18785        // [`AplicacaoError::PolicyTimeoutZero`] then
18786        // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
18787        let mut s = three_member_spec();
18788        s.politicas.circuit_breaker = Some(CircuitBreaker {
18789            max_failures: 0,
18790            window: Duration::from_secs(60),
18791        });
18792        assert_eq!(
18793            s.validate().unwrap_err(),
18794            AplicacaoError::PolicyBreakerZeroFailures,
18795            "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
18796        );
18797    }
18798
18799    #[test]
18800    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
18801        // The cross-arm ordering pin between the cap and the
18802        // sibling `:window` gates (zero-window, canonical-window).
18803        // A breaker carrying both an over-cap `max_failures` AND a
18804        // structurally invalid window (zero, sub-ms) must surface
18805        // the cap diagnostic first — the cap arm is wired
18806        // immediately after the zero-failure arm and strictly
18807        // before the window arms, so the offending value the
18808        // diagnostic names matches the order the author would
18809        // discover the gates by reading top-to-bottom through
18810        // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
18811        // future refactor that reorders the arms surfaces here as a
18812        // test failure rather than a silent diagnostic regression.
18813        let mut s = three_member_spec();
18814        s.politicas.circuit_breaker = Some(CircuitBreaker {
18815            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
18816            window: Duration::ZERO,
18817        });
18818        assert_eq!(
18819            s.validate().unwrap_err(),
18820            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
18821                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
18822            },
18823            "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
18824        );
18825    }
18826
18827    #[test]
18828    fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
18829        // The diagnostic-shape pin: the offending `u32` is carried
18830        // verbatim into the
18831        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
18832        // variant so the surfaced error message names the value the
18833        // author wrote (`":politicas :circuit-breaker :max-failures
18834        // (50000) exceeds the mesh-policy ceiling …"`), not just
18835        // the cap. Same self-locating diagnostic shape every other
18836        // typed-cap arm on this surface carries
18837        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
18838        // offending retry count verbatim,
18839        // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
18840        // offending byte count verbatim).
18841        let mut s = three_member_spec();
18842        s.politicas.circuit_breaker = Some(CircuitBreaker {
18843            max_failures: 50_000,
18844            window: Duration::from_secs(60),
18845        });
18846        let err = s.validate().unwrap_err();
18847        assert!(
18848            matches!(
18849                err,
18850                AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
18851                    max_failures: 50_000
18852                }
18853            ),
18854            "got {err:?}"
18855        );
18856        let msg = err.to_string();
18857        assert!(
18858            msg.contains("50000"),
18859            ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
18860        );
18861    }
18862
18863    #[test]
18864    fn policy_breaker_max_failures_cap_pins_canonical_value() {
18865        // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
18866        // value at 1000 — an order of magnitude above every
18867        // documented production-playbook recommendation band
18868        // (Hystrix `requestVolumeThreshold` default 20, Istio
18869        // `outlierDetection.consecutive5xxErrors` default 5, Envoy
18870        // `outlier_detection.consecutive_5xx` default 5, Polly /
18871        // Resilience4j typical 5..=50) and below the
18872        // clearly-pathological "effectively no protection" floor
18873        // (10_000, 100_000, u32::MAX). Pinning the literal value
18874        // here surfaces a future drift (a relaxation to 10_000, a
18875        // tightening to 100) as a deliberate test edit, not a
18876        // silent contract narrowing.
18877        assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
18878    }
18879
18880    #[test]
18881    fn rejects_circuit_breaker_zero_window() {
18882        let mut s = three_member_spec();
18883        s.politicas.circuit_breaker = Some(CircuitBreaker {
18884            max_failures: 5,
18885            window: Duration::ZERO,
18886        });
18887        assert_eq!(
18888            s.validate().unwrap_err(),
18889            AplicacaoError::PolicyBreakerZeroWindow
18890        );
18891    }
18892
18893    #[test]
18894    fn rejects_zero_rate_limit() {
18895        let mut s = three_member_spec();
18896        s.politicas.rate_limit = Some(RateLimit {
18897            rate: 0,
18898            window: Duration::from_secs(1),
18899        });
18900        assert_eq!(
18901            s.validate().unwrap_err(),
18902            AplicacaoError::PolicyRateLimitZero
18903        );
18904    }
18905
18906    #[test]
18907    fn rejects_rate_limit_zero_window() {
18908        // `RateLimit { rate: 100, window: Duration::ZERO }` is
18909        // constructible programmatically (the typed `Duration` field
18910        // imposes no nonzero invariant) but renders through
18911        // `rate_limit_codec::render` as `"100/0s"` — a fragment the
18912        // codec's `parse` rejects as `unknown rate-limit window unit
18913        // "0s"`. Until this validate-time gate landed the typed slot
18914        // accepted the value silently and the round-trip break only
18915        // surfaced at deserialize time (potentially in a downstream
18916        // consumer that never re-validates). Pin the rejection at
18917        // `AplicacaoSpec::validate` so the typed slot's valid set
18918        // matches the codec's round-trippable set structurally.
18919        let mut s = three_member_spec();
18920        s.politicas.rate_limit = Some(RateLimit {
18921            rate: 100,
18922            window: Duration::ZERO,
18923        });
18924        assert_eq!(
18925            s.validate().unwrap_err(),
18926            AplicacaoError::PolicyRateLimitWindowNotCanonical {
18927                window: Duration::ZERO
18928            }
18929        );
18930    }
18931
18932    #[test]
18933    fn rejects_rate_limit_arbitrary_seconds_window() {
18934        // 45 seconds is a valid `Duration` but not one of the three
18935        // canonical rate-limit windows the codec round-trips
18936        // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
18937        // refuses on round-trip — same round-trip-break shape the
18938        // zero-window arm above pins, with a non-zero magnitude to
18939        // guard against a future "reject only zero" half-measure.
18940        let mut s = three_member_spec();
18941        let window = Duration::from_secs(45);
18942        s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
18943        assert_eq!(
18944            s.validate().unwrap_err(),
18945            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
18946        );
18947    }
18948
18949    #[test]
18950    fn rejects_rate_limit_two_minute_window() {
18951        // 120 seconds = 2 minutes is a "looks-canonical" but
18952        // not-canonical window: it's a clean integer multiple of the
18953        // minute unit, but the codec only round-trips the
18954        // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
18955        // A `Duration::from_secs(120)` window renders as `"100/120s"`
18956        // which the parser rejects. Pinning this case rules out a
18957        // future "accept any clean multiple of s/m/h" relaxation
18958        // that would silently break the codec contract.
18959        let mut s = three_member_spec();
18960        let window = Duration::from_secs(120);
18961        s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
18962        assert_eq!(
18963            s.validate().unwrap_err(),
18964            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
18965        );
18966    }
18967
18968    #[test]
18969    fn rejects_rate_limit_subsecond_window() {
18970        // A sub-second window (e.g. 500ms) is a valid `Duration` but
18971        // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
18972        // Pin the rejection so a future relaxation can't silently
18973        // admit fractional-second windows that the codec can't
18974        // round-trip.
18975        let mut s = three_member_spec();
18976        let window = Duration::from_millis(500);
18977        s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
18978        assert_eq!(
18979            s.validate().unwrap_err(),
18980            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
18981        );
18982    }
18983
18984    #[test]
18985    fn rejects_policy_rate_limit_above_cap() {
18986        // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
18987        // is structurally one past the cap and silently passed
18988        // validate on every pre-gate codebase because the typed slot's
18989        // only `rate` check was the zero-floor arm. The no-op-limiter
18990        // shape only surfaced at the runtime substrate (Envoy's
18991        // `local_rate_limit.token_bucket.max_tokens`, the future
18992        // Cilium L7 rate-limit overlay) far from the source caixa.lisp
18993        // with no field naming the offending policy.
18994        let mut s = three_member_spec();
18995        s.politicas.rate_limit = Some(RateLimit {
18996            rate: POLICY_RATE_LIMIT_MAX + 1,
18997            window: Duration::from_secs(1),
18998        });
18999        assert_eq!(
19000            s.validate().unwrap_err(),
19001            AplicacaoError::PolicyRateLimitExceedsCap {
19002                rate: POLICY_RATE_LIMIT_MAX + 1
19003            }
19004        );
19005    }
19006
19007    #[test]
19008    fn rejects_policy_rate_limit_far_above_cap() {
19009        // The `u32::MAX` worst case — the four-billion-token rate-limit
19010        // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
19011        // copy-paste lands in the slot. Pin the cap arm's coverage
19012        // explicitly across the full `u32` overflow so a future
19013        // relaxation that drops the upper bound surfaces here. Peer to
19014        // `rejects_policy_retries_far_above_cap` on the sibling
19015        // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
19016        // on the sibling `:max-failures` axis.
19017        let mut s = three_member_spec();
19018        s.politicas.rate_limit = Some(RateLimit {
19019            rate: u32::MAX,
19020            window: Duration::from_secs(1),
19021        });
19022        assert_eq!(
19023            s.validate().unwrap_err(),
19024            AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
19025        );
19026    }
19027
19028    #[test]
19029    fn accepts_policy_rate_limit_at_cap() {
19030        // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
19031        // must validate. The cap is inclusive on the top edge, matching
19032        // every other typed upper bound in this crate
19033        // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
19034        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
19035        // across all three canonical windows so a future off-by-one
19036        // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
19037        // window-conditional cap surfaces here as a test failure rather
19038        // than a silent contract narrowing.
19039        for secs in [1u64, 60, 3600] {
19040            let mut s = three_member_spec();
19041            s.politicas.rate_limit = Some(RateLimit {
19042                rate: POLICY_RATE_LIMIT_MAX,
19043                window: Duration::from_secs(secs),
19044            });
19045            s.validate().unwrap_or_else(|e| {
19046                panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
19047            });
19048        }
19049    }
19050
19051    #[test]
19052    fn accepts_policy_rate_limit_typical_values() {
19053        // The documented production-playbook recommendation band —
19054        // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
19055        // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
19056        // Enterprise ~1M per-hour. Every value in the validated set
19057        // must pass; pin the band explicitly so a future tightening
19058        // surfaces here.
19059        //
19060        // Clears the fixture's `:retries` (which is `Some(3)`) so this
19061        // per-axis sweep is pure: the sibling cross-axis
19062        // [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] gate
19063        // rejects any `rate <= retries` pair, so the `rate = 1`
19064        // boundary at the head of the sweep would otherwise trip on the
19065        // fixture-inherited retry policy rather than the per-axis
19066        // boundary this test names. Same discipline the sibling per-axis
19067        // `accepts_circuit_breaker_max_failures_typical_values` sweep
19068        // takes against the fixture's `:retries` for the peer cross-axis
19069        // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
19070        // arm.
19071        for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
19072            for secs in [1u64, 60, 3600] {
19073                let mut s = three_member_spec();
19074                s.politicas.retries = None;
19075                s.politicas.rate_limit = Some(RateLimit {
19076                    rate,
19077                    window: Duration::from_secs(secs),
19078                });
19079                s.validate().unwrap_or_else(|e| {
19080                    panic!("rate={rate} window={secs}s must validate; got {e:?}")
19081                });
19082            }
19083        }
19084    }
19085
19086    #[test]
19087    fn policy_rate_limit_zero_takes_precedence_over_cap() {
19088        // The cross-arm ordering pin: `rate == 0` is structurally
19089        // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
19090        // (cap), but the zero-floor diagnostic is the more
19091        // self-locating one (it directly names the omit-axis
19092        // remediation). Pin the order so a future refactor that
19093        // reorders the arms surfaces here as a test failure rather
19094        // than a silent diagnostic regression. Same shape every other
19095        // zero-then-cap ordering on this surface uses
19096        // ([`AplicacaoError::PolicyRetriesZero`] then
19097        // [`AplicacaoError::PolicyRetriesExceedsCap`];
19098        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
19099        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
19100        let mut s = three_member_spec();
19101        s.politicas.rate_limit = Some(RateLimit {
19102            rate: 0,
19103            window: Duration::from_secs(1),
19104        });
19105        assert_eq!(
19106            s.validate().unwrap_err(),
19107            AplicacaoError::PolicyRateLimitZero,
19108            "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
19109        );
19110    }
19111
19112    #[test]
19113    fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
19114        // Two-axis-bad pin: rate above cap *and* window non-canonical.
19115        // The validate gate must fire on the rate cap first — the
19116        // amplification-shape (no-op limiter) diagnostic is the more
19117        // fundamental one; the window-canonical diagnostic is the
19118        // narrower codec-round-trip shape. Pin the ordering so a future
19119        // refactor that reorders the rate-then-window check arms
19120        // surfaces here as a test failure rather than a silent
19121        // diagnostic regression.
19122        let mut s = three_member_spec();
19123        s.politicas.rate_limit = Some(RateLimit {
19124            rate: POLICY_RATE_LIMIT_MAX + 1,
19125            window: Duration::from_secs(45),
19126        });
19127        assert_eq!(
19128            s.validate().unwrap_err(),
19129            AplicacaoError::PolicyRateLimitExceedsCap {
19130                rate: POLICY_RATE_LIMIT_MAX + 1
19131            },
19132            "above-cap rate must surface the cap diagnostic, not the window diagnostic"
19133        );
19134    }
19135
19136    #[test]
19137    fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
19138        // The diagnostic-shape pin: the offending `u32` is carried
19139        // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
19140        // variant so the surfaced error message names the value the
19141        // author wrote (`":politicas :rate-limit rate (5000000) exceeds
19142        // the mesh-policy ceiling …"`), not just the cap. Same
19143        // self-locating diagnostic shape every other typed-cap arm on
19144        // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
19145        // carries the offending retries count verbatim,
19146        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
19147        // the offending failure count verbatim).
19148        let mut s = three_member_spec();
19149        s.politicas.rate_limit = Some(RateLimit {
19150            rate: 5_000_000,
19151            window: Duration::from_secs(1),
19152        });
19153        let err = s.validate().unwrap_err();
19154        assert!(
19155            matches!(
19156                err,
19157                AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
19158            ),
19159            "got {err:?}"
19160        );
19161        let msg = err.to_string();
19162        assert!(
19163            msg.contains("5000000"),
19164            ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
19165        );
19166    }
19167
19168    #[test]
19169    fn policy_rate_limit_cap_pins_canonical_value() {
19170        // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
19171        // 1_000_000 — two-to-three orders of magnitude above every
19172        // documented production-playbook recommendation band (Envoy /
19173        // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
19174        // Gateway 10_000..=100_000 per-minute) and below the
19175        // clearly-pathological "paste-from-binary blob" floor
19176        // (100_000_000, u32::MAX). Pinning the literal value here
19177        // surfaces a future drift (a relaxation to 10_000_000, a
19178        // tightening to 100_000) as a deliberate test edit, not a
19179        // silent contract narrowing.
19180        assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
19181    }
19182
19183    #[test]
19184    fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
19185        // Both axes are invalid here: rate == 0 *and* window is
19186        // non-canonical. The validate gate must fire on rate first
19187        // (matching the existing `rejects_zero_rate_limit` ordering),
19188        // so the existing diagnostic continues to lead with the
19189        // simpler "zero rate" framing. Pinning the order of checks
19190        // so a future refactor that reorders the arms surfaces here
19191        // as a test failure rather than a silent diagnostic
19192        // regression.
19193        let mut s = three_member_spec();
19194        s.politicas.rate_limit = Some(RateLimit {
19195            rate: 0,
19196            window: Duration::from_secs(45),
19197        });
19198        assert_eq!(
19199            s.validate().unwrap_err(),
19200            AplicacaoError::PolicyRateLimitZero
19201        );
19202    }
19203
19204    #[test]
19205    fn rate_limit_canonical_windows_validate() {
19206        // The three canonical windows the codec round-trips
19207        // losslessly — 1s / 60s / 3600s — must all pass `validate()`
19208        // unchanged. Pin the full canonical set as a positive case
19209        // (the existing `rate_limit_round_trip_seconds` /
19210        // `rate_limit_round_trip_minutes` tests pin the
19211        // serialize-then-deserialize property at the codec layer; this
19212        // test pins the validate-side complement so a future tightening
19213        // of the canonical set — e.g. dropping `:hour` — surfaces here
19214        // as a test failure rather than a silent contract narrowing).
19215        for secs in [1u64, 60, 3600] {
19216            let mut s = three_member_spec();
19217            s.politicas.rate_limit = Some(RateLimit {
19218                rate: 100,
19219                window: Duration::from_secs(secs),
19220            });
19221            s.validate().expect("canonical window must validate");
19222        }
19223    }
19224
19225    #[test]
19226    fn rate_limit_validated_value_round_trips_through_codec() {
19227        // The structural property the validate gate enforces:
19228        // every `RateLimit` past `AplicacaoSpec::validate` round-trips
19229        // losslessly through the `rate_limit_codec` (serialize → string
19230        // → deserialize → equal value). Pin this end-to-end so a future
19231        // change to either side (the validate gate's accepted window
19232        // set, the codec's parse/render unit set) that breaks the
19233        // alignment surfaces here. The previous-state shape (typed
19234        // slot accepts arbitrary `Duration`, codec only round-trips
19235        // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
19236        // window — the validate gate now forecloses that.
19237        for secs in [1u64, 60, 3600] {
19238            let mut s = three_member_spec();
19239            s.politicas.rate_limit = Some(RateLimit {
19240                rate: 250,
19241                window: Duration::from_secs(secs),
19242            });
19243            s.validate().unwrap();
19244            let json = serde_json::to_string(&s.politicas).unwrap();
19245            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
19246            assert_eq!(
19247                back.rate_limit, s.politicas.rate_limit,
19248                "every validated :rate-limit must round-trip losslessly through the codec"
19249            );
19250        }
19251    }
19252
19253    #[test]
19254    fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
19255        // The hour-window canonical form (`"<n>/h"`) was missing from
19256        // the prior `rate_limit_round_trip_seconds` / `_minutes` test
19257        // pair. Now that the validate gate pins 3600s as part of the
19258        // canonical set, pin its serialize-side render shape too so
19259        // the third leg of the s/m/h tripod is explicitly tested.
19260        let policy = MeshPolicy {
19261            rate_limit: Some(RateLimit {
19262                rate: 10000,
19263                window: Duration::from_secs(3600),
19264            }),
19265            ..Default::default()
19266        };
19267        let json = serde_json::to_string(&policy).unwrap();
19268        assert!(
19269            json.contains("\"10000/h\""),
19270            "hour-window canonical form must render with `h` suffix (got: {json})"
19271        );
19272        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
19273        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
19274    }
19275
19276    #[test]
19277    fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
19278        // Pin the substrate-primitive [`RateLimit::canonical_unit`]
19279        // typed accessor's accepted-window set against the codec's
19280        // accepted set explicitly. A future addition to the codec
19281        // (e.g. accepting `:day`/`:week` as authoring units) must be
19282        // accompanied by a parallel addition here, and a regression
19283        // that drops one of the three canonical units from either
19284        // side surfaces as a test failure. The accessor is the
19285        // single source of truth for the canonical-window set —
19286        // [`AplicacaoSpec::validate_politicas`]'s canonical-window
19287        // gate and [`rate_limit_codec::render`]'s canonical arm both
19288        // read through it — this test enshrines that its
19289        // `Duration → Option<RateLimitUnit>` projection matches the
19290        // codec's parse / render arms' accepted-window set exactly.
19291        //
19292        // Predecessor: this pin previously read the module-private
19293        // free helper `is_canonical_rate_limit_window` — a delegate
19294        // that composed [`RateLimitUnit::from_window`] with `.is_some()`
19295        // — but the helper had no production consumers left after the
19296        // validate-gate migration onto [`RateLimit::canonical_unit`]
19297        // and was deleted; the closed-set arm-window bijection now
19298        // lives on exactly one typed dispatch on the substrate
19299        // primitive.
19300        let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
19301            RateLimit { rate: 1, window }.canonical_unit()
19302        };
19303        assert!(canonical_unit(Duration::from_secs(1)).is_some());
19304        assert!(canonical_unit(Duration::from_secs(60)).is_some());
19305        assert!(canonical_unit(Duration::from_secs(3600)).is_some());
19306        // Non-canonical windows the accessor rejects.
19307        assert!(canonical_unit(Duration::ZERO).is_none());
19308        assert!(canonical_unit(Duration::from_secs(2)).is_none());
19309        assert!(canonical_unit(Duration::from_secs(30)).is_none());
19310        assert!(canonical_unit(Duration::from_secs(120)).is_none());
19311        assert!(canonical_unit(Duration::from_secs(86400)).is_none());
19312        // Sub-second windows: even `Duration::from_millis(1000)` is
19313        // exactly 1s and accepted; `Duration::from_millis(500)` is
19314        // sub-second and rejected.
19315        assert!(canonical_unit(Duration::from_millis(1000)).is_some());
19316        assert!(canonical_unit(Duration::from_millis(500)).is_none());
19317        assert!(canonical_unit(Duration::from_millis(1500)).is_none());
19318    }
19319
19320    #[test]
19321    fn rate_limit_unit_table_projections_are_mutual_inverses() {
19322        // Bidirection pin against the closed-set typed enum
19323        // [`RateLimitUnit`] arm-table (the canonical
19324        // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
19325        // of the rate-limit unit surface reads from). The two
19326        // projection directions [`RateLimitUnit::from_suffix`] /
19327        // [`RateLimitUnit::window`] (str → Duration, exposed as one
19328        // typed dispatch through [`RateLimitUnit::window_from_suffix`])
19329        // and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
19330        // (Duration → str, exposed as one typed dispatch through
19331        // [`RateLimit::canonical_unit`] composed with
19332        // [`RateLimitUnit::as_suffix`]) are the substrate primitives the
19333        // codec's parse arm ([`rate_limit_codec::parse`] via
19334        // [`RateLimitUnit::window_from_suffix`]), the codec's render arm
19335        // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
19336        // and the validate gate ([`AplicacaoSpec::validate_politicas`]
19337        // via [`RateLimit::canonical_unit`]) all key off. A future
19338        // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
19339        // sub-second window) is one variant + one arm per method on the
19340        // closed-set enum; the compiler-enforced exhaustiveness on
19341        // every consumer's `match self` arms picks it up by
19342        // construction. This pin enshrines that both projection
19343        // directions agree on every canonical arm row and neither
19344        // leaks a spurious entry the other doesn't recognize.
19345        //
19346        // Predecessor: this test previously read the two vestigial
19347        // module-private free helpers `rate_limit_window_unit` and
19348        // `rate_limit_window_from_unit` on the `Duration → &str` and
19349        // `&str → Duration` axes; the former was deleted after its
19350        // sole production consumer ([`rate_limit_codec::render`])
19351        // migrated onto [`RateLimit::canonical_unit`] (61421a6), and
19352        // the latter is folded here into the substrate primitive
19353        // [`RateLimitUnit::window_from_suffix`] so both projection
19354        // directions live on the closed-set enum's arm-table.
19355        for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
19356            let window = super::RateLimitUnit::window_from_suffix(unit)
19357                .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
19358            assert_eq!(
19359                window,
19360                Duration::from_secs(secs),
19361                "unit {unit:?} must resolve to {secs}s"
19362            );
19363            let projected_suffix = RateLimit { rate: 1, window }
19364                .canonical_unit()
19365                .map(super::RateLimitUnit::as_suffix);
19366            assert_eq!(
19367                projected_suffix,
19368                Some(unit),
19369                "Duration({secs}s) must render as {unit:?} \
19370                 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
19371            );
19372        }
19373        // Non-table units yield None on the `unit → Duration`
19374        // projection — a future `"d"` addition to the table would
19375        // flip this arm; today it pins the current three-row table's
19376        // rejection semantics.
19377        assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
19378        assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
19379        assert!(super::RateLimitUnit::window_from_suffix("").is_none());
19380        // Non-table Durations yield None on the `Duration → unit`
19381        // projection — pins that the two projections agree on the
19382        // "not in the table" semantic too, so a drift where the
19383        // parse-side accepts a value the render-side can't emit is
19384        // a build error at the two-arm pair, not a silent codec
19385        // round-trip break.
19386        let projected_suffix = |window: Duration| -> Option<&'static str> {
19387            RateLimit { rate: 1, window }
19388                .canonical_unit()
19389                .map(super::RateLimitUnit::as_suffix)
19390        };
19391        assert!(projected_suffix(Duration::from_secs(2)).is_none());
19392        assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
19393        assert!(projected_suffix(Duration::from_millis(1500)).is_none());
19394    }
19395
19396    #[test]
19397    fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
19398        // Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
19399        // substrate-primitive `&str → Duration` associated method the
19400        // codec's parse arm ([`rate_limit_codec::parse`]) now routes
19401        // through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
19402        // to the same [`Duration`] the two-step composition
19403        // [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
19404        // returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
19405        // `"MIN"`) must project to [`None`] on both paths. A future
19406        // implementation of `window_from_suffix` that took a shortcut
19407        // through a per-suffix `match` table (bypassing the arm-table's
19408        // `Self::from_suffix` scan and the arm-table's `Self::window`
19409        // dispatch) would silently split the accept-set — the parse
19410        // arm would accept a suffix the enum's arm-table doesn't know,
19411        // or reject a suffix the enum's arm-table does; this pin
19412        // surfaces that drift at caixa-core build time rather than at a
19413        // downstream serde round-trip audit on a live `MeshPolicy`.
19414        //
19415        // Same byte-parity discipline the sibling
19416        // [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
19417        // pin carries on the peer `Duration → RateLimitUnit` axis via
19418        // [`RateLimit::canonical_unit`], and the peer
19419        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
19420        // carries on the bidirectional arm-table axis — extended here
19421        // onto the fifth (and last unlifted) projection axis on the
19422        // closed-set enum's arm-table.
19423        let composition = |suffix: &str| -> Option<Duration> {
19424            super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
19425        };
19426        for suffix in ["s", "m", "h"] {
19427            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
19428            let via_composition = composition(suffix);
19429            assert_eq!(
19430                via_method, via_composition,
19431                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
19432                 from_suffix({suffix:?}).map(window) — the substrate-primitive \
19433                 method must delegate to the arm-table's two typed dispatches, \
19434                 not shortcut through a per-suffix match table"
19435            );
19436            assert!(
19437                via_method.is_some(),
19438                "canonical suffix {suffix:?} must resolve to Some(Duration) via \
19439                 RateLimitUnit::window_from_suffix"
19440            );
19441        }
19442        for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
19443            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
19444            let via_composition = composition(suffix);
19445            assert_eq!(
19446                via_method, via_composition,
19447                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
19448                 from_suffix({suffix:?}).map(window) on the non-arm rejection \
19449                 axis too"
19450            );
19451            assert!(
19452                via_method.is_none(),
19453                "non-arm suffix {suffix:?} must project to None via \
19454                 RateLimitUnit::window_from_suffix — a future extension that \
19455                 accepted this suffix without a corresponding arm on the enum \
19456                 would split the codec's parse-accepted set from the enum's \
19457                 arm-table"
19458            );
19459        }
19460        // And the codec's parse arm now reads through this method: a
19461        // canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
19462        // the same `Duration` the method returns for its unit, closing
19463        // the two-consumer drift surface (the codec's parse arm and the
19464        // enum's arm-table) with one typed dispatch on the substrate
19465        // primitive.
19466        for suffix in ["s", "m", "h"] {
19467            let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
19468            let mp: MeshPolicy = serde_json::from_str(&wire)
19469                .unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
19470            let parsed = mp.rate_limit().expect("rate_limit payload present");
19471            let via_method = super::RateLimitUnit::window_from_suffix(suffix)
19472                .unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
19473            assert_eq!(
19474                parsed.window(),
19475                via_method,
19476                "codec parse arm on {wire:?} must resolve the window through \
19477                 RateLimitUnit::window_from_suffix, not a divergent path"
19478            );
19479        }
19480    }
19481
19482    #[test]
19483    fn rate_limit_unit_all_enumerates_every_arm_once() {
19484        // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
19485        // enumerate every arm of the closed-set enum exactly once, in
19486        // the canonical shortest-to-longest window order (Second before
19487        // Minute before Hour) — the same order the sibling
19488        // [`crate::supervisor::RestartStrategy`] /
19489        // [`crate::supervisor::RestartPolicy`] /
19490        // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
19491        // typed enums carry (the arm declared first is the arm listed
19492        // first). A future variant addition that extends the enum
19493        // without appending to [`RateLimitUnit::ALL`] leaves the
19494        // exhaustive iteration surface silently short one arm — the
19495        // codec's parse arm would then reject the new suffix even
19496        // though the enum knows it. This pin closes the drift.
19497        assert_eq!(
19498            super::RateLimitUnit::ALL,
19499            &[
19500                super::RateLimitUnit::Second,
19501                super::RateLimitUnit::Minute,
19502                super::RateLimitUnit::Hour,
19503            ],
19504            "RateLimitUnit::ALL must enumerate every arm exactly once, \
19505             in canonical shortest-to-longest window order"
19506        );
19507    }
19508
19509    #[test]
19510    fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
19511        // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
19512        // every arm's [`RateLimitUnit::as_suffix`] output must parse
19513        // back through [`RateLimitUnit::from_suffix`] to the same
19514        // variant. A future arm addition that lands `as_suffix` but
19515        // forgets `from_suffix` (`from_suffix` iterates
19516        // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
19517        // is the load-bearing carrier of the round-trip; the sibling
19518        // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
19519        // the `ALL` half) trips here at caixa-core build time rather
19520        // than surfacing as a codec round-trip miss (a `render` emit
19521        // that lands a suffix the paired `parse` cannot decode).
19522        for unit in super::RateLimitUnit::ALL {
19523            let suffix = unit.as_suffix();
19524            let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
19525                panic!(
19526                    "RateLimitUnit::from_suffix({suffix:?}) must accept every \
19527                     RateLimitUnit::as_suffix output — got None for {unit:?}"
19528                )
19529            });
19530            assert_eq!(
19531                parsed, *unit,
19532                "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
19533                 must return RateLimitUnit::{unit:?}"
19534            );
19535        }
19536    }
19537
19538    #[test]
19539    fn rate_limit_unit_from_window_and_window_round_trip() {
19540        // Total round-trip pin on the `(from_window, window)` pair:
19541        // every arm's [`RateLimitUnit::window`] output must parse back
19542        // through [`RateLimitUnit::from_window`] to the same variant.
19543        // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
19544        // on the peer `Duration` axis — the two round-trip pins
19545        // together enshrine that both projections of the typed
19546        // canonical-unit bijection are total on the arm-set.
19547        for unit in super::RateLimitUnit::ALL {
19548            let window = unit.window();
19549            let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
19550                panic!(
19551                    "RateLimitUnit::from_window({window:?}) must accept every \
19552                     RateLimitUnit::window output — got None for {unit:?}"
19553                )
19554            });
19555            assert_eq!(
19556                parsed, *unit,
19557                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
19558                 must return RateLimitUnit::{unit:?}"
19559            );
19560        }
19561    }
19562
19563    #[test]
19564    fn rate_limit_unit_from_window_accessor_is_const_fn() {
19565        // Fail-before-pass-after pin: witnesses the
19566        // [`RateLimitUnit::from_window`] `const`-eval posture via a
19567        // `const fn` wrapper `from_window_via_const_fn(window: Duration)
19568        // -> Option<RateLimitUnit>` whose body calls
19569        // `RateLimitUnit::from_window(window)`, well-formed only when
19570        // the callee is itself `const fn` (any future downgrade to
19571        // non-`const` fails at caixa-core build time with E0015 `cannot
19572        // call non-const function`, strictly stronger than a runtime
19573        // `assert!`, side-stepping the destructor-in-const restriction
19574        // that blocks direct `const _: Option<RateLimitUnit> =
19575        // RateLimitUnit::from_window(...)` items on `Duration`'s
19576        // carrier). The runtime body sweeps every closed-set
19577        // [`RateLimitUnit::ALL`] arm plus a representative non-canonical
19578        // rejection sample (`Duration::from_millis(500)` sub-second
19579        // residue) and asserts the wrapped and direct dispatches agree
19580        // — a violation means the wrapper stopped compiling under a
19581        // future `const`-posture downgrade, or the reverse resolver's
19582        // arm-set silently split from the peer `Self::window` emitter's
19583        // arm-set. Peer of the sibling
19584        // [`crate::supervisor::tests::child_spec_restart_accessor_is_const_fn`]
19585        // (152c868) /
19586        // [`crate::supervisor::tests::supervisor_spec_estrategia_accessor_is_const_fn`]
19587        // (152c868) /
19588        // [`entrada_port_accessor_is_const_fn`] (bafa004) /
19589        // [`placement_estrategia_accessor_is_const_fn`] (bafa004)
19590        // `const`-eval-surface pins on the peer M2 / M3 substrate-
19591        // primitive `Copy`-return accessor axes, extended onto the
19592        // reverse `Duration → RateLimitUnit` projection axis on the
19593        // M3 mesh-slot rate-limit closed-set typed enum.
19594        const fn from_window_via_const_fn(window: Duration) -> Option<super::RateLimitUnit> {
19595            super::RateLimitUnit::from_window(window)
19596        }
19597        for unit in super::RateLimitUnit::ALL {
19598            let window = unit.window();
19599            let via_wrapper = from_window_via_const_fn(window);
19600            let direct = super::RateLimitUnit::from_window(window);
19601            assert_eq!(
19602                via_wrapper, direct,
19603                "RateLimitUnit::from_window({window:?}) via const fn \
19604                 wrapper must agree with direct dispatch for {unit:?}"
19605            );
19606            assert_eq!(
19607                via_wrapper,
19608                Some(*unit),
19609                "RateLimitUnit::from_window({window:?}) via const fn \
19610                 wrapper must return Some({unit:?}) for the peer \
19611                 window() output"
19612            );
19613        }
19614        assert!(from_window_via_const_fn(Duration::from_millis(500)).is_none());
19615        assert!(from_window_via_const_fn(Duration::from_secs(30)).is_none());
19616    }
19617
19618    #[test]
19619    fn rate_limit_unit_from_window_composes_through_window_accessor() {
19620        // Composition-witness pin on the routing-through-peer discipline:
19621        // [`RateLimitUnit::from_window`]'s per-arm probes each dispatch
19622        // through the peer `pub const fn` [`RateLimitUnit::window`]
19623        // canonical-`Duration` projection rather than a hand-authored
19624        // per-arm second-magnitude literal — a future arm-magnitude edit
19625        // on the sibling `window()` accessor (a `Second → 2s` typo, a
19626        // `Hour → 3599s` off-by-one) must therefore reach this reverse
19627        // resolver by construction. A pin that hard-coded the three
19628        // second-magnitudes here would silently split from the peer
19629        // emitter on any such edit; instead, this pin asserts the
19630        // composition invariant `from_window(u.window()) == Some(u)`
19631        // holds byte-for-byte on every closed-set [`RateLimitUnit::ALL`]
19632        // arm — a violation means either the peer `Self::window`
19633        // accessor drifted (breaking every downstream consumer that
19634        // reads through it), or the reverse resolver stopped routing
19635        // through the peer (introducing a hand-authored literal that
19636        // silently disagrees with the emitter). Either failure is a
19637        // caixa-core-build-time surface, not a downstream renderer
19638        // round-trip regression.
19639        //
19640        // Peer of the sibling
19641        // [`crate::render::assert_str_reexport_identity`] discipline on
19642        // the substrate-primitive `&'static str` re-export axis and the
19643        // [`rate_limit_unit_from_window_and_window_round_trip`]
19644        // round-trip pin on the peer projection direction; extends the
19645        // one-canonical-dispatch-per-projection discipline onto the
19646        // reverse-resolver's per-arm probe axis.
19647        for unit in super::RateLimitUnit::ALL {
19648            let window_via_peer = unit.window();
19649            let resolved = super::RateLimitUnit::from_window(window_via_peer);
19650            assert_eq!(
19651                resolved,
19652                Some(*unit),
19653                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
19654                 must return Some({unit:?}) — the reverse resolver's per-arm \
19655                 probes must route through the peer `Self::window` accessor \
19656                 so any future arm-magnitude edit reaches both projection \
19657                 directions by construction"
19658            );
19659        }
19660    }
19661
19662    #[test]
19663    fn rate_limit_canonical_unit_accessor_is_const_fn() {
19664        // Fail-before-pass-after pin: witnesses the
19665        // [`RateLimit::canonical_unit`] `const`-eval posture via a
19666        // `const fn` wrapper
19667        // `canonical_unit_via_const_fn(rl: &RateLimit) -> Option<RateLimitUnit>`
19668        // whose body calls `rl.canonical_unit()`, well-formed only when
19669        // the callee is itself `const fn` (any future downgrade to
19670        // non-`const` fails at caixa-core build time with E0015 `cannot
19671        // call non-const method`). The runtime body sweeps every
19672        // closed-set [`RateLimitUnit::ALL`] arm — for each arm,
19673        // constructs a typed [`RateLimit`] with the peer `Self::window`
19674        // canonical `Duration`, then asserts both the wrapper and the
19675        // direct dispatch agree and both return `Some(unit)`. Composes
19676        // with the sibling
19677        // [`rate_limit_unit_from_window_accessor_is_const_fn`] pin: the
19678        // typed [`RateLimit`] projection layer's `const`-posture is
19679        // load-bearing on the reverse resolver's `const`-posture, and
19680        // both must migrate together (a downgrade of either surface
19681        // splits the paired `const`-eval-surface pass on the M3
19682        // mesh-slot rate-limit `Duration ↔ Self` bijection).
19683        const fn canonical_unit_via_const_fn(
19684            rl: &super::RateLimit,
19685        ) -> Option<super::RateLimitUnit> {
19686            rl.canonical_unit()
19687        }
19688        for unit in super::RateLimitUnit::ALL {
19689            let rl = super::RateLimit {
19690                rate: 1,
19691                window: unit.window(),
19692            };
19693            let via_wrapper = canonical_unit_via_const_fn(&rl);
19694            let direct = rl.canonical_unit();
19695            assert_eq!(
19696                via_wrapper, direct,
19697                "RateLimit::canonical_unit() via const fn wrapper must \
19698                 agree with direct dispatch for {unit:?}"
19699            );
19700            assert_eq!(
19701                via_wrapper,
19702                Some(*unit),
19703                "RateLimit::canonical_unit() via const fn wrapper must \
19704                 return Some({unit:?}) for a RateLimit whose window is \
19705                 the peer RateLimitUnit::{unit:?}.window() output"
19706            );
19707        }
19708    }
19709
19710    #[test]
19711    fn rate_limit_unit_projections_are_pairwise_distinct() {
19712        // Distinctness pin: [`RateLimitUnit::as_suffix`] and
19713        // [`RateLimitUnit::window`] outputs must be pairwise distinct
19714        // across every arm — an accidental copy-paste flip that
19715        // reroutes one arm's suffix or window to also match another
19716        // silently collapses two arms onto one, so
19717        // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
19718        // (both using `find` on `Self::ALL`) would return whichever
19719        // arm the linear scan lands on first — a match-arm-ordering-
19720        // dependent outcome the closed-set typed-enum shape is meant
19721        // to rule out structurally. Peer of the sibling
19722        // `caixa_kind_wire_consts_are_pairwise_distinct` /
19723        // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
19724        // other closed-set typed-enum discriminator axes.
19725        let all = super::RateLimitUnit::ALL;
19726        for (i, a) in all.iter().enumerate() {
19727            for (j, b) in all.iter().enumerate() {
19728                if i != j {
19729                    assert_ne!(
19730                        a.as_suffix(),
19731                        b.as_suffix(),
19732                        "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
19733                         must be distinct — a collision silently collapses two \
19734                         arms onto one under from_suffix's linear scan"
19735                    );
19736                    assert_ne!(
19737                        a.window(),
19738                        b.window(),
19739                        "RateLimitUnit::{a:?}.window() and {b:?}.window() \
19740                         must be distinct — a collision silently collapses two \
19741                         arms onto one under from_window's linear scan"
19742                    );
19743                }
19744            }
19745        }
19746    }
19747
19748    #[test]
19749    fn rate_limit_unit_display_routes_through_as_suffix() {
19750        // Route pin: [`std::fmt::Display`] must byte-equal
19751        // [`RateLimitUnit::as_suffix`] on every arm — the single
19752        // source of truth for the canonical suffix. A future
19753        // reimplementation that hand-rolls the arms instead of
19754        // delegating to [`RateLimitUnit::as_suffix`] would silently
19755        // desynchronize `format!("{u}")` from the codec's parse arm
19756        // (which uses `as_suffix` to compare suffixes). Peer of the
19757        // sibling `caixa_kind_display_routes_through_as_str_helper` /
19758        // `placement_strategy_display_routes_through_as_str_helper`
19759        // pins on the peer closed-set typed-enum Display axes.
19760        for unit in super::RateLimitUnit::ALL {
19761            assert_eq!(
19762                unit.to_string(),
19763                unit.as_suffix(),
19764                "RateLimitUnit::{unit:?} Display must route through \
19765                 as_suffix (single source of truth: the canonical suffix \
19766                 the codec parses and renders)"
19767            );
19768        }
19769    }
19770
19771    #[test]
19772    fn rate_limit_unit_from_window_rejects_non_canonical() {
19773        // Rejection pin on the parser's accept-set: any Duration
19774        // outside the three-arm [`RateLimitUnit::window`] output set
19775        // (sub-second residue, or a second-magnitude outside `{1, 60,
19776        // 3600}`) must return `None`. A future accidental widening of
19777        // the accept-set (rounding down sub-second residue to the
19778        // nearest arm, admitting `Duration::from_secs(30)` as a
19779        // half-minute unit) would silently drift the parser's accept-
19780        // set from the emitter's — a validated slot with a
19781        // non-canonical window would then round-trip through the
19782        // codec to a canonical form the author never wrote.
19783        assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
19784        assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
19785        assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
19786        assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
19787        assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
19788        assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
19789        assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
19790    }
19791
19792    #[test]
19793    fn rate_limit_unit_from_suffix_rejects_unknown() {
19794        // Rejection pin on the suffix parser's accept-set: any string
19795        // outside the three-arm [`RateLimitUnit::as_suffix`] output
19796        // set must return `None`. Peer of the sibling
19797        // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
19798        // the [`crate::CaixaKind`] `from_wire` accept-set.
19799        for bad in [
19800            "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
19801            " s",
19802        ] {
19803            assert!(
19804                super::RateLimitUnit::from_suffix(bad).is_none(),
19805                "RateLimitUnit::from_suffix({bad:?}) must return None — the \
19806                 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
19807                 outputs"
19808            );
19809        }
19810    }
19811
19812    #[test]
19813    fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
19814        // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
19815        // every canonical `:window` magnitude the validate gate
19816        // accepts must map to the paired [`RateLimitUnit`] arm through
19817        // this accessor. A future validate-gate rebrand that widened
19818        // the accepted-window set without extending [`RateLimitUnit`]
19819        // would silently split the accessor's `Some`-return set from
19820        // the validate gate's accept-set — a slot that satisfies
19821        // validate would land at the accessor with `None`, so a
19822        // consumer past validate that pattern-matches on the returned
19823        // `Some` would silently miss the newly-accepted magnitude.
19824        for (window_secs, expected) in [
19825            (1u64, super::RateLimitUnit::Second),
19826            (60, super::RateLimitUnit::Minute),
19827            (3600, super::RateLimitUnit::Hour),
19828        ] {
19829            let rl = RateLimit {
19830                rate: 100,
19831                window: Duration::from_secs(window_secs),
19832            };
19833            assert_eq!(
19834                rl.canonical_unit(),
19835                Some(expected),
19836                "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
19837                 must return Some({expected:?})"
19838            );
19839        }
19840        // Non-canonical windows the validate gate rejects also return
19841        // None here — the accessor is the typed-enum projection of
19842        // the sibling `is_canonical_rate_limit_window` predicate.
19843        let bad = RateLimit {
19844            rate: 100,
19845            window: Duration::from_secs(30),
19846        };
19847        assert!(
19848            bad.canonical_unit().is_none(),
19849            "RateLimit with a non-canonical window must return None from \
19850             canonical_unit — the validate gate rejects the same set"
19851        );
19852    }
19853
19854    #[test]
19855    fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
19856        // Fail-before-pass-after byte-parity pin: for every canonical
19857        // window the [`rate_limit_codec::render`] arm's emitted string
19858        // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
19859        // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
19860        // the vestigial free helper [`rate_limit_window_unit`] (a
19861        // `find_map`-walked `Duration → &'static str` delegate) onto the
19862        // substrate primitive [`RateLimit::canonical_unit`] typed method
19863        // (a closed-set `match self.window` arm on
19864        // [`RateLimitUnit::from_window`], projected through
19865        // [`RateLimitUnit::as_suffix`] via the enum's
19866        // [`std::fmt::Display`] impl). A future re-routing of the render
19867        // arm through a differently-computed unit projection would break
19868        // this pin at build time rather than as a silent per-consumer
19869        // codec round-trip drift far from the substrate primitive edit.
19870        //
19871        // Sibling to the peer
19872        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
19873        // on the free-helper axis: that pin locks the two projections
19874        // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
19875        // on the closed-set arm table; this pin locks the codec's render
19876        // arm reads through the typed accessor rather than the free
19877        // helper. Two production consumers of the canonical-unit axis
19878        // now key off one typed dispatch on the substrate primitive.
19879        for (window_secs, unit) in [
19880            (1u64, super::RateLimitUnit::Second),
19881            (60, super::RateLimitUnit::Minute),
19882            (3600, super::RateLimitUnit::Hour),
19883        ] {
19884            let rl = RateLimit {
19885                rate: 42,
19886                window: Duration::from_secs(window_secs),
19887            };
19888            let policy = MeshPolicy {
19889                rate_limit: Some(rl),
19890                ..Default::default()
19891            };
19892            let json = serde_json::to_string(&policy).unwrap();
19893            let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
19894            assert!(
19895                json.contains(&expected),
19896                "rate_limit_codec::render must emit {expected} (via \
19897                 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
19898                 for a {window_secs}s window; serialized MeshPolicy was: {json}"
19899            );
19900            // And the accessor route resolves to the same typed unit
19901            // the render arm's Display formatting is asked to produce —
19902            // so a future edit that split the two paths (one through
19903            // the accessor, one through a re-introduced free helper)
19904            // trips this pin.
19905            assert_eq!(
19906                rl.canonical_unit(),
19907                Some(unit),
19908                "RateLimit::canonical_unit must return Some({unit:?}) for a \
19909                 {window_secs}s window; the codec render arm reads the same \
19910                 typed unit through this accessor"
19911            );
19912        }
19913    }
19914
19915    #[test]
19916    fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
19917        // Fail-before-pass-after byte-parity pin on the validate gate's
19918        // canonical-window shape probe: every non-canonical `:window`
19919        // the free-helper predicate [`is_canonical_rate_limit_window`]
19920        // rejects is also rejected by the substrate primitive
19921        // [`RateLimit::canonical_unit`] `.is_none()` route the validate
19922        // gate now reads through, and vice versa on the accepted set
19923        // (the three canonical windows). Locks the migration from the
19924        // free helper onto the substrate primitive: a future re-routing
19925        // of one of the two paths through a differently-computed unit
19926        // projection would silently split the codec's accepted set from
19927        // the validate gate's accepted set — a two-consumer drift the
19928        // codec-round-trip pin
19929        // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
19930        // above closes on the render arm and this pin closes on the
19931        // validate arm.
19932        for canonical_window_secs in [1u64, 60, 3600] {
19933            let mut s = three_member_spec();
19934            let rl = RateLimit {
19935                rate: 100,
19936                window: Duration::from_secs(canonical_window_secs),
19937            };
19938            s.politicas.rate_limit = Some(rl);
19939            assert!(
19940                s.validate().is_ok(),
19941                "canonical {canonical_window_secs}s window must pass \
19942                 validate_politicas — the validate gate now reads \
19943                 RateLimit::canonical_unit().is_none() and the accessor \
19944                 returns Some on every canonical arm"
19945            );
19946            assert!(
19947                rl.canonical_unit().is_some(),
19948                "canonical {canonical_window_secs}s window must resolve to \
19949                 Some on RateLimit::canonical_unit — the validate gate reads \
19950                 this accessor directly"
19951            );
19952        }
19953        for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
19954            let mut s = three_member_spec();
19955            let rl = RateLimit {
19956                rate: 100,
19957                window: Duration::from_secs(non_canonical_window_secs),
19958            };
19959            s.politicas.rate_limit = Some(rl);
19960            assert_eq!(
19961                s.validate().unwrap_err(),
19962                AplicacaoError::PolicyRateLimitWindowNotCanonical {
19963                    window: rl.window(),
19964                },
19965                "non-canonical {non_canonical_window_secs}s window must be \
19966                 rejected by validate_politicas — the validate gate now \
19967                 keys off RateLimit::canonical_unit().is_none()"
19968            );
19969            assert!(
19970                rl.canonical_unit().is_none(),
19971                "non-canonical {non_canonical_window_secs}s window must \
19972                 resolve to None on RateLimit::canonical_unit — the two \
19973                 paths (the free helper the validate gate previously read \
19974                 and the substrate primitive the validate gate now reads) \
19975                 must agree on the same rejected set"
19976            );
19977        }
19978        // And the substrate-primitive [`RateLimit::canonical_unit`]
19979        // accessor's accepted-window set matches the codec's parse arm's
19980        // accepted-suffix set on every canonical / non-canonical shape,
19981        // so a future silent drift between the codec's accepted set and
19982        // the validate gate's accepted set is a build error at test time
19983        // (both consumers key off the same closed-set enum's `match self`
19984        // arms). The predecessor free helper `is_canonical_rate_limit_window`
19985        // — a delegate that composed [`RateLimitUnit::from_window`] with
19986        // `.is_some()` — was deleted after this migration; the
19987        // canonical-window set now lives on exactly one typed dispatch
19988        // on the substrate primitive.
19989        for (secs, expected) in [
19990            (1u64, true),
19991            (60, true),
19992            (3600, true),
19993            (2, false),
19994            (30, false),
19995            (86_400, false),
19996        ] {
19997            let window = Duration::from_secs(secs);
19998            let rl = RateLimit { rate: 1, window };
19999            assert_eq!(
20000                rl.canonical_unit().is_some(),
20001                expected,
20002                "RateLimit::canonical_unit().is_some() must agree with the \
20003                 codec-accepted canonical-window set on {secs}s"
20004            );
20005            let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
20006                1 => "s",
20007                60 => "m",
20008                3600 => "h",
20009                _ => return,
20010            })
20011            .is_some_and(|d| d == window);
20012            if expected {
20013                assert!(
20014                    suffix_from_axis,
20015                    "the codec's `&str → Duration` axis \
20016                     ({secs}s) must round-trip to the same Duration the \
20017                     substrate primitive's accessor returns Some on"
20018                );
20019            }
20020        }
20021    }
20022
20023    #[test]
20024    fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
20025        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
20026        // derive: for each of the three variants, exactly one of the
20027        // generated `is_second` / `is_minute` / `is_hour` predicates
20028        // returns `true` and the other two return `false`. Peer of
20029        // the sibling
20030        // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
20031        // sibling `IsVariant`-derived closed-set typed-enum pins.
20032        let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
20033            (super::RateLimitUnit::Second, [true, false, false]),
20034            (super::RateLimitUnit::Minute, [false, true, false]),
20035            (super::RateLimitUnit::Hour, [false, false, true]),
20036        ];
20037        for (variant, expected) in rows {
20038            let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
20039            assert_eq!(
20040                observed, expected,
20041                "RateLimitUnit::{variant:?} is_* predicates must partition \
20042                 the arm set (second, minute, hour); got {observed:?}"
20043            );
20044        }
20045    }
20046
20047    #[test]
20048    fn rejects_policy_timeout_sub_millisecond() {
20049        // A purely sub-millisecond `Duration` (`from_micros(500)` =
20050        // 500_000 ns) is not the zero `Duration` — the `is_zero()`
20051        // arm passes — but `as_millis() == 0`, so the shared codec's
20052        // `render` arm returns the literal `"0s"`, which the
20053        // codec's `parse` arm then deserializes as `Duration::ZERO`
20054        // and the `PolicyTimeoutZero` zero-floor gate would reject
20055        // on re-validate. Pin the rejection at the typed slot's
20056        // canonical-floor gate so the round-trip break surfaces at
20057        // validate time, naming the offending `Duration`, rather
20058        // than at the next serialize → deserialize round-trip far
20059        // from the source `caixa.lisp`.
20060        let mut s = three_member_spec();
20061        let timeout = Duration::from_micros(500);
20062        s.politicas.timeout = Some(timeout);
20063        assert_eq!(
20064            s.validate().unwrap_err(),
20065            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
20066        );
20067    }
20068
20069    #[test]
20070    fn rejects_policy_timeout_non_integer_millisecond() {
20071        // A `Duration` with non-integer-millisecond residue
20072        // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
20073        // through the shared codec's `render` arm as `"1ms"` (the
20074        // `as_millis()` floor truncates), which the codec's `parse`
20075        // arm then deserializes as `Duration::from_millis(1)` =
20076        // 1_000_000 ns — silently *different* from the original.
20077        // Pin the rejection so this round-trip break surfaces at
20078        // validate time, where the offending `Duration` is named,
20079        // rather than as a silent value-laundered round-trip on the
20080        // next codec round-trip.
20081        let mut s = three_member_spec();
20082        let timeout = Duration::from_micros(1500);
20083        s.politicas.timeout = Some(timeout);
20084        assert_eq!(
20085            s.validate().unwrap_err(),
20086            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
20087        );
20088    }
20089
20090    #[test]
20091    fn accepts_policy_timeout_integer_millisecond_forms() {
20092        // The codec's accepted set — integer multiples of 1ms — is
20093        // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
20094        // `1h` all pass the canonical gate. Pin the canonical-forms
20095        // sweep so a future tightening of the codec's grammar (e.g.
20096        // dropping `:ms`) surfaces here as a test failure rather
20097        // than a silent contract narrowing on the typed slot.
20098        for timeout in [
20099            Duration::from_millis(1),
20100            Duration::from_millis(500),
20101            Duration::from_millis(1500),
20102            Duration::from_secs(30),
20103            Duration::from_secs(120),
20104            Duration::from_secs(3600),
20105        ] {
20106            let mut s = three_member_spec();
20107            s.politicas.timeout = Some(timeout);
20108            s.validate()
20109                .expect("integer-millisecond :timeout must validate");
20110        }
20111    }
20112
20113    #[test]
20114    fn policy_timeout_zero_takes_precedence_over_canonical() {
20115        // `Duration::ZERO` carries `subsec_nanos() == 0` and would
20116        // pass the canonical-millisecond gate; the more self-locating
20117        // `PolicyTimeoutZero` arm (which names the omit-axis
20118        // remediation directly) must fire first. Pin the ordering so
20119        // a future refactor that reorders the arms surfaces here as a
20120        // test failure rather than a silent diagnostic regression.
20121        let mut s = three_member_spec();
20122        s.politicas.timeout = Some(Duration::ZERO);
20123        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
20124    }
20125
20126    #[test]
20127    fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
20128        // The diagnostic envelope carries the offending `Duration`
20129        // verbatim so the author can grep their `caixa.lisp` for
20130        // `:timeout "<value>"` and fix it in one edit. Same
20131        // diagnostic shape every other typed-slot canonical-form
20132        // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
20133        // peer `:rate-limit :window` axis.
20134        let mut s = three_member_spec();
20135        let timeout = Duration::from_nanos(1_000_001);
20136        s.politicas.timeout = Some(timeout);
20137        match s.validate().unwrap_err() {
20138            AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
20139                assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
20140            }
20141            other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
20142        }
20143    }
20144
20145    #[test]
20146    fn rejects_policy_timeout_above_cap() {
20147        // The fail-before-pass-after pin: 3601s = 1h + 1s is
20148        // structurally one canonical-tick past the
20149        // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
20150        // integer-millisecond magnitude the canonical-form arm above
20151        // accepts cleanly, that the codec round-trips losslessly as
20152        // `"3601s"`, and that silently passed validate on every
20153        // pre-gate codebase because the typed slot's only checks were
20154        // the zero-floor and canonical-form arms. The mesh-level
20155        // deadline degenerates only at the runtime substrate (Envoy
20156        // / Cilium L7 timeout overlay) far from the source
20157        // `caixa.lisp` with no field naming the offending policy.
20158        let mut s = three_member_spec();
20159        let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
20160        s.politicas.timeout = Some(timeout);
20161        assert_eq!(
20162            s.validate().unwrap_err(),
20163            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
20164        );
20165    }
20166
20167    #[test]
20168    fn rejects_policy_timeout_one_millisecond_above_cap() {
20169        // Boundary case: exactly 1ms past the cap (the granularity
20170        // the canonical-form gate enforces). Catches a future
20171        // "strictly less than" half-measure and pins the diagnostic
20172        // to name the offending `Duration` verbatim. Peer of
20173        // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
20174        // boundary pin on the sibling `:limits :memory` top edge.
20175        let mut s = three_member_spec();
20176        let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
20177        s.politicas.timeout = Some(timeout);
20178        assert_eq!(
20179            s.validate().unwrap_err(),
20180            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
20181        );
20182    }
20183
20184    #[test]
20185    fn rejects_policy_timeout_far_above_cap() {
20186        // The "obvious authoring footgun" case: a `(:timeout "24h")`
20187        // or `(:timeout "86400s")` — values the canonical-form arm
20188        // accepts as integer-millisecond magnitudes, the codec
20189        // round-trips losslessly through serde, but the mesh-level
20190        // policy cannot honor (a 24-hour synchronous-`:contratos`
20191        // deadline is operationally indistinguishable from
20192        // omit-the-axis). Until this gate landed validate accepted
20193        // it. Pin both common above-cap values (24h, 7d) so a future
20194        // relaxation that drops the upper bound surfaces here.
20195        for timeout in [
20196            Duration::from_secs(86_400),    // 24h
20197            Duration::from_secs(604_800),   // 7d
20198            Duration::from_secs(1_000_000), // ~11.5 days
20199        ] {
20200            let mut s = three_member_spec();
20201            s.politicas.timeout = Some(timeout);
20202            assert_eq!(
20203                s.validate().unwrap_err(),
20204                AplicacaoError::PolicyTimeoutExceedsCap { timeout }
20205            );
20206        }
20207    }
20208
20209    #[test]
20210    fn accepts_policy_timeout_at_cap() {
20211        // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
20212        // must validate. The cap is inclusive on the top edge,
20213        // matching the [`POLICY_RETRIES_MAX`] /
20214        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
20215        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
20216        // sibling capped axes. Pin the boundary explicitly so a
20217        // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
20218        // instead of `>`) surfaces here as a test failure rather
20219        // than a silent contract narrowing.
20220        let mut s = three_member_spec();
20221        s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
20222        s.validate()
20223            .expect("timeout == POLICY_TIMEOUT_MAX must validate");
20224    }
20225
20226    #[test]
20227    fn accepts_policy_timeout_typical_values() {
20228        // The documented production-playbook band positive-control
20229        // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
20230        // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
20231        // plus a sweep through the long-running-workflow band
20232        // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
20233        // validated set explicitly so a future tightening of the
20234        // ceiling surfaces here as a deliberate test edit, not a
20235        // silent contract narrowing.
20236        for timeout in [
20237            Duration::from_millis(1),
20238            Duration::from_millis(500),
20239            Duration::from_secs(1),
20240            Duration::from_secs(10),
20241            Duration::from_secs(15), // Envoy default
20242            Duration::from_secs(30),
20243            Duration::from_secs(60), // AWS App Mesh typical
20244            Duration::from_secs(300),
20245            Duration::from_secs(900),
20246            Duration::from_secs(1800),
20247            Duration::from_secs(3600), // exactly 1h, the cap
20248        ] {
20249            let mut s = three_member_spec();
20250            s.politicas.timeout = Some(timeout);
20251            s.validate()
20252                .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
20253        }
20254    }
20255
20256    #[test]
20257    fn policy_timeout_zero_takes_precedence_over_cap() {
20258        // The cross-arm ordering pin: `Duration::ZERO` is
20259        // structurally outside both `>= 1ms` (zero-floor) and
20260        // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
20261        // diagnostic is the more self-locating one (it directly
20262        // names the omit-axis remediation), so the validate gate
20263        // must fire on zero first. Same shape every other
20264        // zero-then-shape ordering on this surface uses
20265        // ([`AplicacaoError::PolicyRetriesZero`] then
20266        // [`AplicacaoError::PolicyRetriesExceedsCap`];
20267        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
20268        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
20269        let mut s = three_member_spec();
20270        s.politicas.timeout = Some(Duration::ZERO);
20271        assert_eq!(
20272            s.validate().unwrap_err(),
20273            AplicacaoError::PolicyTimeoutZero,
20274            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
20275        );
20276    }
20277
20278    #[test]
20279    fn policy_timeout_canonical_takes_precedence_over_cap() {
20280        // The cross-arm ordering pin: a `Duration` that is *both*
20281        // sub-millisecond (non-canonical-form) and structurally
20282        // above the cap surfaces the canonical-form diagnostic
20283        // first, because the round-trip-shape break is the more
20284        // fundamental issue (the value can't even round-trip
20285        // through the codec, so the cap diagnostic naming
20286        // `1ms..=1h` would be misleading — there's no integer-ms
20287        // form of the offending value). Pin the order so a future
20288        // refactor that reorders the arms surfaces here as a test
20289        // failure rather than a silent diagnostic regression.
20290        let mut s = three_member_spec();
20291        // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
20292        // *and* total magnitude above the 1h cap.
20293        let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
20294        s.politicas.timeout = Some(timeout);
20295        assert_eq!(
20296            s.validate().unwrap_err(),
20297            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
20298            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
20299        );
20300    }
20301
20302    #[test]
20303    fn policy_timeout_cap_diagnostic_carries_offending_value() {
20304        // The diagnostic-shape pin: the offending `Duration` is
20305        // carried verbatim into the
20306        // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
20307        // surfaced error message names the value the author wrote
20308        // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
20309        // exceeds the mesh-policy ceiling …"`), not just the cap.
20310        // Same self-locating diagnostic shape every other typed-cap
20311        // arm on this surface carries
20312        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
20313        // offending retry count verbatim).
20314        let mut s = three_member_spec();
20315        let timeout = Duration::from_secs(7200); // 2h
20316        s.politicas.timeout = Some(timeout);
20317        let err = s.validate().unwrap_err();
20318        assert!(
20319            matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
20320            "got {err:?}"
20321        );
20322        let msg = err.to_string();
20323        assert!(
20324            msg.contains("7200"),
20325            ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
20326        );
20327    }
20328
20329    #[test]
20330    fn policy_timeout_cap_pins_canonical_value() {
20331        // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
20332        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
20333        // the shared duration codec emits as a clean canonical
20334        // string (`"<n>h"`). Pinning the literal value here surfaces
20335        // a future drift (a relaxation to 24h, a tightening to 5m)
20336        // as a deliberate test edit, not a silent contract
20337        // narrowing. Same shape every other typed-cap value pin on
20338        // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
20339        assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
20340        assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
20341    }
20342
20343    #[test]
20344    fn policy_timeout_cap_value_round_trips_through_codec() {
20345        // The codec round-trip property the cap arm preserves: the
20346        // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
20347        // the shared duration codec — every value at the cap renders
20348        // to a clean canonical string (`"1h"`) and parses back to
20349        // the same `Duration`. Pin this so a future drift between
20350        // the cap constant and the codec's largest emitted unit
20351        // surfaces here. Same shape every other typed boundary pin
20352        // on this surface uses
20353        // (`wasm32_memory_cap_matches_parsed_4_gib`).
20354        let policy = MeshPolicy {
20355            timeout: Some(POLICY_TIMEOUT_MAX),
20356            ..Default::default()
20357        };
20358        let json = serde_json::to_string(&policy).unwrap();
20359        // The codec emits `"1h"` for the canonical 1-hour magnitude.
20360        assert!(
20361            json.contains("\"1h\""),
20362            "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
20363        );
20364        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
20365        assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
20366    }
20367
20368    #[test]
20369    fn rejects_circuit_breaker_window_sub_millisecond() {
20370        // Peer of the `:timeout` sub-millisecond arm on the second
20371        // typed-`Duration` `:politicas` axis: a purely sub-ms
20372        // `Duration` (`from_micros(500)`) renders through the shared
20373        // codec as `"0s"`, which the codec parses back to
20374        // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
20375        // zero-floor gate then rejects on re-validate.
20376        let mut s = three_member_spec();
20377        let window = Duration::from_micros(500);
20378        s.politicas.circuit_breaker = Some(CircuitBreaker {
20379            max_failures: 5,
20380            window,
20381        });
20382        assert_eq!(
20383            s.validate().unwrap_err(),
20384            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
20385        );
20386    }
20387
20388    #[test]
20389    fn rejects_circuit_breaker_window_non_integer_millisecond() {
20390        // Peer of the `:timeout` non-integer-ms arm: a `Duration`
20391        // with non-integer-millisecond residue renders through the
20392        // shared codec as the truncated `"<n>ms"` form, parsing back
20393        // to a *different* `Duration` on the next round-trip.
20394        let mut s = three_member_spec();
20395        let window = Duration::from_micros(1500);
20396        s.politicas.circuit_breaker = Some(CircuitBreaker {
20397            max_failures: 5,
20398            window,
20399        });
20400        assert_eq!(
20401            s.validate().unwrap_err(),
20402            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
20403        );
20404    }
20405
20406    #[test]
20407    fn accepts_circuit_breaker_window_integer_millisecond_forms() {
20408        // The canonical-forms sweep on the breaker axis: every
20409        // integer-ms multiple the codec round-trips losslessly
20410        // passes the canonical gate.
20411        //
20412        // Clears `:timeout` from the fixture so this per-axis sweep
20413        // covers windows shorter than the fixture's 30s timeout
20414        // (1ms, 500ms, 1500ms) — the sub-timeout arm is a
20415        // structurally-inert breaker
20416        // ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]) that
20417        // the cross-axis gate at the end of
20418        // [`AplicacaoSpec::validate_politicas`] rejects on the paired
20419        // `(:timeout, :window)` shape, not on the per-axis
20420        // integer-millisecond canonical-form shape this test pins.
20421        // The paired shape is covered by
20422        // `rejects_circuit_breaker_window_below_timeout`.
20423        for window in [
20424            Duration::from_millis(1),
20425            Duration::from_millis(500),
20426            Duration::from_millis(1500),
20427            Duration::from_secs(30),
20428            Duration::from_secs(60),
20429            Duration::from_secs(3600),
20430        ] {
20431            let mut s = three_member_spec();
20432            s.politicas.timeout = None;
20433            s.politicas.circuit_breaker = Some(CircuitBreaker {
20434                max_failures: 5,
20435                window,
20436            });
20437            s.validate()
20438                .expect("integer-millisecond :circuit-breaker :window must validate");
20439        }
20440    }
20441
20442    #[test]
20443    fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
20444        // `Duration::ZERO` would pass the canonical-ms gate (the
20445        // sub-ns residue is zero) but must surface the narrower
20446        // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
20447        // remediation.
20448        let mut s = three_member_spec();
20449        s.politicas.circuit_breaker = Some(CircuitBreaker {
20450            max_failures: 5,
20451            window: Duration::ZERO,
20452        });
20453        assert_eq!(
20454            s.validate().unwrap_err(),
20455            AplicacaoError::PolicyBreakerZeroWindow
20456        );
20457    }
20458
20459    #[test]
20460    fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
20461        // Both axes invalid: max_failures == 0 *and* window is
20462        // sub-ms. The validate gate must fire on max_failures first
20463        // (matching the existing ordering pin
20464        // `rejects_circuit_breaker_zero_max_failures` enshrines), so
20465        // the existing diagnostic continues to lead with the simpler
20466        // "zero threshold" framing.
20467        let mut s = three_member_spec();
20468        s.politicas.circuit_breaker = Some(CircuitBreaker {
20469            max_failures: 0,
20470            window: Duration::from_micros(500),
20471        });
20472        assert_eq!(
20473            s.validate().unwrap_err(),
20474            AplicacaoError::PolicyBreakerZeroFailures
20475        );
20476    }
20477
20478    #[test]
20479    fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
20480        let mut s = three_member_spec();
20481        let window = Duration::from_nanos(60_000_000_001);
20482        s.politicas.circuit_breaker = Some(CircuitBreaker {
20483            max_failures: 5,
20484            window,
20485        });
20486        match s.validate().unwrap_err() {
20487            AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
20488                assert_eq!(w, window, "diagnostic must carry the offending Duration");
20489            }
20490            other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
20491        }
20492    }
20493
20494    #[test]
20495    fn rejects_circuit_breaker_window_above_cap() {
20496        // The fail-before-pass-after pin: 3601s = 1h + 1s is
20497        // structurally one canonical-tick past the
20498        // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
20499        // integer-millisecond magnitude the canonical-form arm above
20500        // accepts cleanly, that the codec round-trips losslessly as
20501        // `"3601s"`, and that silently passed validate on every
20502        // pre-gate codebase because the typed slot's only checks were
20503        // the zero-floor and canonical-form arms. The
20504        // rolling-window-to-lifetime-counter degeneration surfaces
20505        // only at the runtime substrate (Envoy's outlier_detection
20506        // interval, the future CiliumClusterwideEnvoyConfig overlay)
20507        // far from the source `caixa.lisp` with no field naming the
20508        // offending policy.
20509        let mut s = three_member_spec();
20510        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
20511        s.politicas.circuit_breaker = Some(CircuitBreaker {
20512            max_failures: 5,
20513            window,
20514        });
20515        assert_eq!(
20516            s.validate().unwrap_err(),
20517            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
20518        );
20519    }
20520
20521    #[test]
20522    fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
20523        // Boundary case: exactly 1ms past the cap (the granularity the
20524        // canonical-form gate enforces). Catches a future "strictly
20525        // less than" half-measure and pins the diagnostic to name the
20526        // offending `Duration` verbatim. Peer of
20527        // `rejects_policy_timeout_one_millisecond_above_cap` on the
20528        // sibling duration-typed `:politicas :timeout` top edge.
20529        let mut s = three_member_spec();
20530        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
20531        s.politicas.circuit_breaker = Some(CircuitBreaker {
20532            max_failures: 5,
20533            window,
20534        });
20535        assert_eq!(
20536            s.validate().unwrap_err(),
20537            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
20538        );
20539    }
20540
20541    #[test]
20542    fn rejects_circuit_breaker_window_far_above_cap() {
20543        // The "obvious authoring footgun" case: a `(:window "24h")` or
20544        // `(:window "86400s")` — values the canonical-form arm
20545        // accepts as integer-millisecond magnitudes, the codec
20546        // round-trips losslessly through serde, but the
20547        // rolling-window breaker contract cannot honor (a 24-hour
20548        // rolling failure window is operationally a lifetime counter).
20549        // Until this gate landed validate accepted it. Pin both common
20550        // above-cap values (24h, 7d) so a future relaxation that
20551        // drops the upper bound surfaces here.
20552        for window in [
20553            Duration::from_secs(86_400),    // 24h
20554            Duration::from_secs(604_800),   // 7d
20555            Duration::from_secs(1_000_000), // ~11.5 days
20556        ] {
20557            let mut s = three_member_spec();
20558            s.politicas.circuit_breaker = Some(CircuitBreaker {
20559                max_failures: 5,
20560                window,
20561            });
20562            assert_eq!(
20563                s.validate().unwrap_err(),
20564                AplicacaoError::PolicyBreakerWindowExceedsCap { window }
20565            );
20566        }
20567    }
20568
20569    #[test]
20570    fn accepts_circuit_breaker_window_at_cap() {
20571        // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
20572        // (1h) — must validate. The cap is inclusive on the top edge,
20573        // matching the [`POLICY_TIMEOUT_MAX`] /
20574        // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
20575        // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
20576        // sibling capped axes. Pin the boundary explicitly so a
20577        // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
20578        // instead of `>`) surfaces here as a test failure rather than
20579        // a silent contract narrowing.
20580        let mut s = three_member_spec();
20581        s.politicas.circuit_breaker = Some(CircuitBreaker {
20582            max_failures: 5,
20583            window: POLICY_BREAKER_WINDOW_MAX,
20584        });
20585        s.validate()
20586            .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
20587    }
20588
20589    #[test]
20590    fn accepts_circuit_breaker_window_typical_values() {
20591        // The documented production-playbook band positive-control
20592        // sweep — every value Hystrix / resilience4j / Istio / Envoy
20593        // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
20594        // through the long-tail failure-detection band (15m, 30m, 1h)
20595        // the cap accepts. Pin the inclusive validated set explicitly
20596        // so a future tightening of the ceiling surfaces here as a
20597        // deliberate test edit, not a silent contract narrowing.
20598        //
20599        // Clears `:timeout` from the fixture so this per-axis sweep
20600        // covers windows shorter than the fixture's 30s timeout
20601        // (Hystrix's 10s default, resilience4j's 30s, and the
20602        // sub-second warm-up band) — every such value is a
20603        // structurally-inert breaker under the cross-axis gate at the
20604        // end of [`AplicacaoSpec::validate_politicas`]
20605        // ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]), and
20606        // the paired `(:timeout, :window)` shape is covered by
20607        // `rejects_circuit_breaker_window_below_timeout`; this
20608        // per-axis pin ranges only over the per-axis-bracket accept set.
20609        for window in [
20610            Duration::from_millis(1),
20611            Duration::from_millis(500),
20612            Duration::from_secs(1),
20613            Duration::from_secs(10), // Hystrix / Istio / Envoy default
20614            Duration::from_secs(30),
20615            Duration::from_secs(60),  // resilience4j typical
20616            Duration::from_secs(300), // AWS App Mesh typical
20617            Duration::from_secs(900),
20618            Duration::from_secs(1800),
20619            Duration::from_secs(3600), // exactly 1h, the cap
20620        ] {
20621            let mut s = three_member_spec();
20622            s.politicas.timeout = None;
20623            s.politicas.circuit_breaker = Some(CircuitBreaker {
20624                max_failures: 5,
20625                window,
20626            });
20627            s.validate()
20628                .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
20629        }
20630    }
20631
20632    #[test]
20633    fn circuit_breaker_zero_window_takes_precedence_over_cap() {
20634        // The cross-arm ordering pin: `Duration::ZERO` is structurally
20635        // outside both `>= 1ms` (zero-floor) and
20636        // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
20637        // diagnostic is the more self-locating one (it directly names
20638        // the omit-axis remediation), so the validate gate must fire
20639        // on zero first. Same shape every other zero-then-cap
20640        // ordering on this surface uses
20641        // ([`AplicacaoError::PolicyTimeoutZero`] then
20642        // [`AplicacaoError::PolicyTimeoutExceedsCap`];
20643        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
20644        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
20645        let mut s = three_member_spec();
20646        s.politicas.circuit_breaker = Some(CircuitBreaker {
20647            max_failures: 5,
20648            window: Duration::ZERO,
20649        });
20650        assert_eq!(
20651            s.validate().unwrap_err(),
20652            AplicacaoError::PolicyBreakerZeroWindow,
20653            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
20654        );
20655    }
20656
20657    #[test]
20658    fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
20659        // The cross-arm ordering pin: a `Duration` that is *both*
20660        // sub-millisecond (non-canonical-form) and structurally above
20661        // the cap surfaces the canonical-form diagnostic first,
20662        // because the round-trip-shape break is the more fundamental
20663        // issue (the value can't even round-trip through the codec, so
20664        // the cap diagnostic naming `1ms..=1h` would be misleading —
20665        // there's no integer-ms form of the offending value). Pin the
20666        // order so a future refactor that reorders the arms surfaces
20667        // here as a test failure rather than a silent diagnostic
20668        // regression. Peer of
20669        // `policy_timeout_canonical_takes_precedence_over_cap` on the
20670        // sibling duration-typed `:politicas :timeout` axis.
20671        let mut s = three_member_spec();
20672        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
20673        s.politicas.circuit_breaker = Some(CircuitBreaker {
20674            max_failures: 5,
20675            window,
20676        });
20677        assert_eq!(
20678            s.validate().unwrap_err(),
20679            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
20680            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
20681        );
20682    }
20683
20684    #[test]
20685    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
20686        // The cross-arm ordering pin between the two breaker axes: a
20687        // `CircuitBreaker` whose *both* `max_failures` is above its
20688        // cap *and* `window` is above its cap surfaces the
20689        // max-failures cap diagnostic first, because the validate
20690        // gate visits the failures arm before the window arm. Pin the
20691        // order so a future refactor that reorders the breaker arms
20692        // surfaces here.
20693        let mut s = three_member_spec();
20694        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
20695        s.politicas.circuit_breaker = Some(CircuitBreaker {
20696            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
20697            window,
20698        });
20699        assert_eq!(
20700            s.validate().unwrap_err(),
20701            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
20702                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
20703            },
20704            "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
20705        );
20706    }
20707
20708    #[test]
20709    fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
20710        // The diagnostic-shape pin: the offending `Duration` is
20711        // carried verbatim into the
20712        // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
20713        // the surfaced error message names the value the author wrote
20714        // (`":politicas :circuit-breaker :window (Duration { secs:
20715        // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
20716        // just the cap. Same self-locating diagnostic shape every
20717        // other typed-cap arm on this surface carries
20718        // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
20719        // offending `Duration` verbatim).
20720        let mut s = three_member_spec();
20721        let window = Duration::from_secs(7200); // 2h
20722        s.politicas.circuit_breaker = Some(CircuitBreaker {
20723            max_failures: 5,
20724            window,
20725        });
20726        let err = s.validate().unwrap_err();
20727        assert!(
20728            matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
20729            "got {err:?}"
20730        );
20731        let msg = err.to_string();
20732        assert!(
20733            msg.contains("7200"),
20734            ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
20735        );
20736    }
20737
20738    #[test]
20739    fn circuit_breaker_window_cap_pins_canonical_value() {
20740        // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
20741        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
20742        // shared duration codec emits as a clean canonical string
20743        // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
20744        // the sibling duration-typed `:politicas :timeout` axis (the
20745        // two duration-typed `:politicas` axes share a uniform top
20746        // edge). Pinning the literal value here surfaces a future
20747        // drift (a relaxation to 24h, a tightening to 5m) as a
20748        // deliberate test edit, not a silent contract narrowing. Same
20749        // shape every other typed-cap value pin on this surface uses
20750        // (`policy_timeout_cap_pins_canonical_value`).
20751        assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
20752        assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
20753        assert_eq!(
20754            POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
20755            "the two duration-typed `:politicas` caps share the same top edge"
20756        );
20757    }
20758
20759    #[test]
20760    fn circuit_breaker_window_cap_value_round_trips_through_codec() {
20761        // The codec round-trip property the cap arm preserves: the
20762        // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
20763        // through the shared duration codec — every value at the cap
20764        // renders to a clean canonical string (`"1h"`) and parses back
20765        // to the same `Duration`. Pin this so a future drift between
20766        // the cap constant and the codec's largest emitted unit
20767        // surfaces here. Same shape every other typed boundary pin on
20768        // this surface uses
20769        // (`policy_timeout_cap_value_round_trips_through_codec`).
20770        let policy = MeshPolicy {
20771            circuit_breaker: Some(CircuitBreaker {
20772                max_failures: 5,
20773                window: POLICY_BREAKER_WINDOW_MAX,
20774            }),
20775            ..Default::default()
20776        };
20777        let json = serde_json::to_string(&policy).unwrap();
20778        // The codec emits `"1h"` for the canonical 1-hour magnitude.
20779        assert!(
20780            json.contains("\"1h\""),
20781            "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
20782        );
20783        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
20784        assert_eq!(
20785            back.circuit_breaker.unwrap().window,
20786            POLICY_BREAKER_WINDOW_MAX
20787        );
20788    }
20789
20790    #[test]
20791    fn is_integer_millisecond_duration_predicate_tracks_codec() {
20792        // Pin the predicate's accepted set against the codec's
20793        // accepted set explicitly. The codec parses
20794        // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
20795        // accepted value is an integer-millisecond multiple — so the
20796        // predicate must accept exactly that set. Same shape every
20797        // other predicate-on-the-typed-slot helper carries
20798        // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
20799        // Read directly from the codec-owned predicate — the crate's
20800        // single source of truth every typed-`Duration` axis now routes
20801        // through via
20802        // [`crate::render::require_positive_canonical_bounded_duration`].
20803        use super::supervisor::duration_codec::is_integer_millisecond_duration;
20804        assert!(is_integer_millisecond_duration(Duration::ZERO));
20805        assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
20806        assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
20807        assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
20808        assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
20809        assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
20810        // Non-integer-millisecond residue: rejected.
20811        assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
20812        assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
20813        assert!(!is_integer_millisecond_duration(Duration::from_micros(
20814            1500
20815        )));
20816        assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
20817        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
20818            999_999
20819        )));
20820        // The 1-ns-past-1ms boundary: rejected (no longer a clean
20821        // integer-millisecond multiple).
20822        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
20823            1_000_001
20824        )));
20825    }
20826
20827    #[test]
20828    fn policy_timeout_validated_value_round_trips_through_codec() {
20829        // The structural property the canonical-ms gate enforces:
20830        // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
20831        // round-trips losslessly through the shared `duration_codec`
20832        // (serialize → string → deserialize → equal value). Pin this
20833        // end-to-end so a future change to either side (the validate
20834        // gate's accepted granularity, the codec's parse/render unit
20835        // set) that breaks the alignment surfaces here. The
20836        // previous-state shape (typed slot accepts arbitrary
20837        // `Duration`, codec only round-trips integer-ms) would fail
20838        // this test for any `Duration::from_micros(1500)` timeout —
20839        // the validate gate now forecloses that.
20840        for timeout in [
20841            Duration::from_millis(1),
20842            Duration::from_millis(1500),
20843            Duration::from_secs(30),
20844            Duration::from_secs(3600),
20845        ] {
20846            let mut s = three_member_spec();
20847            s.politicas.timeout = Some(timeout);
20848            s.validate().unwrap();
20849            let json = serde_json::to_string(&s.politicas).unwrap();
20850            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
20851            assert_eq!(
20852                back.timeout, s.politicas.timeout,
20853                "every validated :timeout must round-trip losslessly through the codec"
20854            );
20855        }
20856    }
20857
20858    #[test]
20859    fn circuit_breaker_window_validated_value_round_trips_through_codec() {
20860        // Peer of the `:timeout` round-trip property on the breaker
20861        // axis.
20862        //
20863        // Clears `:timeout` from the fixture so the round-trip pin
20864        // ranges over sub-timeout `Duration` values (1ms, 1500ms) the
20865        // cross-axis gate would otherwise reject as structurally-inert
20866        // breakers ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]);
20867        // the paired `(:timeout, :window)` cross-axis relation is
20868        // pinned separately by
20869        // `rejects_circuit_breaker_window_below_timeout`, and this
20870        // property is a pure serde-codec round-trip on the per-axis
20871        // slot.
20872        for window in [
20873            Duration::from_millis(1),
20874            Duration::from_millis(1500),
20875            Duration::from_secs(30),
20876            Duration::from_secs(3600),
20877        ] {
20878            let mut s = three_member_spec();
20879            s.politicas.timeout = None;
20880            s.politicas.circuit_breaker = Some(CircuitBreaker {
20881                max_failures: 5,
20882                window,
20883            });
20884            s.validate().unwrap();
20885            let json = serde_json::to_string(&s.politicas).unwrap();
20886            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
20887            assert_eq!(
20888                back.circuit_breaker.unwrap().window,
20889                window,
20890                "every validated :circuit-breaker :window must round-trip losslessly"
20891            );
20892        }
20893    }
20894
20895    #[test]
20896    fn rejects_circuit_breaker_window_below_timeout() {
20897        // The fail-before-pass-after pin on the cross-axis
20898        // `(:timeout, :circuit-breaker :window)` invariant. Each axis
20899        // is individually well-formed under its own per-axis bracket
20900        // (both integer-millisecond, both above the zero floor, both
20901        // below the cap), but the pair is a structurally-inert
20902        // breaker: a call dispatched at t=0 is declared failed at
20903        // t=30s, by which point the 10s rolling window open at
20904        // dispatch has already rolled twice, so no window can hold
20905        // a timeout-derived failure however high the call volume.
20906        //
20907        // Envoy's `outlier_detection.interval` against the per-route
20908        // request timeout carries the identical relation; Hystrix
20909        // ships the canonical ratio in its defaults (10s window
20910        // against a 1s timeout — a 10× ratio, not a 3× under-ratio).
20911        //
20912        // Pin both the diagnostic arm and the payload values so a
20913        // future re-shape of the arm surfaces here as a deliberate
20914        // test edit.
20915        let mut s = three_member_spec();
20916        s.politicas.timeout = Some(Duration::from_secs(30));
20917        s.politicas.circuit_breaker = Some(CircuitBreaker {
20918            max_failures: 5,
20919            window: Duration::from_secs(10),
20920        });
20921        assert_eq!(
20922            s.validate().unwrap_err(),
20923            AplicacaoError::PolicyBreakerWindowBelowTimeout {
20924                window: Duration::from_secs(10),
20925                timeout: Duration::from_secs(30),
20926            }
20927        );
20928    }
20929
20930    #[test]
20931    fn accepts_circuit_breaker_window_equal_to_timeout() {
20932        // Boundary pin: `:window == :timeout` is the smallest window
20933        // that structurally admits at least one full timeout-derived
20934        // failure before the rolling interval closes (the invariant
20935        // is `:window >= :timeout`, not strict inequality). Catches
20936        // a future off-by-one tightening that would drift the accept
20937        // set away from the codified [`MeshPolicy::breaker_window_
20938        // observes_timeout`] predicate.
20939        let mut s = three_member_spec();
20940        s.politicas.timeout = Some(Duration::from_secs(30));
20941        s.politicas.circuit_breaker = Some(CircuitBreaker {
20942            max_failures: 5,
20943            window: Duration::from_secs(30),
20944        });
20945        s.validate()
20946            .expect("window == timeout is the boundary accept case");
20947    }
20948
20949    #[test]
20950    fn accepts_circuit_breaker_window_above_timeout() {
20951        // Positive-control sweep across the production-playbook band —
20952        // Hystrix (1s timeout / 10s window, 10× ratio), Istio (5s /
20953        // 30s, 6×), Envoy (10s / 60s, 6×), resilience4j (30s / 300s,
20954        // 10×), AWS App Mesh (60s / 300s, 5×). Every pair a real
20955        // playbook recommends must validate under the cross-axis gate.
20956        for (timeout, window) in [
20957            (Duration::from_secs(1), Duration::from_secs(10)),
20958            (Duration::from_secs(5), Duration::from_secs(30)),
20959            (Duration::from_secs(10), Duration::from_secs(60)),
20960            (Duration::from_secs(30), Duration::from_secs(300)),
20961            (Duration::from_secs(60), Duration::from_secs(300)),
20962        ] {
20963            let mut s = three_member_spec();
20964            s.politicas.timeout = Some(timeout);
20965            s.politicas.circuit_breaker = Some(CircuitBreaker {
20966                max_failures: 5,
20967                window,
20968            });
20969            s.validate().unwrap_or_else(|e| {
20970                panic!(
20971                    "production-playbook pair timeout={timeout:?}/window={window:?} must \
20972                     validate; got {e:?}"
20973                )
20974            });
20975        }
20976    }
20977
20978    #[test]
20979    fn circuit_breaker_window_below_timeout_by_one_millisecond_rejected() {
20980        // Off-by-one boundary pin: a window exactly 1ms shy of the
20981        // timeout is still structurally inert under the invariant
20982        // (the dispatch-to-report lag is `timeout`, so the window
20983        // must span at least one such lag). Catches a future
20984        // strict-inequality relaxation that would silently drift
20985        // the accept boundary.
20986        let timeout = Duration::from_secs(30);
20987        let window = Duration::from_millis(29_999);
20988        let mut s = three_member_spec();
20989        s.politicas.timeout = Some(timeout);
20990        s.politicas.circuit_breaker = Some(CircuitBreaker {
20991            max_failures: 5,
20992            window,
20993        });
20994        assert_eq!(
20995            s.validate().unwrap_err(),
20996            AplicacaoError::PolicyBreakerWindowBelowTimeout { window, timeout }
20997        );
20998    }
20999
21000    #[test]
21001    fn cross_axis_gate_vacuous_when_timeout_absent() {
21002        // The predicate is vacuously `true` when `:timeout` is None —
21003        // a `:circuit-breaker` alone declares no relation to a
21004        // substrate-imposed deadline (the failure signal reaches the
21005        // breaker from the transport's own error surface, so no
21006        // dispatch-to-report lag is knowable at author time). Pin so
21007        // a future tightening that made the gate opinionated on
21008        // half-declared pairs surfaces here.
21009        let mut s = three_member_spec();
21010        s.politicas.timeout = None;
21011        s.politicas.circuit_breaker = Some(CircuitBreaker {
21012            max_failures: 5,
21013            window: Duration::from_millis(1),
21014        });
21015        s.validate().expect(
21016            "cross-axis gate must be vacuous when :timeout is None, however small :window is",
21017        );
21018    }
21019
21020    #[test]
21021    fn cross_axis_gate_vacuous_when_circuit_breaker_absent() {
21022        // Peer of the sibling `:timeout`-absent case: a `:timeout`
21023        // without a `:circuit-breaker` declares a per-call deadline
21024        // without any rolling-window failure accounting, so the pair
21025        // is undeclared and the cross-axis gate has nothing to check.
21026        let mut s = three_member_spec();
21027        s.politicas.timeout = Some(Duration::from_secs(3600));
21028        s.politicas.circuit_breaker = None;
21029        s.validate().expect(
21030            "cross-axis gate must be vacuous when :circuit-breaker is None, \
21031             however large :timeout is",
21032        );
21033    }
21034
21035    #[test]
21036    fn cross_axis_gate_runs_after_per_axis_brackets() {
21037        // Ordering pin: a pair whose window is *both* zero-floor-
21038        // violating and structurally below the timeout must surface
21039        // the per-axis zero-floor arm first — the zero-floor
21040        // diagnostic is more self-locating (its omit-axis remediation
21041        // is directly named), where the cross-axis arm would send the
21042        // author to reconcile two values one of which is not a
21043        // meaningful window at all. Same ordering discipline every
21044        // per-axis bracket carries internally (zero-floor before
21045        // canonical-form before cap).
21046        let mut s = three_member_spec();
21047        s.politicas.timeout = Some(Duration::from_secs(30));
21048        s.politicas.circuit_breaker = Some(CircuitBreaker {
21049            max_failures: 5,
21050            window: Duration::ZERO,
21051        });
21052        assert_eq!(
21053            s.validate().unwrap_err(),
21054            AplicacaoError::PolicyBreakerZeroWindow,
21055            "per-axis zero-floor arm must fire before the cross-axis gate"
21056        );
21057    }
21058
21059    #[test]
21060    fn breaker_window_observes_timeout_predicate_matches_gate_semantic() {
21061        // Equivalence pin: the substrate-canonical
21062        // [`MeshPolicy::breaker_window_observes_timeout`] predicate
21063        // and the [`AplicacaoSpec::validate_politicas`] cross-axis
21064        // arm must discriminate the same set on every pair covered
21065        // by their shared invariant. A future refactor of either
21066        // side that breaks the equivalence trips here rather than as
21067        // a divergence between the predicate's Boolean answer and
21068        // the validate gate's Ok/Err arm — the same
21069        // predicate-vs-gate coherence discipline the peer
21070        // [`PlacementStrategy::is_shard_keyed`] predicate carries
21071        // against `AplicacaoSpec::validate_placement`. The sweep
21072        // covers both arms of the invariant (below, equal, above)
21073        // and both vacuous arms (None `:timeout`, None
21074        // `:circuit-breaker`), so the equivalence holds
21075        // exhaustively over the axis-covered accept and reject sets.
21076        let cases: &[(Option<Duration>, Option<Duration>)] = &[
21077            (Some(Duration::from_secs(30)), Some(Duration::from_secs(10))),
21078            (Some(Duration::from_secs(30)), Some(Duration::from_secs(29))),
21079            (Some(Duration::from_secs(30)), Some(Duration::from_secs(30))),
21080            (Some(Duration::from_secs(30)), Some(Duration::from_secs(60))),
21081            (Some(Duration::from_secs(1)), Some(Duration::from_secs(10))),
21082            (None, Some(Duration::from_secs(1))),
21083            (Some(Duration::from_secs(30)), None),
21084            (None, None),
21085        ];
21086        for (timeout, window) in cases.iter().copied() {
21087            let politicas = MeshPolicy {
21088                timeout,
21089                circuit_breaker: window.map(|w| CircuitBreaker {
21090                    max_failures: 5,
21091                    window: w,
21092                }),
21093                ..Default::default()
21094            };
21095            let predicate = politicas.breaker_window_observes_timeout();
21096
21097            let mut s = three_member_spec();
21098            s.politicas = politicas.clone();
21099            let gate_ok = !matches!(
21100                s.validate(),
21101                Err(AplicacaoError::PolicyBreakerWindowBelowTimeout { .. })
21102            );
21103
21104            assert_eq!(
21105                predicate, gate_ok,
21106                "predicate must agree with validate arm on pair \
21107                 (timeout={timeout:?}, window={window:?})"
21108            );
21109        }
21110    }
21111
21112    #[test]
21113    fn rejects_rate_limit_starves_circuit_breaker() {
21114        // The fail-before-pass-after pin on the cross-axis
21115        // `(:rate-limit, :circuit-breaker)` invariant. Each axis is
21116        // individually well-formed under its own per-axis bracket
21117        // (both above the zero floor, both below the cap, rate-limit
21118        // window canonical), but the pair is a structurally-inert
21119        // breaker: the token bucket admits `1 × 10s / 3600s` ≈ 0
21120        // calls per rolling breaker window, so no window can
21121        // accumulate five failures however catastrophic the upstream
21122        // failure rate.
21123        //
21124        // Envoy's `outlier_detection.consecutive_5xx` paired against
21125        // `local_rate_limit.token_bucket.max_tokens` /
21126        // `fill_interval` carries the identical relation; every
21127        // production playbook that pairs the two axes (Envoy, Istio,
21128        // AWS App Mesh, Kong) sizes the rate at or above the
21129        // breaker's minimum-request-volume threshold for exactly this
21130        // reason.
21131        //
21132        // Pin both the diagnostic arm and the payload values so a
21133        // future re-shape of the arm surfaces here as a deliberate
21134        // test edit. Clears `:timeout` so the sibling
21135        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] gate
21136        // does not fire first on the ordering-precedent it holds
21137        // over this arm.
21138        let mut s = three_member_spec();
21139        s.politicas.timeout = None;
21140        s.politicas.circuit_breaker = Some(CircuitBreaker {
21141            max_failures: 5,
21142            window: Duration::from_secs(10),
21143        });
21144        s.politicas.rate_limit = Some(RateLimit {
21145            rate: 1,
21146            window: Duration::from_secs(3600),
21147        });
21148        assert_eq!(
21149            s.validate().unwrap_err(),
21150            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
21151                rate: 1,
21152                rl_window: Duration::from_secs(3600),
21153                max_failures: 5,
21154                cb_window: Duration::from_secs(10),
21155            }
21156        );
21157    }
21158
21159    #[test]
21160    fn accepts_rate_limit_can_trip_circuit_breaker() {
21161        // Positive-control sweep across the production-playbook band
21162        // — every pair a real playbook recommends where the rate
21163        // clearly admits enough calls per breaker window to reach
21164        // `:max-failures` must validate. Envoy default 5 failures
21165        // in 10s with 100/s (1000 calls / window, 200× the threshold),
21166        // Istio 5 in 30s with 50/s (1500 calls, 300×), Hystrix 20 in
21167        // 10s with 1000/s (10000 calls, 500×), AWS App Mesh 5 in
21168        // 300s with 10/s (3000 calls, 600×). Clears `:timeout` so
21169        // the sibling cross-axis arm is vacuous on this sweep.
21170        for (rate, rl_window, max_failures, cb_window) in [
21171            (
21172                100u32,
21173                Duration::from_secs(1),
21174                5u32,
21175                Duration::from_secs(10),
21176            ),
21177            (50, Duration::from_secs(1), 5, Duration::from_secs(30)),
21178            (1000, Duration::from_secs(1), 20, Duration::from_secs(10)),
21179            (10, Duration::from_secs(1), 5, Duration::from_secs(300)),
21180            (5000, Duration::from_secs(60), 50, Duration::from_secs(60)),
21181        ] {
21182            let mut s = three_member_spec();
21183            s.politicas.timeout = None;
21184            s.politicas.circuit_breaker = Some(CircuitBreaker {
21185                max_failures,
21186                window: cb_window,
21187            });
21188            s.politicas.rate_limit = Some(RateLimit {
21189                rate,
21190                window: rl_window,
21191            });
21192            s.validate().unwrap_or_else(|e| {
21193                panic!(
21194                    "production-playbook pair rate={rate}/{rl_window:?} \
21195                     max_failures={max_failures}/{cb_window:?} must validate; got {e:?}"
21196                )
21197            });
21198        }
21199    }
21200
21201    #[test]
21202    fn accepts_rate_limit_exactly_at_trip_threshold_per_cb_window() {
21203        // Boundary pin: `rate × cb_window == max_failures × rl_window`
21204        // is the smallest bucket capacity that structurally admits
21205        // exactly `max_failures` calls per rolling breaker window
21206        // (the invariant is `≥`, not strict inequality). Catches a
21207        // future off-by-one tightening to strict inequality that
21208        // would drift the accept set away from the codified
21209        // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicate.
21210        // 5 calls/s over a 1s breaker window == 5 max_failures.
21211        let mut s = three_member_spec();
21212        s.politicas.timeout = None;
21213        s.politicas.circuit_breaker = Some(CircuitBreaker {
21214            max_failures: 5,
21215            window: Duration::from_secs(1),
21216        });
21217        s.politicas.rate_limit = Some(RateLimit {
21218            rate: 5,
21219            window: Duration::from_secs(1),
21220        });
21221        s.validate()
21222            .expect("rate × cb_window == max_failures × rl_window is the boundary accept case");
21223    }
21224
21225    #[test]
21226    fn rejects_rate_limit_one_call_short_per_cb_window() {
21227        // Off-by-one boundary pin: exactly one call short of the trip
21228        // threshold per breaker window is still structurally inert
21229        // (the invariant is `≥`, so `<` refuses even a one-call
21230        // shortfall). 4 calls/s over a 1s window == 4 admissible
21231        // failures, one shy of the 5-`max_failures` threshold.
21232        // Catches a future strict-inequality relaxation that would
21233        // silently drift the accept boundary.
21234        let mut s = three_member_spec();
21235        s.politicas.timeout = None;
21236        s.politicas.circuit_breaker = Some(CircuitBreaker {
21237            max_failures: 5,
21238            window: Duration::from_secs(1),
21239        });
21240        s.politicas.rate_limit = Some(RateLimit {
21241            rate: 4,
21242            window: Duration::from_secs(1),
21243        });
21244        assert_eq!(
21245            s.validate().unwrap_err(),
21246            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
21247                rate: 4,
21248                rl_window: Duration::from_secs(1),
21249                max_failures: 5,
21250                cb_window: Duration::from_secs(1),
21251            }
21252        );
21253    }
21254
21255    #[test]
21256    fn cross_axis_starve_gate_vacuous_when_rate_limit_absent() {
21257        // The predicate is vacuously `true` when `:rate-limit` is
21258        // None — a `:circuit-breaker` alone declares no relation to
21259        // a substrate-imposed call rate (the failure signal reaches
21260        // the breaker from the transport's own error surface, at
21261        // whatever rate upstream callers push traffic). Pin so a
21262        // future tightening that made the gate opinionated on
21263        // half-declared pairs surfaces here.
21264        let mut s = three_member_spec();
21265        s.politicas.timeout = None;
21266        s.politicas.circuit_breaker = Some(CircuitBreaker {
21267            max_failures: 1000,
21268            window: Duration::from_millis(1),
21269        });
21270        s.politicas.rate_limit = None;
21271        s.validate().expect(
21272            "cross-axis starve gate must be vacuous when :rate-limit is None, \
21273             however high :max-failures and however small :window are",
21274        );
21275    }
21276
21277    #[test]
21278    fn cross_axis_starve_gate_vacuous_when_circuit_breaker_absent() {
21279        // Peer of the sibling `:rate-limit`-absent case: a
21280        // `:rate-limit` without a `:circuit-breaker` declares a
21281        // per-edge token-bucket rate without any failure counter to
21282        // starve, so the pair is undeclared and the cross-axis gate
21283        // has nothing to check.
21284        //
21285        // Also clears the fixture's `:retries` (which is `Some(3)`) so
21286        // the sibling cross-axis
21287        // [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] arm
21288        // (which reasons across the paired `(:retries, :rate-limit)`
21289        // pair independent of `:circuit-breaker`) is vacuous on this
21290        // pin — this test names the *starve* arm's vacuity on the
21291        // `:circuit-breaker`-absent case, not the burst arm's.
21292        let mut s = three_member_spec();
21293        s.politicas.timeout = None;
21294        s.politicas.retries = None;
21295        s.politicas.circuit_breaker = None;
21296        s.politicas.rate_limit = Some(RateLimit {
21297            rate: 1,
21298            window: Duration::from_secs(3600),
21299        });
21300        s.validate().expect(
21301            "cross-axis starve gate must be vacuous when :circuit-breaker is None, \
21302             however low :rate is",
21303        );
21304    }
21305
21306    #[test]
21307    fn cross_axis_starve_gate_runs_after_per_axis_brackets() {
21308        // Ordering pin: a pair whose rate is *both* zero-floor-
21309        // violating and structurally below the trip threshold must
21310        // surface the per-axis zero-floor arm first — the zero-floor
21311        // diagnostic is more self-locating (its omit-axis remediation
21312        // is directly named), where the cross-axis arm would send the
21313        // author to reconcile four values one of which is not a
21314        // meaningful rate at all. Same ordering discipline every
21315        // per-axis bracket carries internally (zero-floor before
21316        // canonical-form before cap), and the sibling cross-axis
21317        // `PolicyBreakerZeroWindow`-before-`PolicyBreakerWindowBelowTimeout`
21318        // ordering pins on the `(:timeout, :window)` pair.
21319        let mut s = three_member_spec();
21320        s.politicas.timeout = None;
21321        s.politicas.circuit_breaker = Some(CircuitBreaker {
21322            max_failures: 5,
21323            window: Duration::from_secs(10),
21324        });
21325        s.politicas.rate_limit = Some(RateLimit {
21326            rate: 0,
21327            window: Duration::from_secs(1),
21328        });
21329        assert_eq!(
21330            s.validate().unwrap_err(),
21331            AplicacaoError::PolicyRateLimitZero,
21332            "per-axis rate zero-floor arm must fire before the cross-axis starve gate"
21333        );
21334    }
21335
21336    #[test]
21337    fn cross_axis_starve_gate_runs_after_sibling_window_below_timeout_gate() {
21338        // Cross-axis ordering pin: a `:politicas` whose axes trip
21339        // BOTH cross-axis arms — `:window < :timeout` (the sibling
21340        // `PolicyBreakerWindowBelowTimeout` invariant) AND
21341        // `:rate-limit` starves the breaker within `:window` (this
21342        // arm) — must surface the timeout-relation diagnostic first.
21343        // The timeout arm is the per-call-deadline invariant every
21344        // synchronous edge carries whether or not `:rate-limit` is
21345        // declared, so its diagnostic is more self-locating; the
21346        // starve arm needs the reader to reason across three axes,
21347        // where the timeout arm names only two.
21348        //
21349        // A `{ timeout: 30s, window: 10s, rate: 1/h, max_failures: 5 }`
21350        // pair trips both: the window is below the timeout, and the
21351        // rate (1 call/hour) admits far fewer than 5 calls per 10s
21352        // breaker window.
21353        let mut s = three_member_spec();
21354        s.politicas.timeout = Some(Duration::from_secs(30));
21355        s.politicas.circuit_breaker = Some(CircuitBreaker {
21356            max_failures: 5,
21357            window: Duration::from_secs(10),
21358        });
21359        s.politicas.rate_limit = Some(RateLimit {
21360            rate: 1,
21361            window: Duration::from_secs(3600),
21362        });
21363        assert_eq!(
21364            s.validate().unwrap_err(),
21365            AplicacaoError::PolicyBreakerWindowBelowTimeout {
21366                window: Duration::from_secs(10),
21367                timeout: Duration::from_secs(30),
21368            },
21369            "sibling :window<:timeout cross-axis arm must fire before the \
21370             starve arm when both apply"
21371        );
21372    }
21373
21374    #[test]
21375    fn breaker_can_trip_under_rate_limit_predicate_matches_gate_semantic() {
21376        // Equivalence pin: the substrate-canonical
21377        // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicate
21378        // and the [`AplicacaoSpec::validate_politicas`] cross-axis
21379        // arm must discriminate the same set on every pair covered
21380        // by their shared invariant. A future refactor of either
21381        // side that breaks the equivalence trips here rather than as
21382        // a divergence between the predicate's Boolean answer and
21383        // the validate gate's Ok/Err arm — the same
21384        // predicate-vs-gate coherence discipline the sibling
21385        // [`MeshPolicy::breaker_window_observes_timeout`] predicate
21386        // carries against `AplicacaoSpec::validate_politicas`. The
21387        // sweep covers both arms of the invariant (strictly below,
21388        // exactly at, strictly above) and both vacuous arms (None
21389        // `:rate-limit`, None `:circuit-breaker`), so the
21390        // equivalence holds exhaustively over the axis-covered
21391        // accept and reject sets. Clears `:timeout` throughout so
21392        // the sibling `:window<:timeout` gate is vacuous on every
21393        // input.
21394        let rl = |rate: u32, secs: u64| {
21395            Some(RateLimit {
21396                rate,
21397                window: Duration::from_secs(secs),
21398            })
21399        };
21400        let cb = |max_failures: u32, secs: u64| {
21401            Some(CircuitBreaker {
21402                max_failures,
21403                window: Duration::from_secs(secs),
21404            })
21405        };
21406        let cases: &[(Option<RateLimit>, Option<CircuitBreaker>)] = &[
21407            // starving pairs (predicate = false, gate = Err)
21408            (rl(1, 3600), cb(5, 10)),
21409            (rl(4, 1), cb(5, 1)),
21410            // boundary + coherent pairs (predicate = true, gate = Ok)
21411            (rl(5, 1), cb(5, 1)),
21412            (rl(100, 1), cb(5, 10)),
21413            // vacuous arms
21414            (None, cb(5, 10)),
21415            (rl(1, 3600), None),
21416            (None, None),
21417        ];
21418        for (rate_limit, circuit_breaker) in cases.iter().copied() {
21419            let politicas = MeshPolicy {
21420                circuit_breaker,
21421                rate_limit,
21422                ..Default::default()
21423            };
21424            let predicate = politicas.breaker_can_trip_under_rate_limit();
21425
21426            let mut s = three_member_spec();
21427            s.politicas = politicas.clone();
21428            s.politicas.timeout = None;
21429            let gate_ok = !matches!(
21430                s.validate(),
21431                Err(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit { .. })
21432            );
21433
21434            assert_eq!(
21435                predicate, gate_ok,
21436                "predicate must agree with validate arm on pair \
21437                 (rate_limit={rate_limit:?}, circuit_breaker={circuit_breaker:?})"
21438            );
21439        }
21440    }
21441
21442    #[test]
21443    fn rejects_retries_saturate_breaker_trip_threshold() {
21444        // The fail-before-pass-after pin on the cross-axis
21445        // `(:retries, :circuit-breaker :max-failures)` invariant. Each
21446        // axis is individually well-formed under its own per-axis
21447        // bracket (both above the zero floor, both below the cap), but
21448        // the pair is a structurally-truncated retry policy: one
21449        // client's `retries + 1 = 4` failing attempts hit the trip
21450        // threshold on the third attempt, the breaker opens, and the
21451        // fourth attempt (the last declared retry) is blocked by the
21452        // open breaker — the substrate declared four attempts and
21453        // structurally allows three.
21454        //
21455        // Envoy's `retry_policy.num_retries` paired against
21456        // `outlier_detection.consecutive_5xx` carries the identical
21457        // relation; every production playbook that pairs the two axes
21458        // (Envoy, Istio, resilience4j, Hystrix) sizes the breaker's
21459        // trip threshold strictly above any single client's retry
21460        // budget so the breaker distinguishes one persistently-failing
21461        // client from sustained multi-client failure.
21462        //
21463        // Pin both the diagnostic arm and the payload values so a
21464        // future re-shape of the arm surfaces here as a deliberate
21465        // test edit. Clears `:timeout` and `:rate-limit` so the
21466        // sibling cross-axis
21467        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] /
21468        // [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`]
21469        // arms do not fire first on the ordering-precedent they hold
21470        // over this arm.
21471        let mut s = three_member_spec();
21472        s.politicas.timeout = None;
21473        s.politicas.retries = Some(3);
21474        s.politicas.circuit_breaker = Some(CircuitBreaker {
21475            max_failures: 3,
21476            window: Duration::from_secs(1),
21477        });
21478        s.politicas.rate_limit = None;
21479        assert_eq!(
21480            s.validate().unwrap_err(),
21481            AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
21482                retries: 3,
21483                max_failures: 3,
21484            }
21485        );
21486    }
21487
21488    #[test]
21489    fn accepts_retries_below_breaker_trip_threshold() {
21490        // Positive-control sweep across the production-playbook band
21491        // — every pair a real playbook recommends where the breaker's
21492        // trip threshold is strictly above the client's retry budget
21493        // must validate. Envoy default `num_retries: 3` with
21494        // `consecutive_5xx: 5` (breaker admits one client's 4 attempts,
21495        // opens on multi-client failures beyond that); Istio
21496        // `attempts: 3` with `consecutive5xxErrors: 5`; Hystrix
21497        // `execution.isolation.thread.timeoutInMilliseconds` + 3
21498        // retries with `requestVolumeThreshold: 20`; AWS App Mesh
21499        // `maxRetries: 5` with a `maxEjectionPercent`-derived threshold
21500        // of 10; resilience4j 2 retries with `slidingWindowSize: 10`.
21501        // Clears `:timeout` and `:rate-limit` so the sibling cross-axis
21502        // arms are vacuous on this sweep.
21503        for (retries, max_failures) in [(1u32, 5u32), (3, 5), (3, 20), (5, 10), (2, 10), (10, 1000)]
21504        {
21505            let mut s = three_member_spec();
21506            s.politicas.timeout = None;
21507            s.politicas.retries = Some(retries);
21508            s.politicas.circuit_breaker = Some(CircuitBreaker {
21509                max_failures,
21510                window: Duration::from_secs(60),
21511            });
21512            s.politicas.rate_limit = None;
21513            s.validate().unwrap_or_else(|e| {
21514                panic!(
21515                    "production-playbook pair retries={retries} \
21516                     max_failures={max_failures} must validate; got {e:?}"
21517                )
21518            });
21519        }
21520    }
21521
21522    #[test]
21523    fn accepts_retries_exactly_at_boundary_below_trip_threshold() {
21524        // Boundary pin: `max_failures == retries + 1` is the smallest
21525        // trip threshold that admits one client's exhausted retries
21526        // through completion (the R+1th failure — the last declared
21527        // retry — trips the breaker exactly as it completes, so
21528        // retries fully executed). The invariant is `>`, not `>=`,
21529        // stated in the coherent direction `max_failures > retries`.
21530        // Catches a future off-by-one tightening to
21531        // `max_failures > retries + 1` that would drift the accept set
21532        // away from the codified
21533        // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]
21534        // predicate.
21535        let mut s = three_member_spec();
21536        s.politicas.timeout = None;
21537        s.politicas.retries = Some(3);
21538        s.politicas.circuit_breaker = Some(CircuitBreaker {
21539            max_failures: 4,
21540            window: Duration::from_secs(60),
21541        });
21542        s.politicas.rate_limit = None;
21543        s.validate()
21544            .expect("max_failures == retries + 1 is the boundary accept case");
21545    }
21546
21547    #[test]
21548    fn rejects_retries_equal_to_breaker_trip_threshold() {
21549        // Off-by-one boundary pin: exactly at the trip threshold is
21550        // still structurally truncating (the invariant is `>`, so `<=`
21551        // refuses even the tight boundary). `retries = 3` with
21552        // `max_failures = 3` means the breaker trips on the third
21553        // failure — the last declared retry attempt is blocked.
21554        // Catches a future relaxation to `>=` that would silently
21555        // drift the accept boundary.
21556        let mut s = three_member_spec();
21557        s.politicas.timeout = None;
21558        s.politicas.retries = Some(3);
21559        s.politicas.circuit_breaker = Some(CircuitBreaker {
21560            max_failures: 3,
21561            window: Duration::from_secs(60),
21562        });
21563        s.politicas.rate_limit = None;
21564        assert_eq!(
21565            s.validate().unwrap_err(),
21566            AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
21567                retries: 3,
21568                max_failures: 3,
21569            }
21570        );
21571    }
21572
21573    #[test]
21574    fn cross_axis_retries_gate_vacuous_when_retries_absent() {
21575        // The predicate is vacuously `true` when `:retries` is None —
21576        // a `:circuit-breaker` alone declares a failure counter whose
21577        // per-client attempt count is unconstrained by the substrate,
21578        // so no per-client saturation bound on failures-per-client-call
21579        // is knowable at author time. The substrate takes no position
21580        // on whether an omitted `:retries` axis means zero retries or
21581        // "the client picks its own retry policy" — either way, the
21582        // pair is undeclared and the cross-axis gate has nothing to
21583        // check. Pin so a future tightening that made the gate
21584        // opinionated on half-declared pairs surfaces here.
21585        let mut s = three_member_spec();
21586        s.politicas.timeout = None;
21587        s.politicas.retries = None;
21588        s.politicas.circuit_breaker = Some(CircuitBreaker {
21589            max_failures: 1,
21590            window: Duration::from_secs(60),
21591        });
21592        s.politicas.rate_limit = None;
21593        s.validate().expect(
21594            "cross-axis retries gate must be vacuous when :retries is None, \
21595             however low :max-failures is",
21596        );
21597    }
21598
21599    #[test]
21600    fn cross_axis_retries_gate_vacuous_when_circuit_breaker_absent() {
21601        // Peer of the sibling `:retries`-absent case: a `:retries`
21602        // without a `:circuit-breaker` declares a client-retry policy
21603        // with no failure counter to trip, so the pair is undeclared
21604        // and the cross-axis gate has nothing to check.
21605        let mut s = three_member_spec();
21606        s.politicas.timeout = None;
21607        s.politicas.retries = Some(POLICY_RETRIES_MAX);
21608        s.politicas.circuit_breaker = None;
21609        s.politicas.rate_limit = None;
21610        s.validate().expect(
21611            "cross-axis retries gate must be vacuous when :circuit-breaker is None, \
21612             however high :retries is",
21613        );
21614    }
21615
21616    #[test]
21617    fn cross_axis_retries_gate_runs_after_per_axis_brackets() {
21618        // Ordering pin: a pair whose retries is *both* zero-floor-
21619        // violating and structurally at-or-below the trip threshold
21620        // must surface the per-axis zero-floor arm first — the
21621        // zero-floor diagnostic is more self-locating (its omit-axis
21622        // remediation is directly named), where the cross-axis arm
21623        // would send the author to reconcile two values one of which
21624        // is not a meaningful retry count at all. Same ordering
21625        // discipline every per-axis bracket carries internally
21626        // (zero-floor before canonical-form before cap), and the
21627        // sibling cross-axis
21628        // `PolicyRateLimitZero`-before-`PolicyBreakerCannotTripUnderRateLimit`
21629        // ordering pins on the `(:rate-limit, :circuit-breaker)` pair.
21630        let mut s = three_member_spec();
21631        s.politicas.timeout = None;
21632        s.politicas.retries = Some(0);
21633        s.politicas.circuit_breaker = Some(CircuitBreaker {
21634            max_failures: 3,
21635            window: Duration::from_secs(60),
21636        });
21637        s.politicas.rate_limit = None;
21638        assert_eq!(
21639            s.validate().unwrap_err(),
21640            AplicacaoError::PolicyRetriesZero,
21641            "per-axis retries zero-floor arm must fire before the cross-axis retries gate"
21642        );
21643    }
21644
21645    #[test]
21646    fn cross_axis_retries_gate_runs_after_sibling_starve_gate() {
21647        // Cross-axis ordering pin: a `:politicas` whose axes trip
21648        // BOTH cross-axis arms — `:rate-limit` starves the breaker
21649        // within `:window` (the sibling
21650        // `PolicyBreakerCannotTripUnderRateLimit` invariant) AND
21651        // `:retries + 1` saturates `:max-failures` (this arm) — must
21652        // surface the rate-limit-starve diagnostic first. The
21653        // rate-limit-starve arm reasons across the token-bucket
21654        // admission axis every rate-limited edge carries whether or
21655        // not `:retries` is declared, so its diagnostic is more
21656        // self-locating; the retries-saturate arm reasons across a
21657        // per-client retry-policy budget the starve arm does not
21658        // touch.
21659        //
21660        // A `{ retries: 5, rate: 1/h, max_failures: 5, cb_window: 10s }`
21661        // pair trips both: the rate structurally cannot deliver 5
21662        // failures per 10s breaker window, and simultaneously
21663        // one client's `retries + 1 = 6` attempts alone would
21664        // saturate the 5-`max_failures` threshold.
21665        let mut s = three_member_spec();
21666        s.politicas.timeout = None;
21667        s.politicas.retries = Some(5);
21668        s.politicas.circuit_breaker = Some(CircuitBreaker {
21669            max_failures: 5,
21670            window: Duration::from_secs(10),
21671        });
21672        s.politicas.rate_limit = Some(RateLimit {
21673            rate: 1,
21674            window: Duration::from_secs(3600),
21675        });
21676        assert_eq!(
21677            s.validate().unwrap_err(),
21678            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
21679                rate: 1,
21680                rl_window: Duration::from_secs(3600),
21681                max_failures: 5,
21682                cb_window: Duration::from_secs(10),
21683            },
21684            "sibling :rate-limit-starve cross-axis arm must fire before the \
21685             retries-saturate arm when both apply"
21686        );
21687    }
21688
21689    #[test]
21690    fn retries_fit_under_breaker_trip_threshold_predicate_matches_gate_semantic() {
21691        // Equivalence pin: the substrate-canonical
21692        // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]
21693        // predicate and the [`AplicacaoSpec::validate_politicas`]
21694        // cross-axis arm must discriminate the same set on every pair
21695        // covered by their shared invariant. A future refactor of
21696        // either side that breaks the equivalence trips here rather
21697        // than as a divergence between the predicate's Boolean answer
21698        // and the validate gate's Ok/Err arm — the same
21699        // predicate-vs-gate coherence discipline the sibling
21700        // [`MeshPolicy::breaker_window_observes_timeout`] and
21701        // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
21702        // carry against `AplicacaoSpec::validate_politicas`. The
21703        // sweep covers both arms of the invariant (strictly below,
21704        // exactly at the boundary, strictly above) and both vacuous
21705        // arms (None `:retries`, None `:circuit-breaker`), so the
21706        // equivalence holds exhaustively over the axis-covered accept
21707        // and reject sets. Clears `:timeout` and `:rate-limit`
21708        // throughout so the sibling cross-axis arms are vacuous on
21709        // every input.
21710        let cb = |max_failures: u32| {
21711            Some(CircuitBreaker {
21712                max_failures,
21713                window: Duration::from_secs(60),
21714            })
21715        };
21716        let cases: &[(Option<u32>, Option<CircuitBreaker>)] = &[
21717            // saturating pairs (predicate = false, gate = Err)
21718            (Some(3), cb(3)),
21719            (Some(3), cb(1)),
21720            (Some(10), cb(5)),
21721            // boundary + coherent pairs (predicate = true, gate = Ok)
21722            (Some(3), cb(4)),
21723            (Some(1), cb(5)),
21724            (Some(3), cb(20)),
21725            // vacuous arms
21726            (None, cb(1)),
21727            (Some(10), None),
21728            (None, None),
21729        ];
21730        for (retries, circuit_breaker) in cases.iter().copied() {
21731            let politicas = MeshPolicy {
21732                retries,
21733                circuit_breaker,
21734                ..Default::default()
21735            };
21736            let predicate = politicas.retries_fit_under_breaker_trip_threshold();
21737
21738            let mut s = three_member_spec();
21739            s.politicas = politicas.clone();
21740            let gate_ok = !matches!(
21741                s.validate(),
21742                Err(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted { .. })
21743            );
21744
21745            assert_eq!(
21746                predicate, gate_ok,
21747                "predicate must agree with validate arm on pair \
21748                 (retries={retries:?}, circuit_breaker={circuit_breaker:?})"
21749            );
21750        }
21751    }
21752
21753    #[test]
21754    fn rejects_rate_limit_cannot_admit_retry_burst() {
21755        // The fail-before-pass-after pin on the cross-axis
21756        // `(:retries, :rate-limit)` invariant. Each axis is
21757        // individually well-formed under its own per-axis bracket (both
21758        // above the zero floor, both below the cap), but the pair is a
21759        // structurally-truncated retry policy: one client's
21760        // `retries + 1 = 6` failing attempts consume 6 tokens from a
21761        // bucket that admits at most 3 per refill window, so the fourth
21762        // attempt onward is 429ed by the local rate limiter and the
21763        // declared retry policy is silently truncated by the same rate
21764        // limiter it feeds through — the substrate declared six
21765        // attempts and structurally allows three.
21766        //
21767        // Envoy's `local_rate_limit.token_bucket.max_tokens` paired
21768        // against `retry_policy.num_retries` carries the identical
21769        // relation; every production playbook that pairs the two axes
21770        // (Envoy, Istio, resilience4j, AWS App Mesh) sizes the bucket
21771        // capacity strictly above any single client's retry budget so
21772        // the limiter distinguishes one client's declared retries from
21773        // sustained multi-client load.
21774        //
21775        // Pin both the diagnostic arm and the payload values so a
21776        // future re-shape of the arm surfaces here as a deliberate
21777        // test edit. Clears `:timeout` and `:circuit-breaker` so the
21778        // sibling cross-axis
21779        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] /
21780        // [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`] /
21781        // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
21782        // arms do not fire first on the ordering-precedent they hold
21783        // over this arm.
21784        let mut s = three_member_spec();
21785        s.politicas.timeout = None;
21786        s.politicas.retries = Some(5);
21787        s.politicas.circuit_breaker = None;
21788        s.politicas.rate_limit = Some(RateLimit {
21789            rate: 3,
21790            window: Duration::from_secs(1),
21791        });
21792        assert_eq!(
21793            s.validate().unwrap_err(),
21794            AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
21795                retries: 5,
21796                rate: 3,
21797            }
21798        );
21799    }
21800
21801    #[test]
21802    fn accepts_rate_limit_admits_retry_burst() {
21803        // Positive-control sweep across the production-playbook band
21804        // — every pair a real playbook recommends where the bucket
21805        // capacity is strictly above the client's retry budget must
21806        // validate. Envoy default `num_retries: 3` with 100/s (100
21807        // tokens per window admits 4 attempts per client with 96 to
21808        // spare); Istio `attempts: 3` with 50/s (50 admits 4);
21809        // resilience4j 2 retries with 10/s (10 admits 3); AWS App
21810        // Mesh `maxRetries: 5` with 1000/s (1000 admits 6); Cloudflare
21811        // Enterprise 3 retries with 1_000_000/h (1M admits 4). Clears
21812        // `:timeout` and `:circuit-breaker` so the sibling cross-axis
21813        // arms are vacuous on this sweep.
21814        for (retries, rate, secs) in [
21815            (3u32, 100u32, 1u64),
21816            (3, 50, 1),
21817            (2, 10, 1),
21818            (5, 1000, 1),
21819            (3, 1_000_000, 3600),
21820            (10, POLICY_RATE_LIMIT_MAX, 1),
21821        ] {
21822            let mut s = three_member_spec();
21823            s.politicas.timeout = None;
21824            s.politicas.retries = Some(retries);
21825            s.politicas.circuit_breaker = None;
21826            s.politicas.rate_limit = Some(RateLimit {
21827                rate,
21828                window: Duration::from_secs(secs),
21829            });
21830            s.validate().unwrap_or_else(|e| {
21831                panic!(
21832                    "production-playbook pair retries={retries} rate={rate}/{secs}s \
21833                     must validate; got {e:?}"
21834                )
21835            });
21836        }
21837    }
21838
21839    #[test]
21840    fn accepts_rate_exactly_at_boundary_admits_retry_burst() {
21841        // Boundary pin: `rate == retries + 1` is the smallest bucket
21842        // capacity that structurally admits one client's exhausted
21843        // retries through completion (each attempt draws exactly one
21844        // token; `retries + 1` tokens available admits `retries + 1`
21845        // attempts, retries fully executed). The invariant is `>=`,
21846        // stated in the coherent direction `rate >= retries + 1`.
21847        // Catches a future off-by-one tightening to `rate > retries + 1`
21848        // that would drift the accept set away from the codified
21849        // [`MeshPolicy::rate_limit_admits_retry_burst`] predicate.
21850        let mut s = three_member_spec();
21851        s.politicas.timeout = None;
21852        s.politicas.retries = Some(3);
21853        s.politicas.circuit_breaker = None;
21854        s.politicas.rate_limit = Some(RateLimit {
21855            rate: 4,
21856            window: Duration::from_secs(1),
21857        });
21858        s.validate()
21859            .expect("rate == retries + 1 is the boundary accept case");
21860    }
21861
21862    #[test]
21863    fn rejects_rate_one_below_retry_burst() {
21864        // Off-by-one boundary pin: exactly one token short of the
21865        // retry burst is still structurally truncating (the invariant
21866        // is `>=`, so `<` refuses even a one-token shortfall).
21867        // `retries = 3` with `rate = 3` means one client's four
21868        // attempts consume four tokens from a three-token bucket —
21869        // the fourth attempt is 429ed. Catches a future relaxation to
21870        // `>` on the wrong side (`rate > retries`, accepting equal)
21871        // that would silently drift the accept boundary and admit a
21872        // structurally-truncated retry policy at the emit boundary.
21873        let mut s = three_member_spec();
21874        s.politicas.timeout = None;
21875        s.politicas.retries = Some(3);
21876        s.politicas.circuit_breaker = None;
21877        s.politicas.rate_limit = Some(RateLimit {
21878            rate: 3,
21879            window: Duration::from_secs(1),
21880        });
21881        assert_eq!(
21882            s.validate().unwrap_err(),
21883            AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
21884                retries: 3,
21885                rate: 3,
21886            }
21887        );
21888    }
21889
21890    #[test]
21891    fn cross_axis_burst_gate_vacuous_when_retries_absent() {
21892        // The predicate is vacuously `true` when `:retries` is None —
21893        // a `:rate-limit` alone declares a token-bucket rate whose
21894        // per-client attempt count is unconstrained by the substrate,
21895        // so no per-client saturation bound on tokens-per-client-call
21896        // is knowable at author time. The substrate takes no position
21897        // on whether an omitted `:retries` axis means zero retries or
21898        // "the client picks its own retry policy" — either way, the
21899        // pair is undeclared and the cross-axis gate has nothing to
21900        // check. Pin so a future tightening that made the gate
21901        // opinionated on half-declared pairs surfaces here.
21902        let mut s = three_member_spec();
21903        s.politicas.timeout = None;
21904        s.politicas.retries = None;
21905        s.politicas.circuit_breaker = None;
21906        s.politicas.rate_limit = Some(RateLimit {
21907            rate: 1,
21908            window: Duration::from_secs(1),
21909        });
21910        s.validate().expect(
21911            "cross-axis burst gate must be vacuous when :retries is None, \
21912             however low :rate is",
21913        );
21914    }
21915
21916    #[test]
21917    fn cross_axis_burst_gate_vacuous_when_rate_limit_absent() {
21918        // Peer of the sibling `:retries`-absent case: a `:retries`
21919        // without a `:rate-limit` declares a client-retry policy with
21920        // no rate limiter to saturate, so the pair is undeclared and
21921        // the cross-axis gate has nothing to check. Uses
21922        // [`POLICY_RETRIES_MAX`] to pin the vacuity across the widest
21923        // authored retry budget the per-axis cap admits — a `:retries
21924        // POLICY_RETRIES_MAX` alone must remain a clean pass whether
21925        // or not `:rate-limit` is declared.
21926        let mut s = three_member_spec();
21927        s.politicas.timeout = None;
21928        s.politicas.retries = Some(POLICY_RETRIES_MAX);
21929        s.politicas.circuit_breaker = None;
21930        s.politicas.rate_limit = None;
21931        s.validate().expect(
21932            "cross-axis burst gate must be vacuous when :rate-limit is None, \
21933             however high :retries is",
21934        );
21935    }
21936
21937    #[test]
21938    fn cross_axis_burst_gate_runs_after_per_axis_brackets() {
21939        // Ordering pin: a pair whose retries is *both* zero-floor-
21940        // violating and structurally below the retry-burst threshold
21941        // must surface the per-axis zero-floor arm first — the
21942        // zero-floor diagnostic is more self-locating (its omit-axis
21943        // remediation is directly named), where the cross-axis arm
21944        // would send the author to reconcile two values one of which
21945        // is not a meaningful retry count at all. Same ordering
21946        // discipline every per-axis bracket carries internally
21947        // (zero-floor before canonical-form before cap), and the
21948        // sibling cross-axis
21949        // `PolicyRetriesZero`-before-`PolicyBreakerTripsBeforeRetriesExhausted`
21950        // ordering pin on the `(:retries, :max-failures)` pair.
21951        let mut s = three_member_spec();
21952        s.politicas.timeout = None;
21953        s.politicas.retries = Some(0);
21954        s.politicas.circuit_breaker = None;
21955        s.politicas.rate_limit = Some(RateLimit {
21956            rate: 1,
21957            window: Duration::from_secs(1),
21958        });
21959        assert_eq!(
21960            s.validate().unwrap_err(),
21961            AplicacaoError::PolicyRetriesZero,
21962            "per-axis retries zero-floor arm must fire before the cross-axis burst gate"
21963        );
21964    }
21965
21966    #[test]
21967    fn cross_axis_burst_gate_runs_after_sibling_starve_gate() {
21968        // Cross-axis ordering pin: a `:politicas` whose axes trip
21969        // BOTH cross-axis arms — `:rate-limit` starves the breaker
21970        // within `:window` (the sibling
21971        // `PolicyBreakerCannotTripUnderRateLimit` invariant) AND
21972        // `:retries + 1` exceeds the bucket capacity (this arm) —
21973        // must surface the rate-limit-starve diagnostic first. The
21974        // starve arm is the token-bucket admission invariant every
21975        // rate-limited edge carries against the breaker whether or
21976        // not `:retries` is declared, so its diagnostic is more
21977        // self-locating; the burst arm reasons across a per-client
21978        // retry-policy budget the starve arm does not touch. Same
21979        // "more foundational cross-axis first" ordering discipline the
21980        // sibling
21981        // `PolicyBreakerCannotTripUnderRateLimit`-before-`PolicyBreakerTripsBeforeRetriesExhausted`
21982        // pin on the peer pair carries.
21983        //
21984        // A `{ retries: 5, rate: 1/h, max_failures: 5, cb_window: 10s }`
21985        // pair trips both: the rate structurally cannot deliver 5
21986        // failures per 10s breaker window (starve arm), and
21987        // simultaneously one client's `retries + 1 = 6` attempts alone
21988        // would exhaust the 1-token bucket (burst arm).
21989        let mut s = three_member_spec();
21990        s.politicas.timeout = None;
21991        s.politicas.retries = Some(5);
21992        s.politicas.circuit_breaker = Some(CircuitBreaker {
21993            max_failures: 5,
21994            window: Duration::from_secs(10),
21995        });
21996        s.politicas.rate_limit = Some(RateLimit {
21997            rate: 1,
21998            window: Duration::from_secs(3600),
21999        });
22000        assert_eq!(
22001            s.validate().unwrap_err(),
22002            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
22003                rate: 1,
22004                rl_window: Duration::from_secs(3600),
22005                max_failures: 5,
22006                cb_window: Duration::from_secs(10),
22007            },
22008            "sibling :rate-limit-starve cross-axis arm must fire before the \
22009             burst arm when both apply"
22010        );
22011    }
22012
22013    #[test]
22014    fn cross_axis_burst_gate_runs_after_sibling_retries_saturate_gate() {
22015        // Cross-axis ordering pin: a `:politicas` whose axes trip
22016        // BOTH the retries-saturate arm and this burst arm — one
22017        // client's `retries + 1` failures saturate the breaker's trip
22018        // threshold (the sibling
22019        // `PolicyBreakerTripsBeforeRetriesExhausted` invariant) AND
22020        // `retries + 1` exceeds the bucket capacity (this arm) —
22021        // must surface the retries-saturate diagnostic first. The
22022        // saturate arm is the per-client-vs-breaker relation every
22023        // retry-with-breaker pair carries whether or not `:rate-limit`
22024        // is declared, so its diagnostic is more self-locating; the
22025        // burst arm reasons across the rate-limit token-bucket
22026        // admission axis the saturate arm does not touch. Same
22027        // "more foundational cross-axis first" ordering discipline
22028        // carries here.
22029        //
22030        // A `{ retries: 5, max_failures: 3, cb_window: 60s,
22031        // rate: 3/s }` pair trips both: the breaker's `max_failures
22032        // = 3` is `<= retries = 5` (saturate arm), and simultaneously
22033        // one client's `retries + 1 = 6` attempts alone would exhaust
22034        // the 3-token bucket (burst arm). Clears `:timeout` so the
22035        // sibling `:window<:timeout` gate is vacuous, and the
22036        // `(rate=3/s, max_failures=3, cb_window=60s)` triple keeps
22037        // the starve arm coherent (`3 × 60s >= 3 × 1s`) so it is not
22038        // the arm that fires first.
22039        let mut s = three_member_spec();
22040        s.politicas.timeout = None;
22041        s.politicas.retries = Some(5);
22042        s.politicas.circuit_breaker = Some(CircuitBreaker {
22043            max_failures: 3,
22044            window: Duration::from_secs(60),
22045        });
22046        s.politicas.rate_limit = Some(RateLimit {
22047            rate: 3,
22048            window: Duration::from_secs(1),
22049        });
22050        assert_eq!(
22051            s.validate().unwrap_err(),
22052            AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
22053                retries: 5,
22054                max_failures: 3,
22055            },
22056            "sibling :retries-saturate cross-axis arm must fire before the \
22057             burst arm when both apply"
22058        );
22059    }
22060
22061    #[test]
22062    fn rate_limit_admits_retry_burst_predicate_matches_gate_semantic() {
22063        // Equivalence pin: the substrate-canonical
22064        // [`MeshPolicy::rate_limit_admits_retry_burst`] predicate and
22065        // the [`AplicacaoSpec::validate_politicas`] cross-axis arm
22066        // must discriminate the same set on every pair covered by
22067        // their shared invariant. A future refactor of either side
22068        // that breaks the equivalence trips here rather than as a
22069        // divergence between the predicate's Boolean answer and the
22070        // validate gate's Ok/Err arm — the same predicate-vs-gate
22071        // coherence discipline the three sibling cross-axis
22072        // predicates ([`MeshPolicy::breaker_window_observes_timeout`],
22073        // [`MeshPolicy::breaker_can_trip_under_rate_limit`],
22074        // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`])
22075        // carry against `AplicacaoSpec::validate_politicas`. The sweep
22076        // covers both arms of the invariant (strictly below, exactly
22077        // at the boundary, strictly above) and both vacuous arms
22078        // (None `:retries`, None `:rate-limit`), so the equivalence
22079        // holds exhaustively over the axis-covered accept and reject
22080        // sets. Clears `:timeout` and `:circuit-breaker` throughout
22081        // so the three sibling cross-axis arms are vacuous on every
22082        // input.
22083        let rl = |rate: u32, secs: u64| {
22084            Some(RateLimit {
22085                rate,
22086                window: Duration::from_secs(secs),
22087            })
22088        };
22089        let cases: &[(Option<u32>, Option<RateLimit>)] = &[
22090            // burst-exceeding pairs (predicate = false, gate = Err)
22091            (Some(3), rl(3, 1)),
22092            (Some(5), rl(1, 1)),
22093            (Some(10), rl(5, 1)),
22094            // boundary + coherent pairs (predicate = true, gate = Ok)
22095            (Some(3), rl(4, 1)),
22096            (Some(1), rl(5, 1)),
22097            (Some(3), rl(1_000_000, 3600)),
22098            // vacuous arms
22099            (None, rl(1, 1)),
22100            (Some(10), None),
22101            (None, None),
22102        ];
22103        for (retries, rate_limit) in cases.iter().copied() {
22104            let politicas = MeshPolicy {
22105                retries,
22106                rate_limit,
22107                ..Default::default()
22108            };
22109            let predicate = politicas.rate_limit_admits_retry_burst();
22110
22111            let mut s = three_member_spec();
22112            s.politicas = politicas.clone();
22113            let gate_ok = !matches!(
22114                s.validate(),
22115                Err(AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst { .. })
22116            );
22117
22118            assert_eq!(
22119                predicate, gate_ok,
22120                "predicate must agree with validate arm on pair \
22121                 (retries={retries:?}, rate_limit={rate_limit:?})"
22122            );
22123        }
22124    }
22125
22126    /// Sweep body shared by every `first_cross_axis_violation` ≡ gate
22127    /// equivalence pin — assert that on each `(label, politicas,
22128    /// expected)` case the substrate-canonical fold and the validate
22129    /// cascade agree byte-for-byte. Extracted so each pin's own body
22130    /// stays under `clippy::too_many_lines`.
22131    fn assert_first_cross_axis_violation_agrees_with_gate(
22132        cases: &[(&str, MeshPolicy, Option<AplicacaoError>)],
22133    ) {
22134        for (label, politicas, expected) in cases {
22135            let fold = politicas.first_cross_axis_violation();
22136            assert_eq!(
22137                fold.as_ref(),
22138                expected.as_ref(),
22139                "fold must return {expected:?} on `{label}`; got {fold:?}"
22140            );
22141
22142            let mut s = three_member_spec();
22143            s.politicas = politicas.clone();
22144            let gate = s.validate();
22145            match expected {
22146                None => {
22147                    // No cross-axis violation: validate must pass (the
22148                    // per-axis brackets pass by construction on every
22149                    // fixture above; every fixture's non-`:politicas`
22150                    // slots come from `three_member_spec`).
22151                    gate.as_ref()
22152                        .unwrap_or_else(|e| panic!("`{label}` must validate cleanly; got {e:?}"));
22153                }
22154                Some(want) => {
22155                    let got =
22156                        gate.expect_err(&format!("`{label}` must surface a cross-axis violation"));
22157                    assert_eq!(
22158                        &got, want,
22159                        "validate cross-axis cascade must return {want:?} on `{label}`; got {got:?}"
22160                    );
22161                }
22162            }
22163        }
22164    }
22165
22166    #[test]
22167    fn first_cross_axis_violation_matches_gate_on_single_arm_and_vacuous_shapes() {
22168        // Equivalence pin on the compound cross-axis fold: the
22169        // substrate-canonical [`MeshPolicy::first_cross_axis_violation`]
22170        // and the [`AplicacaoSpec::validate_politicas`] cross-axis
22171        // cascade must return identical `AplicacaoError` variants on
22172        // every axis-covered input — the "compound-fold ≡ gate"
22173        // contract that generalizes the four sibling per-arm pins
22174        // onto the compound primitive that folds all four. A future
22175        // refactor of either side that breaks the equivalence trips
22176        // here rather than as a divergence between what the substrate
22177        // primitive answers and what `feira build` accepts.
22178        //
22179        // Half-A of the sweep: every single-arm violation (one arm
22180        // fires with the three sibling arms vacuous), the vacuous
22181        // shape (empty policy — no arm fires), and the fully-coherent
22182        // shape (every axis declared inside the coherence surface —
22183        // no arm fires). Half-B (pairwise-ordering coverage — the
22184        // "which arm wins when two apply" contract) lives in the
22185        // sibling `first_cross_axis_violation_matches_gate_on_pairwise_orderings`
22186        // pin; splitting keeps each pin's body under
22187        // `clippy::too_many_lines`.
22188        let cb = |max_failures: u32, secs: u64| CircuitBreaker {
22189            max_failures,
22190            window: Duration::from_secs(secs),
22191        };
22192        let rl = |rate: u32, secs: u64| RateLimit {
22193            rate,
22194            window: Duration::from_secs(secs),
22195        };
22196        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
22197            (
22198                "window-below-timeout only",
22199                MeshPolicy {
22200                    timeout: Some(Duration::from_secs(30)),
22201                    circuit_breaker: Some(cb(5, 10)),
22202                    ..Default::default()
22203                },
22204                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
22205                    window: Duration::from_secs(10),
22206                    timeout: Duration::from_secs(30),
22207                }),
22208            ),
22209            (
22210                "starve only",
22211                MeshPolicy {
22212                    rate_limit: Some(rl(1, 3600)),
22213                    circuit_breaker: Some(cb(5, 10)),
22214                    ..Default::default()
22215                },
22216                Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
22217                    rate: 1,
22218                    rl_window: Duration::from_secs(3600),
22219                    max_failures: 5,
22220                    cb_window: Duration::from_secs(10),
22221                }),
22222            ),
22223            (
22224                "retries-saturate only",
22225                MeshPolicy {
22226                    retries: Some(3),
22227                    circuit_breaker: Some(cb(3, 60)),
22228                    ..Default::default()
22229                },
22230                Some(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
22231                    retries: 3,
22232                    max_failures: 3,
22233                }),
22234            ),
22235            (
22236                "retries-burst only",
22237                MeshPolicy {
22238                    retries: Some(5),
22239                    rate_limit: Some(rl(3, 1)),
22240                    ..Default::default()
22241                },
22242                Some(AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
22243                    retries: 5,
22244                    rate: 3,
22245                }),
22246            ),
22247            ("empty policy", MeshPolicy::default(), None),
22248            (
22249                "fully-coherent policy",
22250                MeshPolicy {
22251                    timeout: Some(Duration::from_secs(30)),
22252                    retries: Some(3),
22253                    circuit_breaker: Some(cb(5, 60)),
22254                    mtls_required: Some(true),
22255                    rate_limit: Some(rl(100, 1)),
22256                },
22257                None,
22258            ),
22259        ];
22260        assert_first_cross_axis_violation_agrees_with_gate(cases);
22261    }
22262
22263    #[test]
22264    fn first_cross_axis_violation_matches_gate_on_pairwise_orderings() {
22265        // Half-B of the compound-fold ≡ gate equivalence pin: the
22266        // load-bearing pairwise-ordering coverage. Every ordered pair
22267        // of the four cross-axis arms — six combinations — where two
22268        // arms are simultaneously eligible must surface the
22269        // more-foundational arm's diagnostic verbatim. Pins the fold's
22270        // arm-ordering byte-for-byte against the validate cascade's
22271        // arm-ordering, so a future reshuffle of either side that
22272        // silently drifts the ordering trips here rather than as a
22273        // per-arm miss the sibling per-arm `_predicate_matches_gate_semantic`
22274        // pins cannot catch (they clear every sibling arm, so their
22275        // sweeps are pairwise-ordering-agnostic by construction).
22276        //
22277        // The six pairs the four-arm cascade admits:
22278        // window-before-starve, window-before-saturate,
22279        // window-before-burst, starve-before-saturate,
22280        // starve-before-burst, saturate-before-burst.
22281        let cb = |max_failures: u32, secs: u64| CircuitBreaker {
22282            max_failures,
22283            window: Duration::from_secs(secs),
22284        };
22285        let rl = |rate: u32, secs: u64| RateLimit {
22286            rate,
22287            window: Duration::from_secs(secs),
22288        };
22289        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
22290            (
22291                "window+starve → window wins",
22292                MeshPolicy {
22293                    timeout: Some(Duration::from_secs(30)),
22294                    rate_limit: Some(rl(1, 3600)),
22295                    circuit_breaker: Some(cb(5, 10)),
22296                    ..Default::default()
22297                },
22298                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
22299                    window: Duration::from_secs(10),
22300                    timeout: Duration::from_secs(30),
22301                }),
22302            ),
22303            (
22304                "window+retries-saturate → window wins",
22305                MeshPolicy {
22306                    timeout: Some(Duration::from_secs(30)),
22307                    retries: Some(5),
22308                    circuit_breaker: Some(cb(3, 10)),
22309                    ..Default::default()
22310                },
22311                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
22312                    window: Duration::from_secs(10),
22313                    timeout: Duration::from_secs(30),
22314                }),
22315            ),
22316            (
22317                "window+retries-burst → window wins",
22318                MeshPolicy {
22319                    timeout: Some(Duration::from_secs(30)),
22320                    retries: Some(5),
22321                    rate_limit: Some(rl(3, 1)),
22322                    circuit_breaker: Some(cb(5, 10)),
22323                    ..Default::default()
22324                },
22325                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
22326                    window: Duration::from_secs(10),
22327                    timeout: Duration::from_secs(30),
22328                }),
22329            ),
22330            (
22331                "starve+retries-saturate → starve wins",
22332                MeshPolicy {
22333                    retries: Some(5),
22334                    rate_limit: Some(rl(1, 3600)),
22335                    circuit_breaker: Some(cb(5, 10)),
22336                    ..Default::default()
22337                },
22338                Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
22339                    rate: 1,
22340                    rl_window: Duration::from_secs(3600),
22341                    max_failures: 5,
22342                    cb_window: Duration::from_secs(10),
22343                }),
22344            ),
22345            (
22346                "starve+retries-burst → starve wins",
22347                MeshPolicy {
22348                    retries: Some(5),
22349                    rate_limit: Some(rl(1, 3600)),
22350                    circuit_breaker: Some(cb(10, 10)),
22351                    ..Default::default()
22352                },
22353                Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
22354                    rate: 1,
22355                    rl_window: Duration::from_secs(3600),
22356                    max_failures: 10,
22357                    cb_window: Duration::from_secs(10),
22358                }),
22359            ),
22360            (
22361                "retries-saturate+retries-burst → saturate wins",
22362                MeshPolicy {
22363                    retries: Some(5),
22364                    rate_limit: Some(rl(3, 1)),
22365                    circuit_breaker: Some(cb(3, 60)),
22366                    ..Default::default()
22367                },
22368                Some(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
22369                    retries: 5,
22370                    max_failures: 3,
22371                }),
22372            ),
22373        ];
22374        assert_first_cross_axis_violation_agrees_with_gate(cases);
22375    }
22376
22377    /// Sweep body shared by every `MeshPolicy::validate` ≡ gate
22378    /// equivalence pin — assert that on each `(label, politicas,
22379    /// expected)` case both the substrate primitive
22380    /// [`MeshPolicy::validate`] and the [`AplicacaoSpec::validate_politicas`]
22381    /// cascade (reached through `AplicacaoSpec::validate`, keying off the
22382    /// same `three_member_spec` fixture whose non-`:politicas` slots
22383    /// always validate cleanly) return identical `AplicacaoError` variants.
22384    /// Peer of [`assert_first_cross_axis_violation_agrees_with_gate`] on
22385    /// the sibling cross-axis-only surface — extended here onto the
22386    /// compound per-axis + cross-axis entry gate. Extracted so each pin's
22387    /// own body stays under `clippy::too_many_lines`.
22388    fn assert_validate_matches_gate(cases: &[(&str, MeshPolicy, Option<AplicacaoError>)]) {
22389        for (label, politicas, expected) in cases {
22390            let direct = politicas.validate();
22391            match (expected, &direct) {
22392                (None, Ok(())) => {}
22393                (None, Err(got)) => {
22394                    panic!("`{label}`: MeshPolicy::validate must pass; got {got:?}")
22395                }
22396                (Some(want), Ok(())) => {
22397                    panic!("`{label}`: MeshPolicy::validate must return {want:?}; got Ok")
22398                }
22399                (Some(want), Err(got)) => assert_eq!(
22400                    got, want,
22401                    "`{label}`: MeshPolicy::validate must return {want:?}; got {got:?}"
22402                ),
22403            }
22404
22405            let mut s = three_member_spec();
22406            s.politicas = politicas.clone();
22407            let gate = s.validate();
22408            match (expected, &gate) {
22409                (None, Ok(())) => {}
22410                (None, Err(got)) => {
22411                    panic!("`{label}`: validate_politicas gate must pass; got {got:?}")
22412                }
22413                (Some(want), Ok(())) => {
22414                    panic!("`{label}`: validate_politicas gate must return {want:?}; got Ok")
22415                }
22416                (Some(want), Err(got)) => assert_eq!(
22417                    got, want,
22418                    "`{label}`: validate_politicas gate must return {want:?}; got {got:?}"
22419                ),
22420            }
22421        }
22422    }
22423
22424    #[test]
22425    fn validate_matches_gate_on_per_axis_and_phase_boundary_shapes() {
22426        // Half-A of the compound-per-axis-+-cross-axis-fold ≡ gate
22427        // equivalence pin on [`MeshPolicy::validate`]: the four per-axis
22428        // zero-floor arms (`:timeout`, `:retries`, `:circuit-breaker
22429        // :max-failures`, `:rate-limit` rate) that discriminate the
22430        // "per-axis phase fires" arm of the compound gate, plus one
22431        // per-axis-before-cross-axis case (`{ timeout: 30s, cb.window:
22432        // ZERO }`) that pins the phase-boundary ordering — the per-axis
22433        // `PolicyBreakerZeroWindow` arm strictly precedes the cross-axis
22434        // `PolicyBreakerWindowBelowTimeout` arm, so the zero-window
22435        // diagnostic wins over the window-below-timeout diagnostic. Peer
22436        // of the sibling
22437        // `first_cross_axis_violation_matches_gate_on_single_arm_and_vacuous_shapes`
22438        // + `_on_pairwise_orderings` pins on the compound cross-axis
22439        // fold, extended here onto the outer compound entry gate that
22440        // folds per-axis + cross-axis surfaces. Half-B (cross-axis and
22441        // clean-pass surfaces) lives in the sibling
22442        // `validate_matches_gate_on_cross_axis_and_clean_pass_shapes`
22443        // pin; splitting keeps each pin's body under
22444        // `clippy::too_many_lines`.
22445        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
22446            (
22447                "per-axis: timeout zero",
22448                MeshPolicy {
22449                    timeout: Some(Duration::ZERO),
22450                    ..Default::default()
22451                },
22452                Some(AplicacaoError::PolicyTimeoutZero),
22453            ),
22454            (
22455                "per-axis: retries zero",
22456                MeshPolicy {
22457                    retries: Some(0),
22458                    ..Default::default()
22459                },
22460                Some(AplicacaoError::PolicyRetriesZero),
22461            ),
22462            (
22463                "per-axis: breaker max-failures zero",
22464                MeshPolicy {
22465                    circuit_breaker: Some(CircuitBreaker {
22466                        max_failures: 0,
22467                        window: Duration::from_secs(60),
22468                    }),
22469                    ..Default::default()
22470                },
22471                Some(AplicacaoError::PolicyBreakerZeroFailures),
22472            ),
22473            (
22474                "per-axis: rate-limit rate zero",
22475                MeshPolicy {
22476                    rate_limit: Some(RateLimit {
22477                        rate: 0,
22478                        window: Duration::from_secs(1),
22479                    }),
22480                    ..Default::default()
22481                },
22482                Some(AplicacaoError::PolicyRateLimitZero),
22483            ),
22484            (
22485                "per-axis before cross-axis: zero-window wins over window-below-timeout",
22486                MeshPolicy {
22487                    timeout: Some(Duration::from_secs(30)),
22488                    circuit_breaker: Some(CircuitBreaker {
22489                        max_failures: 5,
22490                        window: Duration::ZERO,
22491                    }),
22492                    ..Default::default()
22493                },
22494                Some(AplicacaoError::PolicyBreakerZeroWindow),
22495            ),
22496        ];
22497        assert_validate_matches_gate(cases);
22498    }
22499
22500    #[test]
22501    fn validate_matches_gate_on_cross_axis_and_clean_pass_shapes() {
22502        // Half-B of the compound-per-axis-+-cross-axis-fold ≡ gate
22503        // equivalence pin on [`MeshPolicy::validate`]: the cross-axis
22504        // arm that discriminates the "cross-axis phase fires" arm of
22505        // the compound gate (window-below-timeout — sibling per-arm
22506        // coverage lives in the two
22507        // `first_cross_axis_violation_matches_gate_on_*` pins above),
22508        // plus the two clean-pass shapes (empty policy — every axis
22509        // absent — and fully-coherent — every axis inside the coherence
22510        // surface) that pin the compound gate's `Ok(())` arm. Half-A
22511        // (per-axis + phase-boundary surfaces) lives in the sibling
22512        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
22513        // pin; splitting keeps each pin's body under
22514        // `clippy::too_many_lines`.
22515        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
22516            (
22517                "cross-axis: window-below-timeout",
22518                MeshPolicy {
22519                    timeout: Some(Duration::from_secs(30)),
22520                    circuit_breaker: Some(CircuitBreaker {
22521                        max_failures: 5,
22522                        window: Duration::from_secs(10),
22523                    }),
22524                    ..Default::default()
22525                },
22526                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
22527                    window: Duration::from_secs(10),
22528                    timeout: Duration::from_secs(30),
22529                }),
22530            ),
22531            ("clean pass: empty policy", MeshPolicy::default(), None),
22532            (
22533                "clean pass: every axis coherent",
22534                MeshPolicy {
22535                    timeout: Some(Duration::from_secs(30)),
22536                    retries: Some(3),
22537                    circuit_breaker: Some(CircuitBreaker {
22538                        max_failures: 5,
22539                        window: Duration::from_secs(60),
22540                    }),
22541                    mtls_required: Some(true),
22542                    rate_limit: Some(RateLimit {
22543                        rate: 100,
22544                        window: Duration::from_secs(1),
22545                    }),
22546                },
22547                None,
22548            ),
22549        ];
22550        assert_validate_matches_gate(cases);
22551    }
22552
22553    #[test]
22554    fn empty_politicas_validates() {
22555        // Omitting every policy axis is fine — defaults express "no
22556        // policy on this axis", not "policy = 0". The fixture's typical
22557        // values continue to validate; this test pins that
22558        // MeshPolicy::default() is a clean pass through validate().
22559        let mut s = three_member_spec();
22560        s.politicas = MeshPolicy::default();
22561        s.validate().unwrap();
22562    }
22563
22564    #[test]
22565    fn typical_politicas_validates_with_every_axis_set() {
22566        // The full §III.1 example block (timeout + retries + breaker +
22567        // mtls + rate-limit) — every axis nonzero — must remain a
22568        // clean pass.
22569        let mut s = three_member_spec();
22570        s.politicas = MeshPolicy {
22571            timeout: Some(Duration::from_secs(30)),
22572            retries: Some(3),
22573            circuit_breaker: Some(CircuitBreaker {
22574                max_failures: 5,
22575                window: Duration::from_secs(60),
22576            }),
22577            mtls_required: Some(true),
22578            rate_limit: Some(RateLimit {
22579                rate: 100,
22580                window: Duration::from_secs(1),
22581            }),
22582        };
22583        s.validate().unwrap();
22584    }
22585
22586    #[test]
22587    fn rejects_empty_cluster_name() {
22588        let mut s = three_member_spec();
22589        s.placement.clusters = vec!["rio".into(), String::new()];
22590        assert_eq!(
22591            s.validate().unwrap_err(),
22592            AplicacaoError::PlacementClusterEmpty
22593        );
22594    }
22595
22596    #[test]
22597    fn rejects_duplicate_cluster_names() {
22598        let mut s = three_member_spec();
22599        s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
22600        let err = s.validate().unwrap_err();
22601        assert!(
22602            matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
22603            "got {err:?}"
22604        );
22605    }
22606
22607    #[test]
22608    fn rejects_placement_cluster_with_uppercase() {
22609        // The canonical "I copied the cluster's display name verbatim"
22610        // typo — K8s context names are lowercase per DNS-1123 label
22611        // rule, but org docs often round-trip a TitleCase identifier
22612        // (`Rio`, `Mar-East`) from an ADR. Mirrors the
22613        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
22614        // on the peer name axis.
22615        let mut s = three_member_spec();
22616        s.placement.clusters = vec!["Rio".into(), "mar".into()];
22617        let err = s.validate().unwrap_err();
22618        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
22619            panic!("expected PlacementClusterInvalid, got other variant");
22620        };
22621        assert_eq!(cluster, "Rio");
22622        assert!(
22623            reason.contains("uppercase"),
22624            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
22625        );
22626        assert!(
22627            reason.contains("\"rio\""),
22628            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
22629        );
22630    }
22631
22632    #[test]
22633    fn rejects_placement_cluster_with_underscore() {
22634        // The canonical "I'm thinking of an env var / hostname slug"
22635        // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
22636        // schema. K8s context filtering on `my_cluster` silently misses
22637        // the cluster the author intended; the gate moves it to caixa-
22638        // build time. Same shape as `rejects_membro_caixa_with_underscore`
22639        // (3f9d7a0).
22640        let mut s = three_member_spec();
22641        s.placement.clusters = vec!["my_cluster".into()];
22642        let err = s.validate().unwrap_err();
22643        assert!(
22644            matches!(
22645                err,
22646                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
22647                    if cluster == "my_cluster" && reason.contains('_')
22648            ),
22649            "got {err:?}"
22650        );
22651    }
22652
22653    #[test]
22654    fn rejects_placement_cluster_with_dot() {
22655        // A `:placement :clusters` entry is a single DNS-1123 *label*,
22656        // not a subdomain — even though K8s context names sometimes
22657        // carry a dotted form via kubeconfig conventions, the strictest
22658        // floor among the use sites (DNS-1035 cluster.x-k8s.io
22659        // `metadata.name`, Cilium identity label values) wins. The "I
22660        // want to namespace my cluster names with `.`" intent is
22661        // expressed via `-` (`mar-east`).
22662        let mut s = three_member_spec();
22663        s.placement.clusters = vec!["team.rio".into()];
22664        let err = s.validate().unwrap_err();
22665        assert!(
22666            matches!(
22667                err,
22668                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
22669                    if cluster == "team.rio" && reason.contains('.')
22670            ),
22671            "got {err:?}"
22672        );
22673    }
22674
22675    #[test]
22676    fn rejects_placement_cluster_with_leading_hyphen() {
22677        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
22678        // with an alphanumeric. The K8s apiserver rejects `-rio`
22679        // outright; the rendered fan-out would emit a `metadata.name:
22680        // "-rio"` that fails admission far from the source caixa.lisp.
22681        let mut s = three_member_spec();
22682        s.placement.clusters = vec!["-rio".into()];
22683        let err = s.validate().unwrap_err();
22684        assert!(
22685            matches!(
22686                err,
22687                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
22688                    if cluster == "-rio" && reason.contains("start and end")
22689            ),
22690            "got {err:?}"
22691        );
22692    }
22693
22694    #[test]
22695    fn rejects_placement_cluster_with_trailing_hyphen() {
22696        // The symmetric arm of the boundary rule. Pin separately so
22697        // both ends are covered against a future relaxation that only
22698        // checks one boundary (parallel to
22699        // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
22700        let mut s = three_member_spec();
22701        s.placement.clusters = vec!["rio-".into()];
22702        let err = s.validate().unwrap_err();
22703        assert!(
22704            matches!(
22705                err,
22706                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
22707                    if cluster == "rio-"
22708            ),
22709            "got {err:?}"
22710        );
22711    }
22712
22713    #[test]
22714    fn rejects_placement_cluster_with_unicode() {
22715        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
22716        // before it reaches K8s. The byte-by-byte ASCII validity check
22717        // rejects multi-byte UTF-8 sequences by the first byte that
22718        // fails `[a-z0-9-]`.
22719        let mut s = three_member_spec();
22720        s.placement.clusters = vec!["rió".into()];
22721        let err = s.validate().unwrap_err();
22722        assert!(
22723            matches!(
22724                err,
22725                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
22726                    if cluster == "rió"
22727            ),
22728            "got {err:?}"
22729        );
22730    }
22731
22732    #[test]
22733    fn rejects_placement_cluster_with_whitespace() {
22734        // Whitespace is the canonical "I pasted from a sketch / doc"
22735        // footgun. The apiserver rejects every cluster `metadata.name`
22736        // value carrying whitespace.
22737        let mut s = three_member_spec();
22738        s.placement.clusters = vec!["rio cluster".into()];
22739        let err = s.validate().unwrap_err();
22740        assert!(
22741            matches!(
22742                err,
22743                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
22744                    if cluster == "rio cluster"
22745            ),
22746            "got {err:?}"
22747        );
22748    }
22749
22750    #[test]
22751    fn rejects_placement_cluster_too_long() {
22752        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
22753        // pin. The diagnostic names both the cap (63) and the actual
22754        // length so the author can shorten in one edit. Mirrors
22755        // `rejects_membro_caixa_too_long` (3f9d7a0).
22756        let mut s = three_member_spec();
22757        let too_long = "a".repeat(64);
22758        s.placement.clusters = vec![too_long.clone()];
22759        let err = s.validate().unwrap_err();
22760        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
22761            panic!("expected PlacementClusterInvalid");
22762        };
22763        assert_eq!(cluster, too_long);
22764        assert!(
22765            reason.contains("63") && reason.contains("64"),
22766            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
22767        );
22768    }
22769
22770    #[test]
22771    fn placement_cluster_max_length_validates() {
22772        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
22773        // future tightening (e.g. dropping to 62) surfaces here as a
22774        // regression, mirroring `membro_caixa_max_length_validates`
22775        // (3f9d7a0).
22776        let mut s = three_member_spec();
22777        s.placement.clusters = vec!["a".repeat(63)];
22778        s.validate().unwrap();
22779    }
22780
22781    #[test]
22782    fn accepts_canonical_placement_cluster_forms() {
22783        // The DNS-1123 label shapes a caixa author is realistically
22784        // going to write for cluster names: single-word lowercase
22785        // (`rio`), regional hyphen-joined (`mar-east`), single
22786        // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
22787        // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
22788        // Pin every leg so a future tightening that bans (e.g.) digit-
22789        // start identifiers surfaces here.
22790        for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
22791            let mut s = three_member_spec();
22792            s.placement.clusters = vec![form.into()];
22793            s.validate().unwrap_or_else(|e| {
22794                panic!("canonical cluster form {form:?} must validate, got {e:?}")
22795            });
22796        }
22797    }
22798
22799    #[test]
22800    fn placement_cluster_empty_takes_precedence_over_invalid() {
22801        // Order pin: the existing `PlacementClusterEmpty` diagnostic
22802        // (which doesn't try to parse) fires before the new
22803        // `PlacementClusterInvalid` parse-side diagnostic, so an empty
22804        // `:clusters` entry keeps its narrower error message — the new
22805        // gate would also reject `""`, but the empty-string arm is the
22806        // more self-locating diagnostic. Mirrors the
22807        // `membro_caixa_empty_takes_precedence_over_invalid` pin
22808        // (3f9d7a0).
22809        let mut s = three_member_spec();
22810        s.placement.clusters = vec!["rio".into(), String::new()];
22811        let err = s.validate().unwrap_err();
22812        assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
22813    }
22814
22815    #[test]
22816    fn placement_cluster_invalid_fires_before_duplicate_check() {
22817        // Order pin: a malformed-shape `:clusters` entry surfaces *its
22818        // own* diagnostic, even when a later entry would otherwise
22819        // collapse onto a duplicate name. The per-entry shape gate runs
22820        // inline before the duplicate-key insert, parallel to
22821        // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
22822        let mut s = three_member_spec();
22823        s.placement.clusters = vec!["Rio".into(), "rio".into()];
22824        let err = s.validate().unwrap_err();
22825        assert!(
22826            matches!(
22827                err,
22828                AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
22829            ),
22830            "got {err:?}"
22831        );
22832    }
22833
22834    #[test]
22835    fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
22836        // The diagnostic-shape pin: the error names the offending
22837        // `:clusters` value verbatim so the author can grep their
22838        // caixa.lisp without re-running the build, and carries a
22839        // non-empty `reason` naming the specific violation. Same shape
22840        // every typed-shape gate enshrines
22841        // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
22842        // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
22843        let mut s = three_member_spec();
22844        s.placement.clusters = vec!["BAD_CLUSTER".into()];
22845        let err = s.validate().unwrap_err();
22846        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
22847            panic!("expected PlacementClusterInvalid");
22848        };
22849        assert_eq!(cluster, "BAD_CLUSTER");
22850        assert!(
22851            !reason.is_empty(),
22852            "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
22853        );
22854    }
22855
22856    #[test]
22857    fn rejects_sharded_with_empty_clusters() {
22858        // §III.1: Sharded uses :clusters as the shard pool. An empty
22859        // pool means "shard across no clusters" — meaningless, same as
22860        // Replicated with no hosts.
22861        let mut s = three_member_spec();
22862        s.placement.estrategia = PlacementStrategy::Sharded;
22863        s.placement.shard_key = Some("$tenantId".into());
22864        s.placement.clusters = vec![];
22865        assert!(matches!(
22866            s.validate().unwrap_err(),
22867            AplicacaoError::PlacementWithoutClusters {
22868                estrategia: PlacementStrategy::Sharded
22869            }
22870        ));
22871    }
22872
22873    #[test]
22874    fn rejects_sharded_with_empty_shard_key() {
22875        let mut s = three_member_spec();
22876        s.placement.estrategia = PlacementStrategy::Sharded;
22877        s.placement.shard_key = Some(String::new());
22878        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
22879    }
22880
22881    #[test]
22882    fn rejects_shard_key_under_replicated_strategy() {
22883        // The fail-before-pass-after pin: a `:placement (:estrategia
22884        // Replicated :shard-key "tenantId")` manifest carries the
22885        // hash-keyed-distribution slot on a strategy that never consumes
22886        // it. Before the gate the typed slot's value silently vanished
22887        // at the renderer layer (caixa-mesh emits `placement.shardKey`
22888        // verbatim regardless of strategy; the Akka-style cluster-
22889        // sharding reconciler keys off `estrategia == Sharded` and
22890        // ignores the slot otherwise), with no diagnostic. Lifting the
22891        // rejection to a build-time gate makes the
22892        // `shard_key.is_some() == matches!(estrategia, Sharded)`
22893        // partition a structural property of every validated
22894        // [`Placement`].
22895        let mut s = three_member_spec();
22896        // The fixture already uses Replicated; just add a shard-key.
22897        s.placement.shard_key = Some("$tenantId".into());
22898        let err = s.validate().unwrap_err();
22899        let AplicacaoError::ShardKeyOnNonSharded {
22900            estrategia,
22901            shard_key,
22902        } = err
22903        else {
22904            panic!("expected ShardKeyOnNonSharded, got {err:?}");
22905        };
22906        assert_eq!(estrategia, PlacementStrategy::Replicated);
22907        assert_eq!(shard_key, "$tenantId");
22908    }
22909
22910    #[test]
22911    fn rejects_shard_key_under_singlenode_strategy() {
22912        // Peer of the Replicated case above on the SingleNode arm: OTP
22913        // distributed-app takeover (one cluster runs at a time) has no
22914        // hash-keyed routing axis to consume `:shard-key` either, so
22915        // the rejection fires on both non-Sharded arms uniformly.
22916        let mut s = three_member_spec();
22917        s.placement.estrategia = PlacementStrategy::SingleNode;
22918        s.placement.shard_key = Some("$tenantId".into());
22919        let err = s.validate().unwrap_err();
22920        let AplicacaoError::ShardKeyOnNonSharded {
22921            estrategia,
22922            shard_key,
22923        } = err
22924        else {
22925            panic!("expected ShardKeyOnNonSharded, got {err:?}");
22926        };
22927        assert_eq!(estrategia, PlacementStrategy::SingleNode);
22928        assert_eq!(shard_key, "$tenantId");
22929    }
22930
22931    #[test]
22932    fn rejects_empty_shard_key_under_replicated_strategy() {
22933        // The `Some("")` case under non-Sharded is rejected by
22934        // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
22935        // fires before the empty-value gate), not
22936        // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
22937        // the `Sharded` arm). Pin the partition so a future reorder of
22938        // the validate_placement match arms doesn't silently swap which
22939        // diagnostic the author sees — both are author errors, but
22940        // ShardKeyOnNonSharded names which strategy is the actual fix
22941        // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
22942        // only says "pick a non-empty key".
22943        let mut s = three_member_spec();
22944        s.placement.shard_key = Some(String::new());
22945        let err = s.validate().unwrap_err();
22946        assert!(
22947            matches!(
22948                err,
22949                AplicacaoError::ShardKeyOnNonSharded {
22950                    estrategia: PlacementStrategy::Replicated,
22951                    ref shard_key,
22952                } if shard_key.is_empty()
22953            ),
22954            "got {err:?}"
22955        );
22956    }
22957
22958    #[test]
22959    fn replicated_without_shard_key_validates() {
22960        // The complement of the rejection: `:placement :estrategia
22961        // Replicated` with `:shard-key None` is the canonical happy
22962        // path on every existing fixture. Pin the no-shard-key case so
22963        // the new gate doesn't accidentally fire on `None`.
22964        let mut s = three_member_spec();
22965        assert!(matches!(
22966            s.placement.estrategia,
22967            PlacementStrategy::Replicated
22968        ));
22969        s.placement.shard_key = None;
22970        s.validate().unwrap();
22971    }
22972
22973    #[test]
22974    fn singlenode_without_shard_key_validates() {
22975        // Peer of the Replicated no-shard-key case on the SingleNode
22976        // arm — both non-Sharded strategies must validate cleanly when
22977        // the slot is omitted.
22978        let mut s = three_member_spec();
22979        s.placement.estrategia = PlacementStrategy::SingleNode;
22980        s.placement.shard_key = None;
22981        s.validate().unwrap();
22982    }
22983
22984    fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
22985        // Fixture builder for the `:placement :shard-key` shape gate
22986        // tests: a three-member Aplicacao on the `Sharded` strategy
22987        // with the supplied `:shard-key` slot. Co-locates the
22988        // arm-construction so every test below carries one line of
22989        // setup (the offending `:shard-key` value) and the assertion.
22990        let mut s = three_member_spec();
22991        s.placement.estrategia = PlacementStrategy::Sharded;
22992        s.placement.shard_key = Some(key.into());
22993        s
22994    }
22995
22996    #[test]
22997    fn rejects_shard_key_with_embedded_space() {
22998        // The canonical paste-from-aligned-doc footgun:
22999        // `:shard-key "$tenant Id"` — the Akka-style entity-id
23000        // extractor reads the slot as a single-token reference, and an
23001        // embedded space breaks the token boundary at the runtime
23002        // hash-extractor pass with no diagnostic naming the offending
23003        // entry.
23004        let s = sharded_spec_with_key("$tenant Id");
23005        let err = s.validate().unwrap_err();
23006        assert!(
23007            matches!(
23008                err,
23009                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
23010                    if shard_key == "$tenant Id" && reason.contains("space")
23011            ),
23012            "got {err:?}"
23013        );
23014    }
23015
23016    #[test]
23017    fn rejects_shard_key_with_leading_space() {
23018        // Leading-space arm of the embedded-whitespace footgun — the
23019        // paste-from-aligned-doc / paste-from-CSV-cell variant where
23020        // the leading column-padding leaked into the slot.
23021        let s = sharded_spec_with_key(" $tenantId");
23022        let err = s.validate().unwrap_err();
23023        assert!(
23024            matches!(
23025                err,
23026                AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
23027                    if shard_key == " $tenantId"
23028            ),
23029            "got {err:?}"
23030        );
23031    }
23032
23033    #[test]
23034    fn rejects_shard_key_with_trailing_newline() {
23035        // The canonical paste-from-shell-heredoc footgun — every
23036        // `<<EOF` heredoc terminator paste leaves a trailing newline
23037        // the YAML emitter then folds away inconsistently across
23038        // emitter implementations.
23039        let s = sharded_spec_with_key("$tenantId\n");
23040        let err = s.validate().unwrap_err();
23041        assert!(
23042            matches!(
23043                err,
23044                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
23045                    if shard_key == "$tenantId\n" && reason.contains("0x0a")
23046            ),
23047            "got {err:?}"
23048        );
23049    }
23050
23051    #[test]
23052    fn rejects_shard_key_with_embedded_tab() {
23053        // The paste-from-aligned-doc tab-stop variant — tabs land
23054        // alongside spaces in copy-paste from formatted columns.
23055        let s = sharded_spec_with_key("$tenant\tId");
23056        let err = s.validate().unwrap_err();
23057        assert!(
23058            matches!(
23059                err,
23060                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
23061                    if shard_key == "$tenant\tId" && reason.contains("tab")
23062            ),
23063            "got {err:?}"
23064        );
23065    }
23066
23067    #[test]
23068    fn rejects_shard_key_with_control_character() {
23069        // The paste-from-binary / paste-from-screen-cleared-terminal
23070        // footgun — an embedded `\x01` (SOH) byte that some YAML
23071        // emitters silently strip and others escape as ``,
23072        // breaking round-trip across emitter implementations.
23073        let s = sharded_spec_with_key("$tenant\u{0001}Id");
23074        let err = s.validate().unwrap_err();
23075        assert!(
23076            matches!(
23077                err,
23078                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
23079                    if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
23080            ),
23081            "got {err:?}"
23082        );
23083    }
23084
23085    #[test]
23086    fn rejects_shard_key_with_non_ascii() {
23087        // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
23088        // footgun — non-ASCII bytes normalize differently between the
23089        // caixa-mesh-side YAML emitter and the in-cluster reconciler's
23090        // YAML parser, the same entity ID can silently map to two
23091        // distinct shards on a re-render.
23092        let s = sharded_spec_with_key("$tenàntId");
23093        let err = s.validate().unwrap_err();
23094        assert!(
23095            matches!(
23096                err,
23097                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
23098                    if shard_key == "$tenàntId" && reason.contains("non-ASCII")
23099            ),
23100            "got {err:?}"
23101        );
23102    }
23103
23104    #[test]
23105    fn rejects_shard_key_too_long() {
23106        // Length cap pin: 64 bytes — one byte over the
23107        // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
23108        // here is a paste-from-doc multi-line blob landing in
23109        // `:shard-key` instead of a single-token extractor expression.
23110        let too_long = "a".repeat(64);
23111        let s = sharded_spec_with_key(&too_long);
23112        let err = s.validate().unwrap_err();
23113        let AplicacaoError::ShardKeyInvalid {
23114            ref shard_key,
23115            ref reason,
23116        } = err
23117        else {
23118            panic!("expected ShardKeyInvalid, got {err:?}");
23119        };
23120        assert_eq!(shard_key, &too_long);
23121        assert!(
23122            reason.contains("63") && reason.contains("64"),
23123            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
23124        );
23125    }
23126
23127    #[test]
23128    fn shard_key_max_length_validates() {
23129        // Boundary pin: 63 bytes exactly — the
23130        // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
23131        // dropping to 62) surfaces here as a regression, mirroring
23132        // `placement_cluster_max_length_validates` /
23133        // `placement_affinity_max_length_validates` on the peer
23134        // identifier-shaped slots.
23135        let s = sharded_spec_with_key(&"a".repeat(63));
23136        s.validate().unwrap();
23137    }
23138
23139    #[test]
23140    fn accepts_canonical_shard_key_forms() {
23141        // The Akka-style entity-id extractor shapes a caixa author is
23142        // realistically going to write — pin every leg so a future
23143        // tightening that bans (e.g.) the `${...}` interpolation
23144        // variant or the `metadata.<field>` JSONPath form surfaces
23145        // here as a regression. The canonical forms span:
23146        //
23147        //   - bare property name (`tenantId`, `customerId`)
23148        //   - Akka `ExtractEntityId` placeholder (`$tenantId`)
23149        //   - JSONPath-style nested reference (`metadata.tenantId`,
23150        //     `$.user.id`)
23151        //   - interpolation-style template (`${tenant}`)
23152        //   - snake_case property name (`customer_id`)
23153        //   - kebab-case property name (`customer-id` — accepted
23154        //     because the slot is a printable-ASCII single-token
23155        //     reference, not a DNS-1123 label like
23156        //     `:placement :affinity` / `:clusters`)
23157        //   - single character (`a`, `$` — boundary)
23158        for form in [
23159            "tenantId",
23160            "customerId",
23161            "$tenantId",
23162            "metadata.tenantId",
23163            "$.user.id",
23164            "${tenant}",
23165            "customer_id",
23166            "customer-id",
23167            "a",
23168            "$",
23169        ] {
23170            let s = sharded_spec_with_key(form);
23171            s.validate().unwrap_or_else(|e| {
23172                panic!("canonical shard-key form {form:?} must validate, got {e:?}")
23173            });
23174        }
23175    }
23176
23177    #[test]
23178    fn shard_key_empty_takes_precedence_over_invalid() {
23179        // Order pin: the existing `ShardedKeyEmpty` diagnostic
23180        // (reserved for the `Sharded` `Some("")` arm) fires before the
23181        // new `ShardKeyInvalid` parse-side diagnostic, so an empty
23182        // `:shard-key` keeps its narrower error message — the new gate
23183        // would also reject `""` defensively, but the empty-string arm
23184        // is the more self-locating diagnostic. Mirrors the
23185        // `placement_cluster_empty_takes_precedence_over_invalid` pin
23186        // on the peer identifier-shaped slot.
23187        let s = sharded_spec_with_key("");
23188        let err = s.validate().unwrap_err();
23189        assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
23190    }
23191
23192    #[test]
23193    fn shard_key_invalid_diagnostic_carries_offending_value() {
23194        // The diagnostic-shape pin: the error names the offending
23195        // `:shard-key` value verbatim so the author can grep their
23196        // caixa.lisp without re-running the build, and carries a
23197        // parser-shaped `reason:` naming the specific violation —
23198        // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
23199        // on the peer identifier-shaped slot.
23200        let s = sharded_spec_with_key("$tenant Id");
23201        let err = s.validate().unwrap_err();
23202        let AplicacaoError::ShardKeyInvalid {
23203            ref shard_key,
23204            ref reason,
23205        } = err
23206        else {
23207            panic!("expected ShardKeyInvalid, got {err:?}");
23208        };
23209        assert_eq!(shard_key, "$tenant Id");
23210        assert!(
23211            !reason.is_empty(),
23212            "reason must name the specific violation, got empty string"
23213        );
23214    }
23215
23216    #[test]
23217    fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
23218        // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
23219        // `:shard-key` carried on non-Sharded strategies) fires before
23220        // the shape gate, so a malformed `:shard-key` carried on (e.g.)
23221        // a `Replicated` strategy surfaces the more self-locating
23222        // strategy-mismatch diagnostic (naming the actual fix — drop
23223        // the slot, or switch to Sharded) rather than the shape
23224        // diagnostic. The strategy-mismatch arm is the more actionable
23225        // diagnostic: a malformed shard-key on Replicated is "you
23226        // shouldn't have a :shard-key here at all", not "your
23227        // :shard-key value is malformed".
23228        let mut s = three_member_spec();
23229        // Replicated is the default fixture strategy.
23230        s.placement.shard_key = Some("$tenant Id".into());
23231        let err = s.validate().unwrap_err();
23232        assert!(
23233            matches!(
23234                err,
23235                AplicacaoError::ShardKeyOnNonSharded {
23236                    estrategia: PlacementStrategy::Replicated,
23237                    ..
23238                }
23239            ),
23240            "got {err:?}"
23241        );
23242    }
23243
23244    #[test]
23245    fn rejects_empty_affinity_hint() {
23246        let mut s = three_member_spec();
23247        s.placement.affinity = Some(String::new());
23248        assert_eq!(
23249            s.validate().unwrap_err(),
23250            AplicacaoError::PlacementAffinityEmpty
23251        );
23252    }
23253
23254    #[test]
23255    fn placement_without_affinity_validates() {
23256        // Omitting :affinity is fine — the placement engine falls back
23257        // to the default heuristic. Pin the no-hint case so the
23258        // affinity-empty rejection doesn't accidentally fire on `None`.
23259        let mut s = three_member_spec();
23260        s.placement.affinity = None;
23261        s.validate().unwrap();
23262    }
23263
23264    #[test]
23265    fn rejects_placement_affinity_with_uppercase() {
23266        // The canonical "I copied the ADR's display name verbatim" typo
23267        // — placement hints land verbatim in K8s label-selector
23268        // territory, where the apiserver enforces the DNS-1123 label
23269        // rule (lowercase-only) on every identity-keyed admission axis.
23270        // Mirrors `rejects_placement_cluster_with_uppercase` on the
23271        // sibling slot.
23272        let mut s = three_member_spec();
23273        s.placement.affinity = Some("DataLocality".into());
23274        let err = s.validate().unwrap_err();
23275        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
23276            panic!("expected PlacementAffinityInvalid, got other variant");
23277        };
23278        assert_eq!(affinity, "DataLocality");
23279        assert!(
23280            reason.contains("uppercase"),
23281            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
23282        );
23283        assert!(
23284            reason.contains("\"datalocality\""),
23285            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
23286        );
23287    }
23288
23289    #[test]
23290    fn rejects_placement_affinity_with_underscore() {
23291        // The canonical "I'm thinking of an env var / Python identifier"
23292        // leak — `_` is forbidden by every DNS-1123 label schema. Same
23293        // shape as `rejects_placement_cluster_with_underscore` on the
23294        // sibling slot.
23295        let mut s = three_member_spec();
23296        s.placement.affinity = Some("data_locality".into());
23297        let err = s.validate().unwrap_err();
23298        assert!(
23299            matches!(
23300                err,
23301                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
23302                    if affinity == "data_locality" && reason.contains('_')
23303            ),
23304            "got {err:?}"
23305        );
23306    }
23307
23308    #[test]
23309    fn rejects_placement_affinity_with_dot() {
23310        // A `:placement :affinity` value is a single DNS-1123 *label*
23311        // (it lands as a K8s label value selector key), not a subdomain.
23312        // The "I want to namespace my hint with `.`" intent is expressed
23313        // via `-` (`data-locality-east`).
23314        let mut s = three_member_spec();
23315        s.placement.affinity = Some("data.locality".into());
23316        let err = s.validate().unwrap_err();
23317        assert!(
23318            matches!(
23319                err,
23320                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
23321                    if affinity == "data.locality" && reason.contains('.')
23322            ),
23323            "got {err:?}"
23324        );
23325    }
23326
23327    #[test]
23328    fn rejects_placement_affinity_with_unicode() {
23329        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
23330        // before it reaches K8s. The byte-by-byte ASCII validity check
23331        // rejects multi-byte UTF-8 sequences by the first byte that
23332        // fails `[a-z0-9-]`.
23333        let mut s = three_member_spec();
23334        s.placement.affinity = Some("data-localité".into());
23335        let err = s.validate().unwrap_err();
23336        assert!(
23337            matches!(
23338                err,
23339                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
23340                    if affinity == "data-localité"
23341            ),
23342            "got {err:?}"
23343        );
23344    }
23345
23346    #[test]
23347    fn rejects_placement_affinity_with_leading_hyphen() {
23348        // DNS-1123 boundary rule: labels must start with an
23349        // alphanumeric. Pin separately from the trailing-hyphen arm so
23350        // a future relaxation that only checks one boundary surfaces
23351        // here as a regression (parallel to
23352        // `rejects_placement_cluster_with_leading_hyphen`).
23353        let mut s = three_member_spec();
23354        s.placement.affinity = Some("-data-locality".into());
23355        let err = s.validate().unwrap_err();
23356        assert!(
23357            matches!(
23358                err,
23359                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
23360                    if affinity == "-data-locality" && reason.contains("start and end")
23361            ),
23362            "got {err:?}"
23363        );
23364    }
23365
23366    #[test]
23367    fn rejects_placement_affinity_with_trailing_hyphen() {
23368        // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
23369        // ends are covered against a future relaxation.
23370        let mut s = three_member_spec();
23371        s.placement.affinity = Some("data-locality-".into());
23372        let err = s.validate().unwrap_err();
23373        assert!(
23374            matches!(
23375                err,
23376                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
23377                    if affinity == "data-locality-"
23378            ),
23379            "got {err:?}"
23380        );
23381    }
23382
23383    #[test]
23384    fn rejects_placement_affinity_with_whitespace() {
23385        // Whitespace is the canonical "I pasted from a sketch / doc"
23386        // footgun. The apiserver rejects every label-selector value
23387        // carrying whitespace.
23388        let mut s = three_member_spec();
23389        s.placement.affinity = Some("data locality".into());
23390        let err = s.validate().unwrap_err();
23391        assert!(
23392            matches!(
23393                err,
23394                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
23395                    if affinity == "data locality"
23396            ),
23397            "got {err:?}"
23398        );
23399    }
23400
23401    #[test]
23402    fn rejects_placement_affinity_too_long() {
23403        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
23404        // pin. The diagnostic names both the cap (63) and the actual
23405        // length so the author can shorten in one edit. Mirrors
23406        // `rejects_placement_cluster_too_long`.
23407        let mut s = three_member_spec();
23408        let too_long = "a".repeat(64);
23409        s.placement.affinity = Some(too_long.clone());
23410        let err = s.validate().unwrap_err();
23411        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
23412            panic!("expected PlacementAffinityInvalid");
23413        };
23414        assert_eq!(affinity, too_long);
23415        assert!(
23416            reason.contains("63") && reason.contains("64"),
23417            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
23418        );
23419    }
23420
23421    #[test]
23422    fn placement_affinity_max_length_validates() {
23423        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
23424        // future tightening (e.g. dropping to 62) surfaces here as a
23425        // regression, mirroring `placement_cluster_max_length_validates`.
23426        let mut s = three_member_spec();
23427        s.placement.affinity = Some("a".repeat(63));
23428        s.validate().unwrap();
23429    }
23430
23431    #[test]
23432    fn accepts_canonical_placement_affinity_forms() {
23433        // The DNS-1123 label shapes a caixa author is realistically
23434        // going to write for placement hints: the M3 canonical examples
23435        // (`data-locality`, `low-latency`, `anti-affinity`), the
23436        // single-token form (`affinity`), the single-character boundary
23437        // (`a`), the digit-start (DNS-1123 allows this, unlike
23438        // DNS-1035), and a regional-suffixed form. Pin every leg so a
23439        // future tightening that bans (e.g.) digit-start identifiers
23440        // surfaces here.
23441        for form in [
23442            "data-locality",
23443            "low-latency",
23444            "anti-affinity",
23445            "affinity",
23446            "a",
23447            "3-tier",
23448            "locality-east",
23449        ] {
23450            let mut s = three_member_spec();
23451            s.placement.affinity = Some(form.into());
23452            s.validate().unwrap_or_else(|e| {
23453                panic!("canonical affinity form {form:?} must validate, got {e:?}")
23454            });
23455        }
23456    }
23457
23458    #[test]
23459    fn placement_affinity_empty_takes_precedence_over_invalid() {
23460        // Order pin: the existing `PlacementAffinityEmpty` diagnostic
23461        // (which doesn't try to parse) fires before the new
23462        // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
23463        // `:affinity` keeps its narrower error message — the new gate
23464        // would also reject `""`, but the empty-string arm is the more
23465        // self-locating diagnostic. Mirrors the
23466        // `placement_cluster_empty_takes_precedence_over_invalid` pin.
23467        let mut s = three_member_spec();
23468        s.placement.affinity = Some(String::new());
23469        let err = s.validate().unwrap_err();
23470        assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
23471    }
23472
23473    #[test]
23474    fn placement_affinity_invalid_diagnostic_carries_offending_value() {
23475        // The diagnostic shape pin: every rejection carries the offending
23476        // `affinity:` verbatim plus a parser-shaped `reason:` so the
23477        // author can grep their caixa.lisp for `:affinity "<hint>"` and
23478        // fix it in one edit. Mirrors the
23479        // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
23480        // pin on the sibling slot.
23481        let mut s = three_member_spec();
23482        s.placement.affinity = Some("Data_Locality".into());
23483        let err = s.validate().unwrap_err();
23484        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
23485            panic!("expected PlacementAffinityInvalid");
23486        };
23487        assert_eq!(affinity, "Data_Locality");
23488        assert!(
23489            !reason.is_empty(),
23490            "diagnostic reason must not be empty (got: {reason:?})"
23491        );
23492    }
23493
23494    #[test]
23495    fn singlenode_with_takeover_candidates_validates() {
23496        // OTP distributed-application convention (MESH-COMPOSITION
23497        // §II.1): SingleNode runs on one cluster at a time but the
23498        // :clusters list enumerates the takeover candidates. Multiple
23499        // entries are not a contradiction — they are the failover pool.
23500        let mut s = three_member_spec();
23501        s.placement.estrategia = PlacementStrategy::SingleNode;
23502        s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
23503        s.validate().unwrap();
23504    }
23505
23506    // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
23507
23508    #[test]
23509    fn mesh_policy_default_is_empty() {
23510        // The Default impl carries None on every axis — the typed
23511        // analog of an unset `:politicas (())` slot. Renderers that
23512        // overlay the policy onto a cluster artifact key off this
23513        // predicate to skip the slot entirely; pinning so a future
23514        // axis added to MeshPolicy can't silently break the contract
23515        // (a new field whose Default is non-None would flip is_empty
23516        // to false on every existing caixa, surfacing here).
23517        assert!(MeshPolicy::default().is_empty());
23518    }
23519
23520    #[test]
23521    fn mesh_policy_with_only_timeout_is_not_empty() {
23522        let p = MeshPolicy {
23523            timeout: Some(Duration::from_secs(30)),
23524            ..Default::default()
23525        };
23526        assert!(!p.is_empty());
23527    }
23528
23529    #[test]
23530    fn mesh_policy_with_only_retries_is_not_empty() {
23531        let p = MeshPolicy {
23532            retries: Some(3),
23533            ..Default::default()
23534        };
23535        assert!(!p.is_empty());
23536    }
23537
23538    #[test]
23539    fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
23540        let p = MeshPolicy {
23541            circuit_breaker: Some(CircuitBreaker {
23542                max_failures: 5,
23543                window: Duration::from_secs(60),
23544            }),
23545            ..Default::default()
23546        };
23547        assert!(!p.is_empty());
23548    }
23549
23550    #[test]
23551    fn mesh_policy_with_only_mtls_required_is_not_empty() {
23552        // Even `mtls_required: Some(false)` (an explicit opt-out) is
23553        // not empty — the author *named* the axis, the renderer needs
23554        // to honor that vs. fall back to the cluster default.
23555        let p = MeshPolicy {
23556            mtls_required: Some(false),
23557            ..Default::default()
23558        };
23559        assert!(!p.is_empty());
23560    }
23561
23562    #[test]
23563    fn mesh_policy_with_only_rate_limit_is_not_empty() {
23564        let p = MeshPolicy {
23565            rate_limit: Some(RateLimit {
23566                rate: 100,
23567                window: Duration::from_secs(1),
23568            }),
23569            ..Default::default()
23570        };
23571        assert!(!p.is_empty());
23572    }
23573
23574    #[test]
23575    fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
23576        // The three-member happy-path fixture sets timeout + retries +
23577        // mtls_required — every populated axis must read non-empty.
23578        // Pin the round-trip so the M3.x per-:politicas emitter (the
23579        // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
23580        // on is_empty() to decide whether to emit at all without
23581        // re-deriving the contract from inline field probes.
23582        assert!(!three_member_spec().politicas.is_empty());
23583    }
23584
23585    // ── shared duration codec: cross-slot integer-magnitude gate ──
23586    //
23587    // The integer-magnitude discipline applied to
23588    // `supervisor::duration_codec::parse` lifts onto every typed slot
23589    // that routes through the shared codec — `MeshPolicy::timeout`
23590    // (`:politicas :timeout`) and `CircuitBreaker::window`
23591    // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
23592    // These cross-slot tests pin that the gate fires at the serde
23593    // layer for both typed slots, not just for the supervisor side.
23594
23595    #[test]
23596    fn policy_timeout_serde_rejects_fractional_seconds() {
23597        // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
23598        // so the shared codec's integer-magnitude gate applies on
23599        // deserialize. `"1.5s"` previously parsed to 1500ms and round-
23600        // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
23601        // deserialize with the canonical-form diagnostic naming the
23602        // offending `"1.5"` and the remediation `"1500ms"`.
23603        let payload = r#"{"timeout":"1.5s"}"#;
23604        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23605        let msg = err.to_string();
23606        assert!(
23607            msg.contains("not a non-negative integer"),
23608            "expected integer-magnitude diagnostic in {msg:?}"
23609        );
23610        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
23611        assert!(
23612            msg.contains("\"1500ms\""),
23613            "missing canonical-form remediation in {msg:?}"
23614        );
23615    }
23616
23617    #[test]
23618    fn policy_timeout_serde_rejects_leading_plus_sign() {
23619        // Pin the leading-`+` arm cross-slot — the prior f64 parser
23620        // accepted `"+30s"` silently and round-tripped to `"30s"`.
23621        let payload = r#"{"timeout":"+30s"}"#;
23622        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23623        let msg = err.to_string();
23624        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
23625    }
23626
23627    #[test]
23628    fn circuit_breaker_window_serde_rejects_fractional_minutes() {
23629        // `CircuitBreaker::window` uses `with =
23630        // "supervisor::duration_codec_required"` (the required-Duration
23631        // variant that delegates to the same shared parser). `"0.5m"`
23632        // parsed to 30s and round-tripped to `"30s"` on next emit —
23633        // DRIFT closed.
23634        let payload = format!(
23635            r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
23636            max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
23637            window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
23638        );
23639        let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
23640        let msg = err.to_string();
23641        assert!(
23642            msg.contains("not a non-negative integer"),
23643            "expected integer-magnitude diagnostic in {msg:?}"
23644        );
23645        assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
23646        assert!(
23647            msg.contains("\"30s\""),
23648            "missing canonical-form remediation in {msg:?}"
23649        );
23650    }
23651
23652    #[test]
23653    fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
23654        // Pin the happy-path on the cross-slot side: every canonical
23655        // author shape `render` ever emits parses cleanly through the
23656        // shared codec on the `CircuitBreaker` slot. The
23657        // codec's accepted set (post-gate) is exactly its emitted set
23658        // for the integer-magnitude class.
23659        for window_lit in ["30s", "500ms", "2m", "1h"] {
23660            let payload = format!(
23661                r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
23662                max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
23663                window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
23664            );
23665            let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
23666                panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
23667            });
23668            assert_eq!(cb.max_failures, 5);
23669        }
23670    }
23671
23672    // ── rate_limit_codec: integer-magnitude gate ──
23673    //
23674    // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
23675    // / 737a676 / d53c922 trajectory landed on every typed-duration /
23676    // typed-byte-size codec in caixa-core lifts onto the fifth typed
23677    // codec — `rate_limit_codec` — through the digit-only magnitude
23678    // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
23679    // These tests pin the gate at the serde layer for `:politicas
23680    // :rate-limit` (the only typed slot the codec backs), and at the
23681    // codec-internal `parse` layer for the canonical positive cases.
23682
23683    #[test]
23684    fn rate_limit_serde_rejects_fractional_rate() {
23685        // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
23686        // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
23687        // wording, which didn't name the canonical-form remediation or
23688        // the round-trip drift the next emit would produce. Now refused
23689        // at deserialize with the canonical-form diagnostic naming the
23690        // offending `"1.5"` magnitude and the round-trip drift wording.
23691        let payload = r#"{"rateLimit":"1.5/s"}"#;
23692        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23693        let msg = err.to_string();
23694        assert!(
23695            msg.contains("not a non-negative integer"),
23696            "expected integer-magnitude diagnostic in {msg:?}"
23697        );
23698        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
23699        assert!(
23700            msg.contains("THEORY.md"),
23701            "missing render-determinism contract citation in {msg:?}"
23702        );
23703    }
23704
23705    #[test]
23706    fn rate_limit_serde_rejects_leading_plus_sign() {
23707        // `u32::from_str("+100")` returns `Ok(100)` (Rust's
23708        // permissive-`+` parse), so `"+100/s"` silently parsed to
23709        // `RateLimit { 100, 1s }` and round-tripped through `render` to
23710        // `"100/s"` — a *different* canonical string on the next emit,
23711        // breaking the THEORY.md Part V render-determinism contract
23712        // exactly the way the peer duration codecs' `"+30s"` case did.
23713        // This is the load-bearing class the digit-only gate closes
23714        // beyond what `u32::from_str`'s strictness covers on its own.
23715        let payload = r#"{"rateLimit":"+100/s"}"#;
23716        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23717        let msg = err.to_string();
23718        assert!(
23719            msg.contains("not a non-negative integer"),
23720            "expected integer-magnitude diagnostic in {msg:?}"
23721        );
23722        assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
23723    }
23724
23725    #[test]
23726    fn rate_limit_serde_rejects_leading_minus_sign() {
23727        // The signed-negative arm: `"-1/s"` lands on the
23728        // non-canonical-but-numeric branch via the `i64` fallback (the
23729        // `f64` parse also succeeds), surfacing the canonical-form
23730        // diagnostic. Replaces the prior value-laundered "not a u32"
23731        // wording with the unified diagnostic across signs.
23732        let payload = r#"{"rateLimit":"-1/s"}"#;
23733        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23734        let msg = err.to_string();
23735        assert!(
23736            msg.contains("not a non-negative integer"),
23737            "expected integer-magnitude diagnostic in {msg:?}"
23738        );
23739        assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
23740    }
23741
23742    #[test]
23743    fn rate_limit_serde_rejects_decimal_shaped_integer() {
23744        // `"100.0/s"` is integer-valued numerically but not in the
23745        // codec's accepted set — `render` emits `"100/s"`, so the
23746        // round-trip would drift. Lifted to the canonical-form
23747        // diagnostic peer with the duration codec's `"1.0s"` case
23748        // (1c55a2a).
23749        let payload = r#"{"rateLimit":"100.0/s"}"#;
23750        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23751        let msg = err.to_string();
23752        assert!(
23753            msg.contains("not a non-negative integer"),
23754            "expected integer-magnitude diagnostic in {msg:?}"
23755        );
23756        assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
23757    }
23758
23759    #[test]
23760    fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
23761        // Non-numeric, non-digit-only input lands on the existing
23762        // narrower `"not a u32"` arm (preserved for diagnostic-shape
23763        // stability on the parser-shape footgun case). Pin this so a
23764        // future relaxation of the numeric-fallback predicate doesn't
23765        // silently collapse garbage onto the canonical-form arm — same
23766        // partition the peer duration codecs draw between
23767        // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
23768        let payload = r#"{"rateLimit":"abc/s"}"#;
23769        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23770        let msg = err.to_string();
23771        assert!(
23772            msg.contains("not a u32"),
23773            "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
23774        );
23775        assert!(
23776            !msg.contains("not a non-negative integer"),
23777            "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
23778        );
23779    }
23780
23781    #[test]
23782    fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
23783        // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
23784        // u32's range. The digit-only gate passes; `u32::from_str`
23785        // fails on overflow. Surface that with the overflow-shaped
23786        // diagnostic naming the offending magnitude verbatim, peer
23787        // with `supervisor::duration_codec`'s overflow arm. Pinning
23788        // the wording so a future refactor doesn't silently collapse
23789        // overflow onto the canonical-form arm.
23790        let payload = r#"{"rateLimit":"4294967296/s"}"#;
23791        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23792        let msg = err.to_string();
23793        assert!(
23794            msg.contains("overflows u32"),
23795            "expected overflow diagnostic in {msg:?}"
23796        );
23797        assert!(
23798            msg.contains("\"4294967296\""),
23799            "missing offending magnitude in {msg:?}"
23800        );
23801    }
23802
23803    #[test]
23804    fn rate_limit_serde_rejects_leading_zero_magnitude() {
23805        // `"0100/s"` is digit-only, so the existing
23806        // non-digit-only / sign / fractional arm doesn't catch it —
23807        // `u32::from_str("0100")` returns `Ok(100)`, so before this
23808        // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
23809        // round-tripped through `render` to `"100/s"` — a *different*
23810        // canonical string on the next emit, breaking the THEORY.md
23811        // Part V render-determinism contract exactly the way the
23812        // peer `"+100/s"` case did before the leading-`+` arm landed.
23813        // This is the load-bearing class the leading-zero gate closes
23814        // beyond what the existing digit-only / sign / fractional
23815        // gates cover, and the peer arm to the leading-`+` test
23816        // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
23817        // canonical-form-drift axis.
23818        let payload = r#"{"rateLimit":"0100/s"}"#;
23819        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23820        let msg = err.to_string();
23821        assert!(
23822            msg.contains("non-canonical leading zero"),
23823            "expected leading-zero diagnostic in {msg:?}"
23824        );
23825        assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
23826        assert!(
23827            msg.contains("THEORY.md"),
23828            "missing render-determinism contract citation in {msg:?}"
23829        );
23830    }
23831
23832    #[test]
23833    fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
23834        // `"00/s"` is the degenerate leading-zero case — every byte
23835        // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
23836        // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
23837        // a *different* canonical string, same render-determinism
23838        // violation. The single-byte `"0/s"` itself is in the
23839        // accepted set (round-trips losslessly through `render`,
23840        // refused downstream by `PolicyRateLimitZero`); the
23841        // multi-byte `"00/s"` is not. Pins the boundary between the
23842        // accepted single-`0` and the rejected leading-zero class.
23843        let payload = r#"{"rateLimit":"00/s"}"#;
23844        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23845        let msg = err.to_string();
23846        assert!(
23847            msg.contains("non-canonical leading zero"),
23848            "expected leading-zero diagnostic in {msg:?}"
23849        );
23850        assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
23851    }
23852
23853    #[test]
23854    fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
23855        // Cross-window pin — the gate is window-agnostic; the
23856        // leading-zero class is a property of the magnitude, not the
23857        // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
23858        // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
23859        // single-window coverage extended across the three canonical
23860        // windows the codec accepts.
23861        let payload = r#"{"rateLimit":"007/h"}"#;
23862        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23863        let msg = err.to_string();
23864        assert!(
23865            msg.contains("non-canonical leading zero"),
23866            "expected leading-zero diagnostic in {msg:?}"
23867        );
23868        assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
23869    }
23870
23871    #[test]
23872    fn rate_limit_serde_rejects_leading_whitespace() {
23873        // `" 100/s"` — the canonical paste-from-aligned-doc /
23874        // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
23875        // the top-level `s.trim()` silently ate the leading space and
23876        // parsed the value to `RateLimit { 100, 1s }`, which then
23877        // round-tripped through `render` to `"100/s"` (a *different*
23878        // canonical string on the next emit) — the exact
23879        // canonical-form-drift class the leading-`+` / leading-zero
23880        // arms already close, extended to the whitespace byte class.
23881        let payload = r#"{"rateLimit":" 100/s"}"#;
23882        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23883        let msg = err.to_string();
23884        assert!(
23885            msg.contains("contains whitespace byte"),
23886            "expected whitespace diagnostic in {msg:?}"
23887        );
23888        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
23889        assert!(
23890            msg.contains("THEORY.md"),
23891            "missing render-determinism contract citation in {msg:?}"
23892        );
23893    }
23894
23895    #[test]
23896    fn rate_limit_serde_rejects_trailing_whitespace() {
23897        // `"100/s "` — the canonical shell-history / trailing-space
23898        // paste footgun. Before this gate the top-level `s.trim()`
23899        // silently ate the trailing space and parsed to
23900        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
23901        // next emit — same canonical-form drift as the leading-space
23902        // sibling, closed on the same whitespace-byte arm.
23903        let payload = r#"{"rateLimit":"100/s "}"#;
23904        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23905        let msg = err.to_string();
23906        assert!(
23907            msg.contains("contains whitespace byte"),
23908            "expected whitespace diagnostic in {msg:?}"
23909        );
23910        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
23911    }
23912
23913    #[test]
23914    fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
23915        // `"100 / s"` — the canonical typographically-spaced author
23916        // shape (the same idiom every prose reference to a rate limit
23917        // renders as, mistakenly retained when the value is pasted
23918        // into a codec-shaped slot). Before this gate the per-part
23919        // `rate_str.trim()` / `unit.trim()` calls silently ate both
23920        // spaces on either side of `/` and parsed to
23921        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
23922        // codec's *internal* whitespace-tolerance vector, orthogonal
23923        // to the leading / trailing surface but the same canonical-
23924        // form-drift class. Pins the arm as strictly stronger than the
23925        // pre-existing top-level `s.trim()` behavior: it fires on
23926        // whitespace anywhere in the value, not just at the string
23927        // boundary.
23928        let payload = r#"{"rateLimit":"100 / s"}"#;
23929        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23930        let msg = err.to_string();
23931        assert!(
23932            msg.contains("contains whitespace byte"),
23933            "expected whitespace diagnostic in {msg:?}"
23934        );
23935        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
23936    }
23937
23938    #[test]
23939    fn rate_limit_serde_rejects_tab_byte() {
23940        // `"\t100/s"` — the canonical paste-from-indented-doc /
23941        // paste-from-YAML-block-scalar footgun where a tab byte leads
23942        // the magnitude. Pins that the gate covers tab (`0x09`) as
23943        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
23944        // members and both would be silently swallowed by `s.trim()`
23945        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
23946        // space alone to the full ASCII-whitespace set (space `0x20`,
23947        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
23948        // the tab arm as a representative of the non-space members.
23949        let payload = r#"{"rateLimit":"\t100/s"}"#;
23950        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23951        let msg = err.to_string();
23952        assert!(
23953            msg.contains("contains whitespace byte"),
23954            "expected whitespace diagnostic in {msg:?}"
23955        );
23956        assert!(
23957            msg.contains("0x09"),
23958            "missing offending tab byte in {msg:?}"
23959        );
23960    }
23961
23962    // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
23963    //
23964    // Successor to the ASCII-whitespace arm (1ad7755) on
23965    // `rate_limit_codec` — closes the strictly-complementary class the
23966    // byte-scan cannot see, through the lifted
23967    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
23968
23969    #[test]
23970    fn rate_limit_serde_rejects_leading_nbsp() {
23971        // NBSP prefix — paste-from-typography footgun. Byte-scan
23972        // misses, `str::trim` silently strips it, value drifts to
23973        // `"100/s"` on next serialize.
23974        let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
23975        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23976        let msg = err.to_string();
23977        assert!(
23978            msg.contains("non-ASCII Unicode whitespace character"),
23979            "expected non-ASCII whitespace diagnostic in {msg:?}"
23980        );
23981        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
23982    }
23983
23984    #[test]
23985    fn rate_limit_serde_rejects_internal_em_space() {
23986        // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
23987        // paste-from-typography footgun on the `<integer>/<unit>`
23988        // shape.
23989        let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
23990        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23991        let msg = err.to_string();
23992        assert!(
23993            msg.contains("non-ASCII Unicode whitespace character"),
23994            "expected non-ASCII whitespace diagnostic in {msg:?}"
23995        );
23996        assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
23997    }
23998
23999    #[test]
24000    fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
24001        // Positive-control pin: every ASCII-only canonical form the
24002        // renderer emits stays accepted through the new arm.
24003        for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
24004            let payload = format!(r#"{{"rateLimit":{lit}}}"#);
24005            let p: MeshPolicy = serde_json::from_str(&payload)
24006                .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
24007            assert!(p.rate_limit.is_some());
24008        }
24009    }
24010
24011    #[test]
24012    fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
24013        // The boundary case — `"0/s"` is the canonical form
24014        // `render(RateLimit { 0, 1s })` emits, so the codec accepts
24015        // it at the parse layer; the downstream
24016        // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
24017        // `rate == 0` at the typed-validate layer above. Pins the
24018        // partition: the leading-zero gate at the codec layer does
24019        // not poach the rate-zero semantic-validation arm at the
24020        // typed-validate layer above (a future stricter codec must
24021        // not reject `"0/s"` here, or it'd collapse the diagnostic
24022        // partitioning that lets `PolicyRateLimitZero` name the
24023        // offending typed slot).
24024        let payload = r#"{"rateLimit":"0/s"}"#;
24025        let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
24026            panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
24027        });
24028        let rl = policy.rate_limit.expect("rate_limit must be Some");
24029        assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
24030        assert_eq!(
24031            rl.window,
24032            Duration::from_secs(1),
24033            "single-`0` magnitude with `s` unit must parse to window=1s"
24034        );
24035    }
24036
24037    #[test]
24038    fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
24039        // The complementary boundary pin — every magnitude
24040        // `render` emits starts with `[1-9]` (or is the single byte
24041        // `"0"`), so the canonical-form predicate is `(len == 1) ||
24042        // (first byte != '0')`. Pinning the `len > 1 && first byte ==
24043        // '1'` case explicitly so a future tightening of the gate
24044        // (e.g. an over-eager "no leading digit < 5" rule, or a
24045        // mistakenly anchored start-of-magnitude byte check) lands
24046        // here before the canonical-forms-iterating test would catch
24047        // it.
24048        let payload = r#"{"rateLimit":"100/s"}"#;
24049        let policy: MeshPolicy = serde_json::from_str(payload)
24050            .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
24051        let rl = policy.rate_limit.expect("rate_limit must be Some");
24052        assert_eq!(
24053            rl.rate, 100,
24054            "canonical-100 magnitude must parse to rate=100"
24055        );
24056    }
24057
24058    #[test]
24059    fn rate_limit_serde_accepts_integer_canonical_forms() {
24060        // Pin the happy-path: every canonical author shape `render`
24061        // ever emits parses cleanly through the codec post-gate. The
24062        // codec's accepted set (post-gate) is exactly its emitted set
24063        // for the integer-magnitude class — same property
24064        // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
24065        // gates guarantee on the peer codecs. Iterating across rate
24066        // magnitudes (including `"0"`, which the codec accepts even
24067        // though `validate_politicas` rejects `rate == 0` at the typed
24068        // layer above) closes the codec contract at the parse layer
24069        // independently of the validate layer.
24070        for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
24071            for unit_lit in ["s", "m", "h"] {
24072                let lit = format!("{rate_lit}/{unit_lit}");
24073                let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
24074                let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
24075                    panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
24076                });
24077                let rl = policy.rate_limit.expect("rate_limit must be Some");
24078                assert_eq!(
24079                    rl.rate,
24080                    rate_lit.parse::<u32>().unwrap(),
24081                    "rate mismatch for {lit:?}"
24082                );
24083            }
24084        }
24085    }
24086
24087    #[test]
24088    fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
24089        // The structural property the gate enforces: serialize ∘
24090        // deserialize is the identity on every canonical author shape.
24091        // Peer of `parse_byte_size`'s and `parse_duration`'s
24092        // `_round_trips_through_render_for_every_canonical_form` tests
24093        // on the rate-limit axis. Before the gate, `"+100/s"` violated
24094        // this (`parse` → `RateLimit { 100, 1s }` → `render` →
24095        // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
24096        for rate in [1u32, 100, 5000, 1_000_000] {
24097            for (window, unit) in [
24098                (Duration::from_secs(1), "s"),
24099                (Duration::from_secs(60), "m"),
24100                (Duration::from_secs(3600), "h"),
24101            ] {
24102                let policy = MeshPolicy {
24103                    rate_limit: Some(RateLimit { rate, window }),
24104                    ..Default::default()
24105                };
24106                let json = serde_json::to_string(&policy).unwrap();
24107                let expected = format!("\"{rate}/{unit}\"");
24108                assert!(
24109                    json.contains(&expected),
24110                    "expected {expected:?} in {json:?}"
24111                );
24112                let back: MeshPolicy = serde_json::from_str(&json).unwrap();
24113                assert_eq!(
24114                    back.rate_limit, policy.rate_limit,
24115                    "round-trip for {json:?}"
24116                );
24117            }
24118        }
24119    }
24120
24121    // ── self-membership cross-slot gate ──────────────────────────────
24122
24123    #[test]
24124    fn validate_no_self_membership_rejects_self_named_membro() {
24125        // An Aplicacao whose `:membros` lists its own `:nome` is a
24126        // one-node lacre-closure recursion — rejected, naming the parent.
24127        let membros = vec![
24128            membro("catalog", "^0.1"),
24129            membro("checkout", "^0.1"),
24130            membro("cart", "^0.1"),
24131        ];
24132        let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
24133        assert!(
24134            matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
24135            "got {err:?}"
24136        );
24137    }
24138
24139    #[test]
24140    fn validate_no_self_membership_accepts_distinct_membros() {
24141        // Positive control: distinct member names (including a member
24142        // that is itself an Aplicacao — recursive composition is valid,
24143        // MESH-COMPOSITION §V) pass the gate.
24144        let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
24145        validate_no_self_membership(&membros, "checkout").unwrap();
24146    }
24147
24148    #[test]
24149    fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
24150        // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
24151        // `NoMembros` arm (the more-fundamental "graph must have nodes"
24152        // gate), not by this cross-slot self-edge gate. Keeping the
24153        // self-membership predicate vacuously-ok on the empty input
24154        // matches its supervisor-axis peer
24155        // (`validate_no_self_supervision_empty_children_is_ok`) and
24156        // makes the gate composable from any future call site (an M4
24157        // CR materializer's per-membros validator) without re-checking
24158        // emptiness.
24159        validate_no_self_membership(&[], "checkout").unwrap();
24160    }
24161
24162    #[test]
24163    fn validate_no_self_membership_diagnostic_names_offending_caixa() {
24164        // Pinning the Display: the self-membership diagnostic must name
24165        // the offending caixa verbatim + the "lists itself" framing the
24166        // author can grep for, so the cluster-far failure surfaces at
24167        // build time with one-line remediation. Same diagnostic shape
24168        // as the supervisor-axis `ChildSupervisesSelf` peer.
24169        let membros = vec![membro("orquestra", "^0.1")];
24170        let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
24171        let msg = err.to_string();
24172        assert!(
24173            msg.contains("orquestra"),
24174            "diagnostic must name the offending caixa nome (got: {msg:?})"
24175        );
24176        assert!(
24177            msg.contains("lists itself"),
24178            "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
24179        );
24180    }
24181
24182    #[test]
24183    fn default_servico_port_constant_pins_canonical_8080_literal() {
24184        // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
24185        // at the verbatim `8080` literal both consumers (the
24186        // `Entrada::port` serde default via [`default_port`] and the
24187        // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
24188        // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
24189        // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
24190        // discipline (a085b26) on the per-renderer canonical-K8s-axis
24191        // string-constant axis: a future refactor that drifts the
24192        // constant out from under either consumer surfaces here ahead
24193        // of every per-renderer's first emission. The literal value
24194        // matches the well-known HTTP-alt port the `pleme-computeunit`
24195        // library chart already emits as its `trigger.service.port`
24196        // default — by construction the same value the substrate
24197        // assumes about every Servico's in-cluster L4 listener.
24198        assert_eq!(
24199            DEFAULT_SERVICO_PORT, 8080,
24200            "canonical Servico port literal must remain `8080` verbatim — \
24201             this is the value both the `Entrada::port` serde default and the \
24202             caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
24203        );
24204    }
24205
24206    #[test]
24207    fn default_port_helper_returns_canonical_servico_port_constant() {
24208        // The bridge-arm — pins that the [`default_port`] helper
24209        // [`Entrada::port`]'s `#[serde(default = "default_port")]`
24210        // attribute hooks routes through the lifted
24211        // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
24212        // literal. A future refactor that re-introduces the `8080`
24213        // literal at the helper's return site (silently re-opening
24214        // the drift footgun this lift closed) surfaces here ahead of
24215        // every author-side `(:entrada (:host … :para …))` slot
24216        // without an explicit `:port`. Peer with the
24217        // `default_namespace_re_export_points_at_caixa_core_canonical`
24218        // pin on the caixa-mesh-side re-export axis.
24219        assert_eq!(
24220            default_port(),
24221            DEFAULT_SERVICO_PORT,
24222            "the serde-default helper must route through the lifted constant"
24223        );
24224    }
24225
24226    #[test]
24227    fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
24228        // The end-to-end pin — an author-surface `(:entrada (:host …
24229        // :para …))` without an explicit `:port` slot deserializes to
24230        // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
24231        // verbatim. Routes the canonical lifted constant through both
24232        // the serde-default machinery (the `#[serde(default =
24233        // "default_port")]` attribute) and the typed-value-shape
24234        // contract (the resulting [`Entrada::port`] value). A future
24235        // refactor that drifts either axis — replacing the serde
24236        // hook's helper, changing the typed slot's wire shape — would
24237        // surface here before any per-renderer's CNP / Gateway /
24238        // HTTPRoute emission consumed the drifted default.
24239        let entrada: Entrada =
24240            serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
24241        assert_eq!(
24242            entrada.port, DEFAULT_SERVICO_PORT,
24243            "the serde default must materialize as the lifted canonical Servico port"
24244        );
24245    }
24246
24247    #[test]
24248    fn servico_port_min_pins_canonical_accept_set_floor() {
24249        // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
24250        // verbatim `1` literal every typed `:entrada :port` acceptance
24251        // gate keys off. Peer with the
24252        // [`default_servico_port_constant_pins_canonical_8080_literal`]
24253        // discipline on the canonical-Servico-port-constant axis: a
24254        // future refactor that drifts the accept-set floor out from
24255        // under the sole consumer at [`AplicacaoSpec::validate`]'s
24256        // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
24257        // every per-`:entrada` `EntradaPortZero` diagnostic. The
24258        // literal value matches the IANA-registered TCP/UDP port
24259        // space floor (`1..=65535` — port `0` is the "any ephemeral"
24260        // sentinel, not a well-defined destination the substrate's
24261        // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
24262        // axis can honor).
24263        assert_eq!(
24264            SERVICO_PORT_MIN, 1,
24265            "canonical Servico port accept-set floor must remain `1` verbatim — \
24266             this is the value the `AplicacaoSpec::validate` gate at \
24267             `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
24268        );
24269    }
24270
24271    #[test]
24272    fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
24273        // The cross-const invariant pin — the substrate's canonical
24274        // default port must satisfy its own accept-set floor by
24275        // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
24276        // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
24277        // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
24278        // override the operator pins through a future
24279        // `:placement :default-port` slot that lands out-of-range, a
24280        // per-edition Servico-port migration that lifted the floor
24281        // above the previous default without coordinating the pair —
24282        // would silently invalidate the serde-default emission at
24283        // every author-side `(:entrada (:host … :para …))` slot
24284        // without an explicit `:port`: the default port would fall
24285        // below the accept-set floor, the `AplicacaoSpec::validate`
24286        // gate would reject every default-carrying Aplicacao as
24287        // `EntradaPortZero`, and the substrate's typed
24288        // `(defcaixa … :kind Aplicacao)` surface would fail validate
24289        // on every Aplicacao whose author omitted `:entrada :port`
24290        // for the substrate's chosen default — a class of authoring-
24291        // surface footguns the compile-time pin structurally closes.
24292        // Peer with the
24293        // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
24294        // (27f9b34) cross-const invariant pin discipline on the peer
24295        // canonical-Helm-per-values-block child-chart-enablement-toggle
24296        // axis pair.
24297        const {
24298            assert!(
24299                SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
24300                "the substrate's canonical default port DEFAULT_SERVICO_PORT \
24301                 must satisfy its own accept-set floor SERVICO_PORT_MIN — \
24302                 every default-carrying `(:entrada (:host … :para …))` slot \
24303                 without an explicit `:port` inherits `DEFAULT_SERVICO_PORT` \
24304                 through the serde default hook and must pass the \
24305                 `AplicacaoSpec::validate` floor gate by construction",
24306            );
24307        }
24308    }
24309
24310    #[test]
24311    fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
24312        // The gate-site pin — asserts the `AplicacaoSpec::validate`
24313        // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
24314        // `EntradaPortZero` diagnostic on the below-floor input
24315        // `port: 0` (the only below-floor value the `u16` field can
24316        // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
24317        // is the singleton `{0}`). A future refactor that drifts the
24318        // gate off the lifted const (silently re-introducing an
24319        // inline `if e.port == 0` byte-check) surfaces here — the
24320        // pin cannot distinguish `< 1` from `== 0` on the current
24321        // floor, but it *does* pin that the diagnostic fires on `0`
24322        // through whichever gate is wired, so any future accept-set
24323        // floor migration (a hypothetical unprivileged-only
24324        // migration lifting `SERVICO_PORT_MIN` to `1024`) must
24325        // update this test alongside the const declaration —
24326        // structurally guaranteeing the gate + accept-set + pin
24327        // trio move together. Peer with the
24328        // [`rejects_zero_entrada_port`] behavioral pin on the same
24329        // per-`:entrada :port` axis — that pin asserts the pre-lift
24330        // behavioral contract (`port: 0` → `EntradaPortZero`); this
24331        // pin adds the structural link to the lifted floor const.
24332        assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
24333        let mut s = three_member_spec();
24334        s.entrada.as_mut().unwrap().port = 0;
24335        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
24336    }
24337
24338    // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
24339
24340    #[test]
24341    fn membro_serde_keys_match_lifted_membro_key_consts() {
24342        // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
24343        // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
24344        // name the exact camelCase JSON keys the
24345        // `#[serde(rename_all = "camelCase")]` attribute on
24346        // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
24347        // that each canonical byte-sequence appears verbatim in the
24348        // JSON — a future accidental `rename_all = "snake_case"` /
24349        // `"kebab-case"` / verbatim-field-name flip at the derive
24350        // attribute (any of which would silently break every downstream
24351        // JSON consumer that reaches for one of the two consts via
24352        // `Value::get(...)`) surfaces here as a build-time test failure
24353        // at `aplicacao.rs`, not as an apply-time
24354        // `.get(<stale-canonical-const>)` returning `None` far from the
24355        // derive-attr drift's commit. Peer with the sibling
24356        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
24357        // (40cc4e5) pin on the M2 supervision-tree top-level axis —
24358        // same discipline the SupervisorSpec top-level lift established,
24359        // extended here to the M3 [`Membro`] per-`:membros` axis.
24360        let m = Membro {
24361            caixa: "catalog".into(),
24362            versao: "^0.1".into(),
24363        };
24364        let json = serde_json::to_string(&m).unwrap();
24365        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
24366            let quoted = format!("\"{key}\"");
24367            assert!(
24368                json.contains(&quoted),
24369                "serialized Membro must carry the lifted MEMBRO_KEY_* \
24370                 byte-sequence {quoted} verbatim in the JSON emission \
24371                 (got: {json})",
24372            );
24373        }
24374    }
24375
24376    #[test]
24377    fn membro_key_consts_are_pairwise_distinct() {
24378        // Cross-axis drift-detection pin: a future collapse of the two
24379        // canonical [`Membro`] per-entry byte-strings onto the same
24380        // value (e.g. an accidental copy-paste flip of
24381        // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
24382        // silently reroute every downstream probe on one axis onto the
24383        // sibling axis's overlay entry and pass every propagation-probe
24384        // test that expected only the stale axis's value. Peer of the
24385        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
24386        // (40cc4e5).
24387        let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
24388        for (i, a) in all.iter().enumerate() {
24389            for b in all.iter().skip(i + 1) {
24390                assert_ne!(
24391                    a, b,
24392                    "MEMBRO_KEY_* consts must be pairwise-distinct \
24393                     canonical byte-sequences — got `{a}` == `{b}`",
24394                );
24395            }
24396        }
24397    }
24398
24399    // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
24400    //    URL-path fallback resolver every HTTPRoute-aware renderer
24401    //    reaching for a per-rule path-list resolution routes through.
24402    //    The four pin tests below fix the four-way accept-set the
24403    //    resolver must always honor: (:paths-non-empty-verbatim,
24404    //    :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
24405    //    :paths-preserves-order-across-multiple-entries) — drift on any
24406    //    arm surfaces at caixa-core build time rather than at cluster-
24407    //    apply time. Peer discipline with `MeshPolicy::is_empty` on the
24408    //    sibling `:politicas` typed-primitive dispatch axis.
24409
24410    fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
24411        Entrada {
24412            host: "example.com".into(),
24413            para: "cart".into(),
24414            paths: paths.into_iter().map(String::from).collect(),
24415            port: DEFAULT_SERVICO_PORT,
24416        }
24417    }
24418
24419    #[test]
24420    fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
24421        // The typed `:entrada :paths` slot carries an author-declared
24422        // list — the resolver returns each entry verbatim, no
24423        // catch-all substitution. The canonical "author declared
24424        // paths, honor them verbatim" arm of the path-list dispatch.
24425        let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
24426        assert_eq!(
24427            e.resolved_paths(),
24428            vec!["/api/cart", "/api/products"],
24429            "resolved_paths must return each `:entrada :paths` entry \
24430             verbatim when the typed slot is non-empty (got {:?})",
24431            e.resolved_paths(),
24432        );
24433    }
24434
24435    #[test]
24436    fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
24437        // Empty `:entrada :paths` slot — the resolver substitutes the
24438        // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
24439        // catch-all fallback verbatim. Pins the empty-arm of the
24440        // resolver's four-way accept-set against a future silent
24441        // detour that returned an empty Vec (which would emit an
24442        // HTTPRoute with zero rules — silently dropping every
24443        // external `:entrada` flow at admission time), routed to a
24444        // different fallback shape, or dropped the catch-all
24445        // altogether.
24446        let e = entrada_with_paths(vec![]);
24447        assert_eq!(
24448            e.resolved_paths(),
24449            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
24450            "resolved_paths on empty `:entrada :paths` must fall back \
24451             to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
24452             all — got {:?}",
24453            e.resolved_paths(),
24454        );
24455    }
24456
24457    #[test]
24458    fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
24459        // Single-entry `:entrada :paths` — the resolver returns the
24460        // single declared path verbatim, NOT the catch-all fallback
24461        // (author declared a path, honor it — the empty-arm and the
24462        // len-1 arm are semantically distinct axes of the resolver's
24463        // accept-set). Pins that the resolver treats "author declared
24464        // one path" as authored input, not as the empty case.
24465        let e = entrada_with_paths(vec!["/api/only"]);
24466        assert_eq!(
24467            e.resolved_paths(),
24468            vec!["/api/only"],
24469            "resolved_paths on single-entry `:entrada :paths` must \
24470             return the declared path verbatim, NOT the catch-all \
24471             fallback (got {:?})",
24472            e.resolved_paths(),
24473        );
24474    }
24475
24476    #[test]
24477    fn resolved_paths_preserves_author_declared_order() {
24478        // The `:entrada :paths` list is author-ordered — the resolver
24479        // preserves the author's declaration order verbatim, since
24480        // per-rule dispatch order at the K8s Gateway API HTTPRoute
24481        // consumer is significant (first-match-wins under the
24482        // path-prefix matcher). Pins against a future silent
24483        // re-sort / dedup / normalize detour that reordered author
24484        // input.
24485        let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
24486        assert_eq!(
24487            e.resolved_paths(),
24488            vec!["/z/last", "/a/first", "/m/mid"],
24489            "resolved_paths must preserve author-declared `:entrada \
24490             :paths` order verbatim — got {:?}",
24491            e.resolved_paths(),
24492        );
24493    }
24494
24495    // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
24496    //    slot `&[String]` slice accessor every per-`:entrada` consumer
24497    //    that must see the author's declaration verbatim (not the
24498    //    fallback-applied projection the sibling `resolved_paths`
24499    //    returns) routes through. The three pin tests below fix the
24500    //    accept-set the accessor must honor: (:non-empty-byte-equal,
24501    //    :empty-projects-empty-slice, :preserves-author-declared-order)
24502    //    — drift on any arm surfaces at caixa-core build time rather
24503    //    than at cluster-apply time. Peer discipline with the sibling
24504    //    [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
24505    //    peer M3 mesh-slot `Vec<String>`-carry axis.
24506
24507    #[test]
24508    fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
24509        // Byte-equal pin: [`Entrada::paths`] must project the raw
24510        // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
24511        // slice borrowed from the typed slot's own [`Vec<String>`]
24512        // storage — no re-ordering, no dedup, no per-entry normalization,
24513        // no fallback substitution (the fallback-applying projection is
24514        // the sibling [`Entrada::resolved_paths`] resolver). Pins against
24515        // a future silent detour that re-normalized the list, dropped
24516        // duplicates the [`AplicacaoSpec::validate`]
24517        // `EntradaPathDuplicate` refusal already rejects at build time,
24518        // or (most severe) accidentally routed through the fallback-
24519        // applying sibling and returned the substrate catch-all when
24520        // the author declared an empty list — collapsing the raw-slot
24521        // and fallback-applied axes into one and breaking the
24522        // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
24523        //
24524        // Peer of the sibling
24525        // [`Placement::clusters`]-shape byte-equal pin
24526        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
24527        // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
24528        let fixtures: Vec<Vec<String>> = vec![
24529            Vec::new(),
24530            vec!["/api/cart".into()],
24531            vec!["/api/cart".into(), "/api/products".into()],
24532            vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
24533        ];
24534        for paths in fixtures {
24535            let e = Entrada {
24536                host: "example.com".into(),
24537                para: "cart".into(),
24538                paths: paths.clone(),
24539                port: DEFAULT_SERVICO_PORT,
24540            };
24541            assert_eq!(
24542                e.paths(),
24543                paths.as_slice(),
24544                "Entrada::paths must return :entrada :paths verbatim \
24545                 (got {:?}, expected {:?})",
24546                e.paths(),
24547                paths.as_slice(),
24548            );
24549            assert_eq!(
24550                e.paths(),
24551                e.paths.as_slice(),
24552                "Entrada::paths accessor and .paths.as_slice() field \
24553                 access must byte-equal — the accessor is the substrate-\
24554                 primitive typed dispatch every downstream per-`:entrada` \
24555                 raw-slot path-list consumer must route through",
24556            );
24557            assert_eq!(
24558                e.paths().len(),
24559                e.paths.len(),
24560                "Entrada::paths().len() must byte-equal self.paths.len() \
24561                 — a length drift would silently split the paired \
24562                 pre-flight cascade-head `.is_empty()` probe input in \
24563                 the sibling [`Entrada::resolved_paths`] resolver from \
24564                 the per-entry validate loop's traversal input in \
24565                 [`AplicacaoSpec::validate`]",
24566            );
24567        }
24568    }
24569
24570    #[test]
24571    fn resolved_paths_reads_through_lifted_paths_accessor() {
24572        // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
24573        // pre-flight `.paths().is_empty()` cascade-head probe (which
24574        // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
24575        // catch-all fallback arm when the accessor projects the empty
24576        // slice) and the per-entry `.paths().iter().map(String::as_str)`
24577        // projection (which must reach every entry in the same order
24578        // the accessor projects, so the sibling
24579        // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
24580        // per-entry projection stay in lockstep by construction) must
24581        // both key off the lifted accessor. Pins the two-site coherence
24582        // by exercising each production consumer end-to-end: (1) the
24583        // catch-all-fallback arm under the empty slice, (2) the
24584        // author-declared-verbatim arm under a two-entry cohort whose
24585        // per-entry projection must byte-equal the input's per-entry
24586        // author-declared paths in the author's declared order.
24587        //
24588        // Peer of the sibling M3
24589        // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
24590        // `validate_placement_reads_through_lifted_clusters_accessor`
24591        // on the sibling `Placement::clusters` reader-site convergence.
24592        let empty = entrada_with_paths(vec![]);
24593        assert_eq!(
24594            empty.resolved_paths(),
24595            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
24596            "resolved_paths on empty :entrada :paths must trip the \
24597             lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
24598             catch-all fallback — routing through the lifted paths() \
24599             accessor must not silently drop the fallback arm",
24600        );
24601
24602        let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
24603        assert_eq!(
24604            declared.resolved_paths(),
24605            vec!["/api/cart", "/api/products"],
24606            "resolved_paths on non-empty :entrada :paths must return each \
24607             entry verbatim in the author's declared order — routing \
24608             through the lifted paths() accessor must not silently \
24609             reorder or drop entries",
24610        );
24611        // Byte-equal pin against the raw-slot accessor to keep the
24612        // fallback-applying resolver's per-entry projection input in
24613        // lockstep with the raw-slot accessor's projection.
24614        let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
24615        assert_eq!(
24616            declared.resolved_paths(),
24617            raw_projected,
24618            "resolved_paths non-empty projection must byte-equal the \
24619             lifted paths() accessor's per-entry String::as_str projection \
24620             — the two projections share the same input slice by \
24621             construction, so any drift here would surface a silent \
24622             re-ordering / dedup / normalization detour in the resolver",
24623        );
24624    }
24625
24626    #[test]
24627    fn validate_reads_through_lifted_entrada_paths_accessor() {
24628        // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
24629        // per-entry value-shape gate's `for p in e.paths()` traversal
24630        // (which must reach every entry in the same order the accessor
24631        // projects, so both the per-entry `EntradaPathEmpty` /
24632        // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
24633        // the duplicate-detection HashSet insert that trips
24634        // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
24635        // projection) must route through the lifted accessor. Pins the
24636        // coherence by exercising each production consumer end-to-end:
24637        // (1) the `EntradaPathEmpty` refusal fires on the second entry
24638        // of a two-entry cohort whose head is valid but tail is empty
24639        // (which requires the loop to reach the second entry through
24640        // the accessor), and (2) the `EntradaPathDuplicate` refusal
24641        // fires on the second entry of a two-entry cohort that shares
24642        // a path (which requires the loop to reach both entries — a
24643        // first-entry-only projection would silently pass since the
24644        // dedup HashSet has room for the first insert).
24645        //
24646        // Peer of the sibling
24647        // `validate_placement_reads_through_lifted_clusters_accessor`
24648        // on the sibling `Placement::clusters` reader-site convergence.
24649        let base = crate::AplicacaoSpec {
24650            membros: vec![crate::Membro {
24651                caixa: "cart".into(),
24652                versao: "^0.1".into(),
24653            }],
24654            contratos: Vec::new(),
24655            politicas: crate::MeshPolicy::default(),
24656            placement: crate::Placement {
24657                estrategia: crate::PlacementStrategy::SingleNode,
24658                clusters: vec!["rio".into()],
24659                shard_key: None,
24660                affinity: None,
24661            },
24662            entrada: Some(Entrada {
24663                host: "example.com".into(),
24664                para: "cart".into(),
24665                paths: vec!["/api/cart".into(), String::new()],
24666                port: DEFAULT_SERVICO_PORT,
24667            }),
24668        };
24669        assert_eq!(
24670            base.validate(),
24671            Err(crate::AplicacaoError::EntradaPathEmpty),
24672            "validate must trip EntradaPathEmpty on the second entry of \
24673             a two-entry cohort — routing through the lifted paths() \
24674             accessor must not silently short-circuit the loop at the \
24675             valid head entry",
24676        );
24677
24678        let mut dup = base;
24679        dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
24680        assert_eq!(
24681            dup.validate(),
24682            Err(crate::AplicacaoError::EntradaPathDuplicate {
24683                path: "/api/cart".into(),
24684            }),
24685            "validate must trip EntradaPathDuplicate on the second entry \
24686             of a two-entry cohort that shares a path — routing through \
24687             the lifted paths() accessor must not silently short-circuit \
24688             the dedup HashSet insert at the first entry",
24689        );
24690    }
24691
24692    // ── Entrada::hostname / Entrada::hostnames — the substrate-
24693    //    canonical per-`:entrada` DNS-hostname resolver pair every
24694    //    Gateway-API-aware renderer reaching for a per-listener
24695    //    singular `hostname:` filter (Gateway) or a per-route plural
24696    //    `spec.hostnames[]` filter list (HTTPRoute) routes through.
24697    //    The three pin tests below fix the two-way accept-set the pair
24698    //    must always honor: (:singular-byte-equal-to-host,
24699    //    :plural-is-singleton-of-singular, :plural-len-is-one) — drift
24700    //    on any arm surfaces at caixa-core build time rather than at
24701    //    cluster-apply time when the API server refuses the HTTPRoute
24702    //    for non-intersecting hostname filters. Peer discipline with
24703    //    the sibling `resolved_paths` accept-set pin block above on the
24704    //    per-`:entrada` path-list resolver axis.
24705
24706    fn entrada_with_host(host: &str) -> Entrada {
24707        Entrada {
24708            host: host.into(),
24709            para: "cart".into(),
24710            paths: Vec::new(),
24711            port: DEFAULT_SERVICO_PORT,
24712        }
24713    }
24714
24715    #[test]
24716    fn hostname_returns_entrada_host_byte_equal() {
24717        // The canonical singular-axis pin: [`Entrada::hostname`] must
24718        // return the `:entrada :host` field byte-for-byte, borrowed
24719        // from the typed slot's own [`String`] storage. Pins against a
24720        // future silent detour that re-normalized the host (an
24721        // accidental `.to_lowercase()` — validate_entrada_host already
24722        // enforces lowercase, so any re-normalization is redundant + a
24723        // drift surface between the validator and the accessor), a
24724        // trailing-`.` fully-qualified DNS shape substitution, or a
24725        // Punycode round-trip that lowered a Unicode host through IDNA.
24726        let e = entrada_with_host("checkout.quero.cloud");
24727        assert_eq!(
24728            e.hostname(),
24729            "checkout.quero.cloud",
24730            "Entrada::hostname must return :entrada :host verbatim \
24731             (got {:?})",
24732            e.hostname(),
24733        );
24734        assert_eq!(
24735            e.hostname(),
24736            e.host.as_str(),
24737            "Entrada::hostname must byte-equal the .host field access",
24738        );
24739    }
24740
24741    #[test]
24742    fn hostnames_returns_singleton_of_hostname_accessor() {
24743        // The pair-invariant pin: [`Entrada::hostnames`] must always
24744        // return exactly `vec![hostname()]` — the singleton list whose
24745        // sole entry is the substrate's canonical per-`:entrada`
24746        // singular hostname. Pins the two-consumer coherence axis: the
24747        // Gateway listener's singular `hostname:` filter and the
24748        // HTTPRoute's plural `spec.hostnames[]` filter list must
24749        // agree, else the Gateway API v1.x conformance layer rejects
24750        // the HTTPRoute at attach time with
24751        // `Accepted:False/NoMatchingParent` (the parent Gateway's
24752        // listener hostname doesn't intersect the route's hostname
24753        // filter list) — a divergence whose apply-time symptom is far
24754        // from any single-site commit and never surfaces in the
24755        // emitted YAML. Pinning the pair-invariant here makes any
24756        // future accidental split (an accidental `.to_string() + "."`
24757        // trailing-`.` on the plural side that didn't land on the
24758        // singular side, an accidental prefix stripping on one axis,
24759        // an accidental wildcard prepend the SNI fan-out overlay
24760        // authors on the plural side without a paired singular
24761        // migration) trip at caixa-core build time.
24762        let e = entrada_with_host("checkout.quero.cloud");
24763        assert_eq!(
24764            e.hostnames(),
24765            vec![e.hostname()],
24766            "Entrada::hostnames must return `vec![hostname()]` under \
24767             the pair-invariant — got {:?} vs. singleton {:?}",
24768            e.hostnames(),
24769            vec![e.hostname()],
24770        );
24771    }
24772
24773    #[test]
24774    fn hostnames_is_singleton_under_single_host_author_surface() {
24775        // The singleton-shape pin: under today's single-hostname-per-
24776        // `:entrada` author surface (the `:host` slot is a single
24777        // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
24778        // must always return a list of length exactly one. Pins
24779        // against a future silent detour that returned an empty list
24780        // (which would emit an HTTPRoute with `spec.hostnames: []` —
24781        // matching every incoming Host header regardless of the
24782        // Aplicacao's declared ingress apex, silently over-matching
24783        // every foreign VirtualHost the parent Gateway also fronts) or
24784        // a duplicated entry (which the Gateway API v1.x parser
24785        // accepts as a `[]-length-2 list of equal hostnames]` but
24786        // whose semantics differ from the intended singleton). The
24787        // author-surface extension point ("a future `:entrada
24788        // :alt-hosts` list overlay" the docstring names) is the sole
24789        // future axis that flips this pin — that migration will re-
24790        // author this test to pin the new plural cardinality.
24791        let e = entrada_with_host("checkout.quero.cloud");
24792        assert_eq!(
24793            e.hostnames().len(),
24794            1,
24795            "Entrada::hostnames must be a singleton under today's \
24796             single-hostname-per-`:entrada` author surface — got \
24797             length {}: {:?}",
24798            e.hostnames().len(),
24799            e.hostnames(),
24800        );
24801    }
24802
24803    // ── Entrada::destination — the substrate-canonical per-`:entrada`
24804    //    destination-Servico scalar accessor every Gateway-API
24805    //    HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
24806    //    discriminator arg (HTTPRoute name composer) or a per-rule
24807    //    `backendRefs[0].name` axis routes through. The two pin tests
24808    //    below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
24809    //    either arm surfaces at caixa-core build time rather than at
24810    //    cluster-apply time when an HTTPRoute's `metadata.name` and
24811    //    `backendRefs[]` silently disagree on which destination Servico
24812    //    the ingress fronts. Peer discipline with the sibling
24813    //    `resolved_paths` + `hostname` + `hostnames` accept-set pin
24814    //    blocks above on the per-`:entrada` path-list / DNS-hostname
24815    //    resolver axes.
24816
24817    #[test]
24818    fn destination_returns_entrada_para_byte_equal() {
24819        // The canonical destination-scalar pin: [`Entrada::destination`]
24820        // must return the `:entrada :para` field byte-for-byte, borrowed
24821        // from the typed slot's own [`String`] storage. Pins against a
24822        // future silent detour that re-normalized the destination (an
24823        // accidental `.to_lowercase()` — the destination Servico is
24824        // already validated as a DNS-1123 label upstream, so any
24825        // re-normalization is redundant + a drift surface between the
24826        // validator and the accessor), a namespace-prefix rewrite (an
24827        // accidental `format!("{namespace}/{para}")` per-CR fully-
24828        // qualified rewrite that didn't land on the peer axis), or a
24829        // per-cluster suffix stamp the operator authors on one
24830        // consumer without the other.
24831        for para in ["cart", "checkout", "catalog", "orders-v2"] {
24832            let e = Entrada {
24833                host: "checkout.quero.cloud".into(),
24834                para: para.into(),
24835                paths: Vec::new(),
24836                port: DEFAULT_SERVICO_PORT,
24837            };
24838            assert_eq!(
24839                e.destination(),
24840                para,
24841                "Entrada::destination must return :entrada :para verbatim \
24842                 (got {:?}, expected {para:?})",
24843                e.destination(),
24844            );
24845            assert_eq!(
24846                e.destination(),
24847                e.para.as_str(),
24848                "Entrada::destination must byte-equal the .para field access",
24849            );
24850        }
24851    }
24852
24853    #[test]
24854    fn destination_borrows_from_entrada_para_storage() {
24855        // The borrow-not-copy pin: [`Entrada::destination`] must
24856        // return a `&str` slice that borrows from the typed slot's
24857        // own [`String`] storage — same-address invariant with
24858        // `entrada.para.as_str()`. Pins against a future silent detour
24859        // that allocated a fresh `String` (`self.para.clone()` in the
24860        // body would type-check but silently drop the borrow, and
24861        // every downstream consumer that assumed the returned slice
24862        // outlives `&self` would break on a stale-reference use-after-
24863        // free). Peer with the sibling `hostname_returns_entrada_
24864        // host_byte_equal` on the singular-DNS-hostname axis.
24865        let e = entrada_with_host("checkout.quero.cloud");
24866        let dest = e.destination();
24867        let para_slice = e.para.as_str();
24868        assert_eq!(
24869            dest.as_ptr(),
24870            para_slice.as_ptr(),
24871            "Entrada::destination must borrow from the .para String's \
24872             backing storage — a fresh allocation here means the \
24873             accessor no longer names the substrate-primitive typed \
24874             dispatch and every downstream consumer would silently \
24875             carry a detached copy",
24876        );
24877        assert_eq!(
24878            dest.len(),
24879            para_slice.len(),
24880            "Entrada::destination and .para.as_str() must byte-equal in \
24881             length as well as in address",
24882        );
24883    }
24884
24885    #[test]
24886    fn port_returns_entrada_port_verbatim_across_permutations() {
24887        // The canonical L4-port-scalar pin: [`Entrada::port`] must
24888        // return the `:entrada :port` field verbatim as a `u16` across
24889        // every author-declared value in the validated accept-set
24890        // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
24891        // silent detour that clamped the port (an accidental
24892        // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
24893        // land on the peer [`AplicacaoSpec::port_for_destination`]
24894        // resolver), rewrote it through a per-cluster port-remap table
24895        // the operator authors on one consumer without the other, or
24896        // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
24897        // serde-default value (which would silently collapse the
24898        // distinction between "author explicitly declared `:port 8080`"
24899        // and "author omitted the slot and inherited the default" the
24900        // future per-cluster override slot depends on). Peer with the
24901        // sibling `destination_returns_entrada_para_byte_equal` +
24902        // `hostname_returns_entrada_host_byte_equal` pins on the
24903        // per-`:entrada` `&str` scalar axes.
24904        for port in [
24905            SERVICO_PORT_MIN,
24906            DEFAULT_SERVICO_PORT,
24907            8443u16,
24908            9090u16,
24909            u16::MAX,
24910        ] {
24911            let e = Entrada {
24912                host: "checkout.quero.cloud".into(),
24913                para: "cart".into(),
24914                paths: Vec::new(),
24915                port,
24916            };
24917            assert_eq!(
24918                e.port(),
24919                port,
24920                "Entrada::port must return :entrada :port verbatim \
24921                 (got {}, expected {port})",
24922                e.port(),
24923            );
24924            assert_eq!(
24925                e.port(),
24926                e.port,
24927                "Entrada::port accessor and .port field access must \
24928                 byte-equal — the accessor is the substrate-primitive \
24929                 typed dispatch every downstream L4-port consumer must \
24930                 route through",
24931            );
24932        }
24933    }
24934
24935    #[test]
24936    fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
24937        // Two-consumer coherence pin: the
24938        // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
24939        // (which reads through [`Entrada::port`] to compare against
24940        // [`SERVICO_PORT_MIN`]) and the
24941        // [`AplicacaoSpec::port_for_destination`] resolver (which reads
24942        // through [`Entrada::port`] to emit the per-destination
24943        // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
24944        // lifted accessor, so any future rebrand on the typed slot's
24945        // reader shape lands at exactly one place. Pins the two-site
24946        // coherence by exercising a below-floor port through validate
24947        // (which must reject) and a validated in-accept-set port through
24948        // port_for_destination (which must emit the same value the
24949        // accessor returns).
24950        let mut spec = three_member_spec();
24951        if let Some(e) = spec.entrada.as_mut() {
24952            e.port = 0;
24953        }
24954        assert_eq!(
24955            spec.validate().unwrap_err(),
24956            AplicacaoError::EntradaPortZero,
24957            "validate must reject `:entrada :port 0` through the lifted \
24958             Entrada::port accessor — port zero lies below \
24959             SERVICO_PORT_MIN and the validator routes through port() \
24960             to name the floor",
24961        );
24962
24963        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
24964            let mut spec = three_member_spec();
24965            if let Some(e) = spec.entrada.as_mut() {
24966                e.port = port;
24967            }
24968            spec.validate().expect(
24969                "entrada with in-accept-set :port must validate — the \
24970                 structural-floor gate reads through Entrada::port",
24971            );
24972            let entrada_ref = spec.entrada().expect(":entrada present");
24973            assert_eq!(
24974                spec.port_for_destination(entrada_ref.destination()),
24975                entrada_ref.port(),
24976                "port_for_destination(entrada.destination()) must equal \
24977                 entrada.port() — the two consumers of the per-:entrada \
24978                 L4-port axis (validator, per-destination resolver) both \
24979                 route through Entrada::port",
24980            );
24981        }
24982    }
24983
24984    #[test]
24985    fn wit_contract_source_returns_de_byte_equal_across_permutations() {
24986        // The canonical caller-Servico-scalar pin: [`WitContract::source`]
24987        // must return the `:contratos :de` field byte-for-byte, borrowed
24988        // from the typed slot's own [`String`] storage. Peer of the
24989        // sibling `destination_returns_entrada_para_byte_equal` pin on
24990        // the per-`:entrada` axis — same "the substrate-primitive
24991        // accessor must byte-equal the raw field access verbatim across
24992        // every author-declared value" discipline extended to the
24993        // per-`:contratos` caller arm. Pins against a future silent
24994        // detour that re-normalized the caller (an accidental
24995        // `.to_lowercase()` — every `:contratos :de` is validated as a
24996        // DNS-1123 label upstream via `validate_contrato_caixa`, so any
24997        // re-normalization is redundant + a drift surface between the
24998        // validator and the accessor), a namespace-prefix rewrite (an
24999        // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
25000        // rewrite that didn't land on the peer axis), or a per-cluster
25001        // suffix stamp the operator authors on one consumer without the
25002        // other.
25003        for de in ["cart", "checkout", "catalog", "orders-v2"] {
25004            let c = WitContract {
25005                de: de.into(),
25006                para: "downstream".into(),
25007                wit: "wasi:http/proxy".into(),
25008                endpoint: Some("/lookup".into()),
25009                subject: None,
25010                slot: None,
25011            };
25012            assert_eq!(
25013                c.source(),
25014                de,
25015                "WitContract::source must return :contratos :de verbatim \
25016                 (got {:?}, expected {de:?})",
25017                c.source(),
25018            );
25019            assert_eq!(
25020                c.source(),
25021                c.de.as_str(),
25022                "WitContract::source must byte-equal the .de field access",
25023            );
25024        }
25025    }
25026
25027    #[test]
25028    fn wit_contract_source_borrows_from_de_storage() {
25029        // The borrow-not-copy pin: [`WitContract::source`] must return a
25030        // `&str` slice that borrows from the typed slot's own [`String`]
25031        // storage — same-address invariant with `c.de.as_str()`. Pins
25032        // against a future silent detour that allocated a fresh `String`
25033        // (`self.de.clone()` in the body would type-check but silently
25034        // drop the borrow, and every downstream consumer that assumed
25035        // the returned slice outlives `&self` would break on a stale-
25036        // reference use-after-free). Peer of the sibling
25037        // `destination_borrows_from_entrada_para_storage` on the
25038        // per-`:entrada` axis.
25039        let c = WitContract {
25040            de: "cart".into(),
25041            para: "catalog".into(),
25042            wit: "wasi:http/proxy".into(),
25043            endpoint: Some("/lookup".into()),
25044            subject: None,
25045            slot: None,
25046        };
25047        let src = c.source();
25048        let de_slice = c.de.as_str();
25049        assert_eq!(
25050            src.as_ptr(),
25051            de_slice.as_ptr(),
25052            "WitContract::source must borrow from the .de String's \
25053             backing storage — a fresh allocation here means the \
25054             accessor no longer names the substrate-primitive typed \
25055             dispatch and every downstream consumer would silently \
25056             carry a detached copy",
25057        );
25058        assert_eq!(
25059            src.len(),
25060            de_slice.len(),
25061            "WitContract::source and .de.as_str() must byte-equal in \
25062             length as well as in address",
25063        );
25064    }
25065
25066    #[test]
25067    fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
25068        // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
25069        // must return the `:contratos :para` field byte-for-byte,
25070        // borrowed from the typed slot's own [`String`] storage. Peer of
25071        // the sibling `destination_returns_entrada_para_byte_equal` on
25072        // the per-`:entrada` axis — both accessors name "the destination-
25073        // Servico byte-string" concept on their respective mesh-slot
25074        // atoms (per-ingress apex vs. per-typed-edge callee) and both
25075        // must project the underlying `.para` field verbatim so every
25076        // downstream renderer that composes them with peer accessors
25077        // (e.g. `spec.port_for_destination(c.destination())` at the CNP
25078        // per-edge L4 port emit site) reads the same byte-string the
25079        // author declared.
25080        for para in ["catalog", "payment", "orders", "inventory-v3"] {
25081            let c = WitContract {
25082                de: "cart".into(),
25083                para: para.into(),
25084                wit: "wasi:http/proxy".into(),
25085                endpoint: Some("/lookup".into()),
25086                subject: None,
25087                slot: None,
25088            };
25089            assert_eq!(
25090                c.destination(),
25091                para,
25092                "WitContract::destination must return :contratos :para \
25093                 verbatim (got {:?}, expected {para:?})",
25094                c.destination(),
25095            );
25096            assert_eq!(
25097                c.destination(),
25098                c.para.as_str(),
25099                "WitContract::destination must byte-equal the .para \
25100                 field access",
25101            );
25102        }
25103    }
25104
25105    #[test]
25106    fn wit_contract_destination_borrows_from_para_storage() {
25107        // The borrow-not-copy pin: [`WitContract::destination`] must
25108        // return a `&str` slice that borrows from the typed slot's own
25109        // [`String`] storage — same-address invariant with
25110        // `c.para.as_str()`. Peer of the sibling
25111        // `destination_borrows_from_entrada_para_storage` on the
25112        // per-`:entrada` axis.
25113        let c = WitContract {
25114            de: "cart".into(),
25115            para: "catalog".into(),
25116            wit: "wasi:http/proxy".into(),
25117            endpoint: Some("/lookup".into()),
25118            subject: None,
25119            slot: None,
25120        };
25121        let dest = c.destination();
25122        let para_slice = c.para.as_str();
25123        assert_eq!(
25124            dest.as_ptr(),
25125            para_slice.as_ptr(),
25126            "WitContract::destination must borrow from the .para \
25127             String's backing storage — a fresh allocation here means \
25128             the accessor no longer names the substrate-primitive typed \
25129             dispatch and every downstream consumer would silently \
25130             carry a detached copy",
25131        );
25132        assert_eq!(
25133            dest.len(),
25134            para_slice.len(),
25135            "WitContract::destination and .para.as_str() must byte-equal \
25136             in length as well as in address",
25137        );
25138    }
25139
25140    #[test]
25141    fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
25142        // The canonical per-`:contratos` WIT-world-reference scalar pin:
25143        // [`WitContract::world_ref`] must return the `:contratos :wit`
25144        // field byte-for-byte, borrowed from the typed slot's own
25145        // [`String`] storage. Sibling of the peer per-`:contratos`
25146        // [`WitContract::source`] / [`WitContract::destination`]
25147        // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
25148        // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
25149        // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
25150        // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
25151        // "the substrate-primitive accessor must byte-equal the raw
25152        // field access verbatim across every author-declared value"
25153        // discipline extended to the per-`:contratos` WIT-world arm.
25154        // Pins against a future silent detour that re-canonicalized the
25155        // WIT world reference (an accidental `.to_lowercase()` pass that
25156        // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
25157        // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
25158        // gate is already lowercase-prefixed so any re-normalization is
25159        // redundant + a drift surface between the validator and the
25160        // accessor), an M4-promotion-shape rewrite that formatted a
25161        // typed WIT-world enum through [`Display`] and silently drifted
25162        // the printer output from the source `caixa.lisp`, or a per-
25163        // cluster WIT-alias rewrite that didn't land on the peer field-
25164        // access sites. Five values sweep the shape-dispatch accept-set
25165        // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
25166        // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
25167        // `wasi:keyvalue/`).
25168        for (wit, endpoint, subject, slot) in [
25169            ("wasi:http/proxy", Some("/lookup"), None, None),
25170            ("http:proxy", Some("/health"), None, None),
25171            ("nats:pub-sub", None, Some("orders.paid"), None),
25172            ("kafka:events", None, Some("checkout-events"), None),
25173            ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
25174        ] {
25175            let c = WitContract {
25176                de: "cart".into(),
25177                para: "downstream".into(),
25178                wit: wit.into(),
25179                endpoint: endpoint.map(str::to_string),
25180                subject: subject.map(str::to_string),
25181                slot: slot.map(str::to_string),
25182            };
25183            assert_eq!(
25184                c.world_ref(),
25185                wit,
25186                "WitContract::world_ref must return :contratos :wit \
25187                 verbatim (got {:?}, expected {wit:?})",
25188                c.world_ref(),
25189            );
25190            assert_eq!(
25191                c.world_ref(),
25192                c.wit.as_str(),
25193                "WitContract::world_ref must byte-equal the .wit field \
25194                 access",
25195            );
25196        }
25197    }
25198
25199    #[test]
25200    fn wit_contract_world_ref_borrows_from_wit_storage() {
25201        // The borrow-not-copy pin: [`WitContract::world_ref`] must
25202        // return a `&str` slice that borrows from the typed slot's own
25203        // [`String`] storage — same-address invariant with
25204        // `c.wit.as_str()`. Pins against a future silent detour that
25205        // allocated a fresh `String` (`self.wit.clone()` in the body
25206        // would type-check but silently drop the borrow, and every
25207        // downstream consumer that assumed the returned slice outlives
25208        // `&self` would break on a stale-reference use-after-free — the
25209        // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
25210        // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
25211        // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
25212        // / [`is_pubsub`][WitContract::is_pubsub] /
25213        // [`is_store`][WitContract::is_store] methods route through —
25214        // each borrow from the WitContract's own storage and each would
25215        // silently misbehave if this accessor produced a detached copy).
25216        // Peer of the sibling per-`:contratos` [`WitContract::source`] /
25217        // [`WitContract::destination`] and per-`:entrada`
25218        // [`Entrada::destination`] / [`Entrada::hostname`] and
25219        // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
25220        // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
25221        let c = WitContract {
25222            de: "cart".into(),
25223            para: "catalog".into(),
25224            wit: "wasi:http/proxy".into(),
25225            endpoint: Some("/lookup".into()),
25226            subject: None,
25227            slot: None,
25228        };
25229        let world = c.world_ref();
25230        let wit_slice = c.wit.as_str();
25231        assert_eq!(
25232            world.as_ptr(),
25233            wit_slice.as_ptr(),
25234            "WitContract::world_ref must borrow from the .wit String's \
25235             backing storage — a fresh allocation here means the \
25236             accessor no longer names the substrate-primitive typed \
25237             dispatch and every downstream consumer would silently carry \
25238             a detached copy",
25239        );
25240        assert_eq!(
25241            world.len(),
25242            wit_slice.len(),
25243            "WitContract::world_ref and .wit.as_str() must byte-equal in \
25244             length as well as in address",
25245        );
25246    }
25247
25248    #[test]
25249    fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
25250        // Sibling-triple invariant pin composing all three per-`:contratos`
25251        // substrate-primitive typed dispatches — [`WitContract::source`]
25252        // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
25253        // [`WitContract::world_ref`] — at the joint
25254        // `(source(), destination(), world_ref())` call shape every
25255        // renderer that fans on per-edge caller-callee-shape identity
25256        // keys off. The invariant, evaluated per-contract:
25257        //
25258        //   (c.source(), c.destination(), c.world_ref())
25259        //   == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
25260        //
25261        // Closes the last unlifted per-`:contratos` scalar axis — every
25262        // downstream consumer that reads the triple now routes through
25263        // exactly three typed dispatches on the substrate primitive,
25264        // not two typed + one open-coded field access. A future refactor
25265        // that silently split any one accessor's projection (an
25266        // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
25267        // canonicalization that didn't reach the peer `source`/
25268        // `destination` arms, an accidental `source()` per-cluster
25269        // caller-alias rewrite that didn't land on the `world_ref` peer)
25270        // surfaces at caixa-core build time. Peer of the sibling per-
25271        // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
25272        // per-`:entrada` `(hostname(), destination())` (6db982c /
25273        // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
25274        // axes, extended to the per-`:contratos` triple.
25275        for (de, para, wit, endpoint, subject, slot) in [
25276            (
25277                "cart",
25278                "catalog",
25279                "wasi:http/proxy",
25280                Some("/lookup"),
25281                None,
25282                None,
25283            ),
25284            (
25285                "checkout",
25286                "orders",
25287                "nats:pub-sub",
25288                None,
25289                Some("orders.paid"),
25290                None,
25291            ),
25292            (
25293                "cart",
25294                "kv",
25295                "wasi:keyvalue/store",
25296                None,
25297                None,
25298                Some("carts/{cart_id}"),
25299            ),
25300            (
25301                "orders-v2",
25302                "inventory-v3",
25303                "http:proxy",
25304                Some("/reserve"),
25305                None,
25306                None,
25307            ),
25308        ] {
25309            let c = WitContract {
25310                de: de.into(),
25311                para: para.into(),
25312                wit: wit.into(),
25313                endpoint: endpoint.map(str::to_string),
25314                subject: subject.map(str::to_string),
25315                slot: slot.map(str::to_string),
25316            };
25317            assert_eq!(
25318                (c.source(), c.destination(), c.world_ref()),
25319                (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
25320                "(WitContract::source, ::destination, ::world_ref) must \
25321                 project (.de, .para, .wit) verbatim across every author-\
25322                 declared triple (got ({:?}, {:?}, {:?}), expected \
25323                 ({de:?}, {para:?}, {wit:?}))",
25324                c.source(),
25325                c.destination(),
25326                c.world_ref(),
25327            );
25328        }
25329    }
25330
25331    #[test]
25332    fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
25333        // The canonical per-`:contratos` owned-form caller-callee-pair
25334        // pin: [`WitContract::edge_pair`] must return the
25335        // `(source(), destination())` tuple in owned form byte-for-byte,
25336        // projected through the lifted [`WitContract::source`] /
25337        // [`WitContract::destination`] scalar accessors. Pins the
25338        // composite-projection invariant on the per-`:contratos`
25339        // mesh-slot atom — every author-declared `(de, para)` pair must
25340        // round-trip verbatim through the substrate primitive's typed
25341        // dispatch, so the nine [`AplicacaoError`] diagnostic-
25342        // construction sites the accessor now feeds
25343        // ([`AplicacaoError::EmptyWit`],
25344        // [`AplicacaoError::ContratoEndpointEmpty`],
25345        // [`AplicacaoError::ContratoEndpointNotAbsolute`],
25346        // [`AplicacaoError::ContratoEndpointInvalid`],
25347        // [`AplicacaoError::ContratoSubjectEmpty`],
25348        // [`AplicacaoError::ContratoSubjectInvalid`],
25349        // [`AplicacaoError::ContratoSlotEmpty`],
25350        // [`AplicacaoError::ContratoSlotInvalid`],
25351        // [`AplicacaoError::ContratoDuplicate`]) all read the same
25352        // `(de, para)` label pair every author sees at the source
25353        // `caixa.lisp`. Pins against a future silent detour that swapped
25354        // the `.0` / `.1` arms (an accidental `(destination(),
25355        // source())` re-order in the body would silently invert every
25356        // downstream diagnostic's `de:` / `para:` label pair, silently
25357        // reversing the direction of every operator-facing typed error
25358        // arrow), a fresh-allocation shape drift (an accidental
25359        // `.to_string()` on one arm but not the other would leave the
25360        // owned/borrowed pair mismatched vs. the sibling `source()` /
25361        // `destination()` returns), or an M4 per-cluster caller/callee-
25362        // alias rewrite that landed on `source()` without reaching
25363        // `destination()` (or vice versa). Peer of the sibling per-
25364        // `:contratos` `(source, destination, world_ref)` triple
25365        // pin above on the mesh-slot-atom scalar-value axes, extended
25366        // to the owned-form pair-projection axis.
25367        for (de, para, wit, endpoint, subject, slot) in [
25368            (
25369                "cart",
25370                "catalog",
25371                "wasi:http/proxy",
25372                Some("/lookup"),
25373                None,
25374                None,
25375            ),
25376            (
25377                "checkout",
25378                "orders",
25379                "nats:pub-sub",
25380                None,
25381                Some("orders.paid"),
25382                None,
25383            ),
25384            (
25385                "cart",
25386                "kv",
25387                "wasi:keyvalue/store",
25388                None,
25389                None,
25390                Some("carts/{cart_id}"),
25391            ),
25392            (
25393                "orders-v2",
25394                "inventory-v3",
25395                "http:proxy",
25396                Some("/reserve"),
25397                None,
25398                None,
25399            ),
25400        ] {
25401            let c = WitContract {
25402                de: de.into(),
25403                para: para.into(),
25404                wit: wit.into(),
25405                endpoint: endpoint.map(str::to_string),
25406                subject: subject.map(str::to_string),
25407                slot: slot.map(str::to_string),
25408            };
25409            assert_eq!(
25410                c.edge_pair(),
25411                (de.to_string(), para.to_string()),
25412                "WitContract::edge_pair must return (:contratos :de, \
25413                 :contratos :para) as an owned tuple verbatim (got {:?}, \
25414                 expected ({de:?}, {para:?}))",
25415                c.edge_pair(),
25416            );
25417        }
25418    }
25419
25420    #[test]
25421    fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
25422        // The composition pin: [`WitContract::edge_pair`] must return
25423        // exactly `(source().to_string(), destination().to_string())` —
25424        // the owned form of the sibling accessor pair — so any future
25425        // refactor that silently re-authored the caller-arm / callee-arm
25426        // projection to bypass the lifted scalar accessors (an accidental
25427        // `(self.de.clone(), self.para.clone())` regression back to the
25428        // raw field-access shape, an M4-typed-caller-enum `Display`
25429        // re-canonicalization on `source()` that didn't reach
25430        // `edge_pair()`, a per-cluster alias rewrite the operator lands
25431        // on `destination()` without reaching this composite projection)
25432        // trips at caixa-core build time. Pins the "typed dispatch
25433        // composes with typed dispatch, not with raw field access"
25434        // discipline every downstream diagnostic-construction site now
25435        // routes through — a `de:` / `para:` label pair whose
25436        // projection silently drifted off the substrate primitive's
25437        // scalar accessors would silently split the diagnostic's self-
25438        // locating signal from the source `caixa.lisp` author's view.
25439        // Peer of the sibling per-`:politicas` `is_empty` /
25440        // `validate_politicas` accessor-routing-pin family on the M3
25441        // mesh-slot family (18575, 18739, 18918, 19140, 19371).
25442        let c = WitContract {
25443            de: "cart".into(),
25444            para: "catalog".into(),
25445            wit: "wasi:http/proxy".into(),
25446            endpoint: Some("/lookup".into()),
25447            subject: None,
25448            slot: None,
25449        };
25450        assert_eq!(
25451            c.edge_pair(),
25452            (c.source().to_string(), c.destination().to_string()),
25453            "WitContract::edge_pair must compose exactly \
25454             (source().to_string(), destination().to_string()) — a \
25455             bypass of either sibling accessor here would silently \
25456             decouple the composite-projection axis from the \
25457             substrate-primitive scalar accessors every downstream \
25458             consumer routes through",
25459        );
25460    }
25461
25462    #[test]
25463    fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
25464     {
25465        // The canonical per-`:contratos` owned-form
25466        // caller-callee-world-ref-triple pin:
25467        // [`WitContract::edge_triple`] must return the
25468        // `(source(), destination(), world_ref())` tuple in owned form
25469        // byte-for-byte, projected through the lifted
25470        // [`WitContract::source`] / [`WitContract::destination`] /
25471        // [`WitContract::world_ref`] scalar accessors. Pins the
25472        // composite-projection invariant on the per-`:contratos`
25473        // mesh-slot atom — every author-declared `(de, para, wit)`
25474        // triple must round-trip verbatim through the substrate
25475        // primitive's typed dispatch, so the nine
25476        // [`AplicacaoError`] diagnostic-construction sites the
25477        // accessor now feeds (the [`WitTarget`]-dispatch's eight
25478        // wrong-target / missing-target / invalid-wit / capability-
25479        // with-payload arms in [`WitContract::target`], plus the
25480        // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
25481        // diagnostic constructor in [`AplicacaoSpec::validate`]) all
25482        // read the same `(de, para, wit)` triple every author sees at
25483        // the source `caixa.lisp`. Pins against a future silent
25484        // detour that swapped any two arms (an accidental `(destination(),
25485        // source(), world_ref())` re-order in the body would silently
25486        // invert every downstream diagnostic's `de:` / `para:` label
25487        // pair, silently reversing the direction of every operator-
25488        // facing typed error arrow), a fresh-allocation shape drift
25489        // (an accidental `.to_string()` skipped on one arm would leave
25490        // the owned/borrowed triple mismatched vs. the sibling
25491        // `source()` / `destination()` / `world_ref()` returns), or an
25492        // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
25493        // canonicalization pass that landed on one accessor without
25494        // reaching the peers. Peer of the sibling per-`:contratos`
25495        // caller-callee-pair
25496        // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
25497        // pin on the mesh-slot-atom composite-projection axis,
25498        // extended to the triple-projection axis.
25499        for (de, para, wit, endpoint, subject, slot) in [
25500            (
25501                "cart",
25502                "catalog",
25503                "wasi:http/proxy",
25504                Some("/lookup"),
25505                None,
25506                None,
25507            ),
25508            (
25509                "checkout",
25510                "orders",
25511                "nats:pub-sub",
25512                None,
25513                Some("orders.paid"),
25514                None,
25515            ),
25516            (
25517                "cart",
25518                "kv",
25519                "wasi:keyvalue/store",
25520                None,
25521                None,
25522                Some("carts/{cart_id}"),
25523            ),
25524            (
25525                "orders-v2",
25526                "inventory-v3",
25527                "http:proxy",
25528                Some("/reserve"),
25529                None,
25530                None,
25531            ),
25532        ] {
25533            let c = WitContract {
25534                de: de.into(),
25535                para: para.into(),
25536                wit: wit.into(),
25537                endpoint: endpoint.map(str::to_string),
25538                subject: subject.map(str::to_string),
25539                slot: slot.map(str::to_string),
25540            };
25541            assert_eq!(
25542                c.edge_triple(),
25543                (de.to_string(), para.to_string(), wit.to_string()),
25544                "WitContract::edge_triple must return (:contratos :de, \
25545                 :contratos :para, :contratos :wit) as an owned triple \
25546                 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
25547                c.edge_triple(),
25548            );
25549        }
25550    }
25551
25552    #[test]
25553    fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
25554        // The composition pin: [`WitContract::edge_triple`] must return
25555        // exactly `(source().to_string(), destination().to_string(),
25556        // world_ref().to_string())` — the owned form of the sibling
25557        // scalar-accessor triple — so any future refactor that silently
25558        // re-authored one arm's projection to bypass the lifted scalar
25559        // accessors (an accidental `(self.de.clone(), self.para.clone(),
25560        // self.wit.clone())` regression back to the raw field-access
25561        // shape the internal `edge` closure and the ContratoDuplicate
25562        // diagnostic both carried before this lift landed, an
25563        // M4-typed-caller-enum `Display` re-canonicalization on
25564        // `source()` that didn't reach `edge_triple()`, a per-cluster
25565        // alias rewrite the operator lands on `destination()` /
25566        // `world_ref()` without reaching this composite projection)
25567        // trips at caixa-core build time. Pins the "typed dispatch
25568        // composes with typed dispatch, not with raw field access"
25569        // discipline every downstream diagnostic-construction site now
25570        // routes through — a `de:` / `para:` / `wit:` triple whose
25571        // projection silently drifted off the substrate primitive's
25572        // scalar accessors would silently split the diagnostic's self-
25573        // locating signal from the source `caixa.lisp` author's view.
25574        // Peer of the sibling per-`:contratos` edge_pair composition-
25575        // pin above on the mesh-slot-atom composite-projection axis.
25576        let c = WitContract {
25577            de: "cart".into(),
25578            para: "catalog".into(),
25579            wit: "wasi:http/proxy".into(),
25580            endpoint: Some("/lookup".into()),
25581            subject: None,
25582            slot: None,
25583        };
25584        assert_eq!(
25585            c.edge_triple(),
25586            (
25587                c.source().to_string(),
25588                c.destination().to_string(),
25589                c.world_ref().to_string(),
25590            ),
25591            "WitContract::edge_triple must compose exactly \
25592             (source().to_string(), destination().to_string(), \
25593             world_ref().to_string()) — a bypass of any sibling accessor \
25594             here would silently decouple the composite-projection axis \
25595             from the substrate-primitive scalar accessors every \
25596             downstream consumer routes through",
25597        );
25598    }
25599
25600    #[test]
25601    fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
25602        // The canonical semantics-pin: [`WitContract::edge_triple`] must
25603        // project the full `(de, para, wit)` identity of a `:contratos`
25604        // edge — the sub-triple every triple-carrying
25605        // [`AplicacaoError::Contrato*`] diagnostic weaves into its
25606        // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
25607        // missing-target, capability-with-payload, invalid-wit, and the
25608        // duplicate-gate). Rejects a drift in shape (an accidental
25609        // silent detour that returned a `(de, para)` pair or added an
25610        // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
25611        // would trip here because the return type would no longer
25612        // pattern-match the eight `let (de, para, wit) = edge();`
25613        // destructures the [`WitContract::target`] dispatch feeds off
25614        // + the paired duplicate-gate `let (de, para, wit) =
25615        // c.edge_triple();` destructure in
25616        // [`AplicacaoSpec::validate`]). Peer of the sibling per-
25617        // `:contratos` caller-callee-pair pin above extended to the
25618        // triple projection surface: closes the "one composite
25619        // accessor per typed diagnostic-construction sub-tuple"
25620        // discipline on the per-`:contratos` mesh-slot-atom axis.
25621        let c = WitContract {
25622            de: "checkout".into(),
25623            para: "orders".into(),
25624            wit: "nats:pub-sub".into(),
25625            endpoint: None,
25626            subject: Some("orders.paid".into()),
25627            slot: None,
25628        };
25629        let (de, para, wit) = c.edge_triple();
25630        assert_eq!(de, "checkout");
25631        assert_eq!(para, "orders");
25632        assert_eq!(wit, "nats:pub-sub");
25633    }
25634
25635    #[test]
25636    fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
25637     {
25638        // The composition pin: [`WitContract::identity`] must return
25639        // exactly `(source(), destination(), world_ref(), endpoint(),
25640        // subject(), slot())` — the borrowed form of the six-scalar-
25641        // accessor identity axis. Any future refactor that silently
25642        // re-authored one arm's projection to bypass a scalar accessor
25643        // (a `self.de.as_str()` regression back to raw field access on
25644        // any of the three required arms, a `self.endpoint.as_deref()`
25645        // regression on any of the three optional arms, an M4 per-
25646        // cluster caller/callee-alias rewrite the operator lands on
25647        // `source()` / `destination()` without reaching this composite
25648        // projection) trips at caixa-core build time. Sweeps four
25649        // permutations of the WIT-shape × payload lattice — HTTP with
25650        // endpoint, pub-sub with subject, store with slot, payload-less
25651        // capability — so every payload arm is exercised. Peer of the
25652        // sibling per-`:contratos`
25653        // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
25654        // composition pin on the mesh-slot-atom composite-projection
25655        // axis; extends the discipline from the (de, para, wit) prefix
25656        // onto the full-identity axis carrying the three payload arms.
25657        for (de, para, wit, endpoint, subject, slot) in [
25658            (
25659                "cart",
25660                "catalog",
25661                "wasi:http/proxy",
25662                Some("/lookup"),
25663                None,
25664                None,
25665            ),
25666            (
25667                "checkout",
25668                "orders",
25669                "nats:pub-sub",
25670                None,
25671                Some("orders.paid"),
25672                None,
25673            ),
25674            (
25675                "cart",
25676                "kv",
25677                "wasi:keyvalue/store",
25678                None,
25679                None,
25680                Some("carts/{cart_id}"),
25681            ),
25682            ("audit", "sink", "wasi:logging", None, None, None),
25683        ] {
25684            let c = WitContract {
25685                de: de.into(),
25686                para: para.into(),
25687                wit: wit.into(),
25688                endpoint: endpoint.map(str::to_owned),
25689                subject: subject.map(str::to_owned),
25690                slot: slot.map(str::to_owned),
25691            };
25692            assert_eq!(
25693                c.identity(),
25694                (
25695                    c.source(),
25696                    c.destination(),
25697                    c.world_ref(),
25698                    c.endpoint(),
25699                    c.subject(),
25700                    c.slot(),
25701                ),
25702                "WitContract::identity must compose exactly \
25703                 (source(), destination(), world_ref(), endpoint(), \
25704                 subject(), slot()) — a bypass of any sibling accessor \
25705                 here would silently decouple the identity-projection \
25706                 axis from the substrate-primitive scalar accessors \
25707                 every dedup-key consumer routes through",
25708            );
25709        }
25710    }
25711
25712    #[test]
25713    fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
25714        // The canonical semantics-pin: [`WitContract::identity`] must
25715        // project the six-axis (de, para, wit, endpoint, subject, slot)
25716        // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
25717        // gate keys off — two `WitContract`s that agree on all six axes
25718        // are the same typed edge declared twice, the graph-edge
25719        // analogue of duplicate `:membros` / `:placement :clusters` /
25720        // `:entrada :paths` entries. Rejects a shape drift (an
25721        // accidental silent detour that returned a prefix tuple or
25722        // added an extra field) by pattern-matching the six-arm shape.
25723        // Peer of the sibling per-`:contratos`
25724        // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
25725        // pin extended from the (de, para, wit) prefix onto the full
25726        // six-axis identity that the dedup key rides.
25727        let c = WitContract {
25728            de: "cart".into(),
25729            para: "catalog".into(),
25730            wit: "wasi:http/proxy".into(),
25731            endpoint: Some("/products/:id".into()),
25732            subject: None,
25733            slot: None,
25734        };
25735        let (de, para, wit, endpoint, subject, slot) = c.identity();
25736        assert_eq!(de, "cart");
25737        assert_eq!(para, "catalog");
25738        assert_eq!(wit, "wasi:http/proxy");
25739        assert_eq!(endpoint, Some("/products/:id"));
25740        assert_eq!(subject, None);
25741        assert_eq!(slot, None);
25742
25743        // Two byte-identical contracts must produce equal identities —
25744        // the dedup key's foundational invariant.
25745        let c2 = c.clone();
25746        assert_eq!(c.identity(), c2.identity());
25747
25748        // Any change on any of the six axes must break the identity —
25749        // sweeps by mutating one axis at a time.
25750        let mut mutated = c.clone();
25751        mutated.de = "search".into();
25752        assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
25753        let mut mutated = c.clone();
25754        mutated.para = "warehouse".into();
25755        assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
25756        let mut mutated = c.clone();
25757        mutated.wit = "http:legacy".into();
25758        assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
25759        let mut mutated = c.clone();
25760        mutated.endpoint = Some("/search".into());
25761        assert_ne!(
25762            c.identity(),
25763            mutated.identity(),
25764            "endpoint axis must partition"
25765        );
25766        let mut mutated = c.clone();
25767        mutated.subject = Some("orders.paid".into());
25768        assert_ne!(
25769            c.identity(),
25770            mutated.identity(),
25771            "subject axis must partition"
25772        );
25773        let mut mutated = c;
25774        mutated.slot = Some("carts/{id}".into());
25775        assert_ne!(mutated.identity().5, None, "slot axis must partition");
25776    }
25777
25778    #[test]
25779    fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
25780        // The canonical per-`:contratos` structural-self-edge pin:
25781        // [`WitContract::is_self_loop`] must return `true` when the
25782        // `:de` and `:para` fields agree byte-for-byte, across every
25783        // WIT-shape variant the per-edge shape family carries. Pins
25784        // the shape-agnostic identity-space partition the
25785        // [`AplicacaoSpec::validate`] self-edge gate at
25786        // caixa-core/src/aplicacao.rs:5559 fires against — all four
25787        // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
25788        // under the same one predicate. Four permutations sweep the
25789        // accept-set: HTTP with endpoint, pub-sub with subject, KV
25790        // store with slot, and payload-less capability.
25791        for (nome, wit, endpoint, subject, slot) in [
25792            ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
25793            ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
25794            (
25795                "kv",
25796                "wasi:keyvalue/store",
25797                None,
25798                None,
25799                Some("carts/{cart_id}"),
25800            ),
25801            ("audit", "wasi:logging", None, None, None),
25802        ] {
25803            let c = WitContract {
25804                de: nome.into(),
25805                para: nome.into(),
25806                wit: wit.into(),
25807                endpoint: endpoint.map(str::to_string),
25808                subject: subject.map(str::to_string),
25809                slot: slot.map(str::to_string),
25810            };
25811            assert!(
25812                c.is_self_loop(),
25813                "WitContract::is_self_loop must return true when \
25814                 :contratos :de == :contratos :para (got false on \
25815                 {nome:?} under {wit:?})",
25816            );
25817        }
25818    }
25819
25820    #[test]
25821    fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
25822        // The complement pin: [`WitContract::is_self_loop`] must return
25823        // `false` on every well-shaped inter-Servico contract (the
25824        // author-intended `:contratos` shape MESH-COMPOSITION §III.1
25825        // names — "Servico A calls Servico B" between two distinct
25826        // graph nodes). Pins against a future silent detour that
25827        // inverted the predicate (an accidental `!= ` swap for `==`
25828        // would silently reject every legitimate inter-Servico edge
25829        // and admit every self-edge — the exact inversion of the
25830        // author-intended shape). Four permutations sweep the same
25831        // WIT-shape accept-set the sibling positive-arm test carries.
25832        for (de, para, wit, endpoint, subject, slot) in [
25833            (
25834                "cart",
25835                "catalog",
25836                "wasi:http/proxy",
25837                Some("/lookup"),
25838                None,
25839                None,
25840            ),
25841            (
25842                "checkout",
25843                "orders",
25844                "nats:pub-sub",
25845                None,
25846                Some("orders.paid"),
25847                None,
25848            ),
25849            (
25850                "cart",
25851                "kv",
25852                "wasi:keyvalue/store",
25853                None,
25854                None,
25855                Some("carts/{cart_id}"),
25856            ),
25857            ("audit", "sink", "wasi:logging", None, None, None),
25858        ] {
25859            let c = WitContract {
25860                de: de.into(),
25861                para: para.into(),
25862                wit: wit.into(),
25863                endpoint: endpoint.map(str::to_string),
25864                subject: subject.map(str::to_string),
25865                slot: slot.map(str::to_string),
25866            };
25867            assert!(
25868                !c.is_self_loop(),
25869                "WitContract::is_self_loop must return false when \
25870                 :contratos :de differs from :contratos :para (got true \
25871                 on {de:?} → {para:?} under {wit:?})",
25872            );
25873        }
25874    }
25875
25876    #[test]
25877    fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
25878        // The composition pin: [`WitContract::is_self_loop`] must
25879        // resolve to exactly `self.source() == self.destination()` —
25880        // the equality probe of the sibling scalar-accessor pair — so
25881        // any future refactor that silently re-authored the predicate
25882        // to bypass the lifted scalar accessors (an accidental
25883        // `self.de == self.para` regression back to the raw field-
25884        // access shape, an M4-typed-caller-enum identity-comparison
25885        // rule that landed on `source()` without reaching
25886        // `destination()`, a per-cluster alias rewrite the operator
25887        // pins on `destination()` without reaching this predicate)
25888        // trips at caixa-core build time. Pins the "typed dispatch
25889        // composes with typed dispatch, not with raw field access"
25890        // discipline the sibling [`WitContract::edge_pair`] /
25891        // [`WitContract::edge_triple`] composite-projection accessors
25892        // already carry, extended onto the per-edge endpoint-equality
25893        // predicate axis. Positive and complement arms both fire.
25894        let self_edge = WitContract {
25895            de: "cart".into(),
25896            para: "cart".into(),
25897            wit: "wasi:http/proxy".into(),
25898            endpoint: Some("/lookup".into()),
25899            subject: None,
25900            slot: None,
25901        };
25902        assert_eq!(
25903            self_edge.is_self_loop(),
25904            self_edge.source() == self_edge.destination(),
25905            "WitContract::is_self_loop must compose exactly \
25906             `source() == destination()` — a bypass of either sibling \
25907             accessor here would silently decouple the endpoint-\
25908             equality predicate from the substrate-primitive scalar \
25909             accessors every downstream consumer routes through",
25910        );
25911        let inter_edge = WitContract {
25912            de: "cart".into(),
25913            para: "catalog".into(),
25914            wit: "wasi:http/proxy".into(),
25915            endpoint: Some("/lookup".into()),
25916            subject: None,
25917            slot: None,
25918        };
25919        assert_eq!(
25920            inter_edge.is_self_loop(),
25921            inter_edge.source() == inter_edge.destination(),
25922            "WitContract::is_self_loop must compose exactly \
25923             `source() == destination()` on the complement arm too",
25924        );
25925    }
25926
25927    #[test]
25928    fn wit_contract_target_wit_shape_gate_routes_through_world_ref_accessor() {
25929        // The composition pin: [`WitContract::target`]'s invalid-wit
25930        // value-shape gate must feed the reason string through the
25931        // lifted [`WitContract::world_ref`] scalar accessor — the same
25932        // typed dispatch on the substrate primitive every peer
25933        // per-`:contratos` payload-carrier extraction in the same
25934        // method body already routes through
25935        // ([`WitContract::endpoint`] on the HTTP-arm target extraction,
25936        // [`WitContract::subject`] on the pub-sub-arm target extraction,
25937        // [`WitContract::slot`] on the store-arm target extraction) and
25938        // every peer composite-projection accessor
25939        // ([`WitContract::edge_pair`], [`WitContract::edge_triple`],
25940        // [`WitContract::identity`]) already composes from. Any future
25941        // refactor that silently re-authored the gate to bypass the
25942        // lifted accessor (an accidental `&self.wit` regression back to
25943        // the raw field-access shape, an M4-typed-`WitWorld` `Display`
25944        // re-canonicalization on `world_ref()` that didn't reach this
25945        // gate, a per-CR lowercasing canonicalization pass the M4
25946        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
25947        // per-tenant that lands on `world_ref()` without reaching this
25948        // gate) would silently split the invalid-wit diagnostic reason
25949        // from the substrate-primitive projection every downstream
25950        // consumer routes through. Same "typed dispatch composes with
25951        // typed dispatch, not with raw field access" discipline the
25952        // sibling
25953        // [`wit_contract_is_self_loop_routes_through_source_destination_accessors`]
25954        // pin already carries on the endpoint-equality predicate axis,
25955        // extended onto the invalid-wit value-shape gate axis inside
25956        // the same [`WitContract::target`] body. Closes the last
25957        // unlifted raw-field-access site inside `impl WitContract`.
25958        //
25959        // The fixture carries `:wit "WASI:HTTP/proxy"` — the canonical
25960        // uppercase-typo footgun the pre-c4213a4 shape silently demoted
25961        // to a capability-only edge; the value-shape gate rejects it
25962        // through [`crate::render::is_wit_world_ref`] on the substrate
25963        // primitive's ASCII-lowercase-only accept-set, with a
25964        // parser-shaped reason string the test asserts round-trips
25965        // byte-for-byte between the direct-dispatch call (through the
25966        // predicate on the accessor's projection) and the
25967        // [`WitContract::target`] gate's produced reason field.
25968        let c = WitContract {
25969            de: "cart".into(),
25970            para: "catalog".into(),
25971            wit: "WASI:HTTP/proxy".into(),
25972            endpoint: Some("/lookup".into()),
25973            subject: None,
25974            slot: None,
25975        };
25976        let err = c.target().unwrap_err();
25977        let AplicacaoError::ContratoWitInvalid {
25978            ref de,
25979            ref para,
25980            ref wit,
25981            ref reason,
25982        } = err
25983        else {
25984            panic!("expected ContratoWitInvalid, got {err:?}");
25985        };
25986        assert_eq!(de, "cart");
25987        assert_eq!(para, "catalog");
25988        assert_eq!(wit, "WASI:HTTP/proxy");
25989        let expected_reason = crate::render::is_wit_world_ref(c.world_ref()).unwrap_err();
25990        assert_eq!(
25991            *reason, expected_reason,
25992            "WitContract::target's invalid-wit value-shape gate reason \
25993             must compose exactly is_wit_world_ref(self.world_ref()) — \
25994             a bypass here (e.g. a raw `&self.wit` field-access \
25995             regression, or a divergent predicate on a different \
25996             projection) would silently decouple the invalid-wit \
25997             diagnostic's reason field from the substrate-primitive \
25998             scalar accessor every peer per-`:contratos` extraction in \
25999             the same method body already routes through",
26000        );
26001    }
26002
26003    #[test]
26004    fn wit_contract_is_self_loop_predicate_is_const_fn() {
26005        // Fail-before-pass-after pin on the [`WitContract::is_self_loop`]
26006        // caller-callee identity-space predicate's `const`-eval-surface
26007        // posture. The wrapper below dispatches through
26008        // [`WitContract::is_self_loop`] and is well-formed only when the
26009        // callee is itself `pub const fn` — any future accidental
26010        // downgrade to non-`const` fails the wrapper at caixa-core build
26011        // time with E0015 (`cannot call non-const method`), strictly
26012        // stronger than a runtime `assert!` and strictly stronger than a
26013        // module-scope `const _: () = assert!(…)` pin (the type's
26014        // `String` / `Option<String>` carriers rule out `const`-context
26015        // value construction; the `const fn` wrapper is the load-bearing
26016        // shape that side-steps the destructor-in-const restriction on
26017        // the value axis while still pinning the `const`-fn posture on
26018        // the callee — mirror of the sibling
26019        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
26020        // (279823b) and
26021        // [`wit_contract_identity_projection_accessor_is_const_fn`]
26022        // (1ab648c) pins' discipline verbatim on the peer scalar-
26023        // accessor and composite-projection surfaces). Closes the last
26024        // unlifted per-`:contratos` shape/identity predicate on the
26025        // const-eval surface — the peer WIT-shape-partition family
26026        // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
26027        // [`WitContract::is_store`] / [`WitContract::is_capability`]
26028        // already carried the `pub const fn` posture on the peer
26029        // WIT-world-ref classifier axis (d46420c / 84c2325 / 279823b);
26030        // this pin extends the same posture onto the caller-callee
26031        // identity-space partition. Sweeps every WIT-shape arm on both
26032        // the equal-endpoints (self-edge) and distinct-endpoints
26033        // (inter-edge) arms of the identity-space partition, plus one
26034        // same-length distinct-byte pair to pin the mid-loop `!=` arm
26035        // past the leading length-mismatch shortcut.
26036        const fn is_self_loop_via_const_fn(c: &WitContract) -> bool {
26037            c.is_self_loop()
26038        }
26039        let mk = |de: &str, para: &str, wit: &str| WitContract {
26040            de: de.into(),
26041            para: para.into(),
26042            wit: wit.into(),
26043            endpoint: None,
26044            subject: None,
26045            slot: None,
26046        };
26047        for (nome, wit) in [
26048            ("cart", "wasi:http/proxy"),
26049            ("checkout", "nats:pub-sub"),
26050            ("kv", "wasi:keyvalue/store"),
26051            ("audit", "wasi:logging"),
26052        ] {
26053            let self_edge = mk(nome, nome, wit);
26054            assert!(
26055                is_self_loop_via_const_fn(&self_edge),
26056                "self-edge {nome:?} under {wit:?}"
26057            );
26058            assert_eq!(
26059                is_self_loop_via_const_fn(&self_edge),
26060                self_edge.is_self_loop()
26061            );
26062        }
26063        for (de, para, wit) in [
26064            ("cart", "catalog", "wasi:http/proxy"),
26065            ("checkout", "orders", "nats:pub-sub"),
26066            ("cart", "kv", "wasi:keyvalue/store"),
26067            ("audit", "sink", "wasi:logging"),
26068        ] {
26069            let inter_edge = mk(de, para, wit);
26070            assert!(
26071                !is_self_loop_via_const_fn(&inter_edge),
26072                "inter-edge {de:?}→{para:?} under {wit:?}",
26073            );
26074            assert_eq!(
26075                is_self_loop_via_const_fn(&inter_edge),
26076                inter_edge.is_self_loop()
26077            );
26078        }
26079        // Same-length distinct-byte pair — pins the mid-loop `!=` arm
26080        // past the leading `a.len() != b.len()` shortcut so the const-fn
26081        // wrapper exercises every arm of the byte-slice equality loop.
26082        let same_len_pair = mk("cart", "kart", "wasi:http/proxy");
26083        assert!(
26084            !is_self_loop_via_const_fn(&same_len_pair),
26085            "same-length distinct-byte"
26086        );
26087        assert_eq!(
26088            is_self_loop_via_const_fn(&same_len_pair),
26089            same_len_pair.is_self_loop()
26090        );
26091    }
26092
26093    #[test]
26094    fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
26095        // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
26096        // pin: [`WitContract::endpoint`] must return the `:contratos
26097        // :endpoint` field byte-for-byte, borrowed from the typed slot's
26098        // own `Option<String>` storage. Peer of the sibling
26099        // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
26100        // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
26101        // mesh-slot `Option<String>` optional-scalar axes — same "the
26102        // substrate-primitive accessor must byte-equal the raw field
26103        // access verbatim across every author-declared value" discipline
26104        // extended to the per-`:contratos` HTTP-payload-carrier arm.
26105        // Pins against a future silent detour that re-canonicalized the
26106        // endpoint (an accidental percent-encoding pass that didn't
26107        // reach the peer field-access site at the dedup key, a per-CR
26108        // fully-qualified prefix rewrite the operator authors on one
26109        // consumer without the other, or an M4 typed-path-template
26110        // `Display` re-canonicalization that silently drifted the
26111        // printer output from the source `caixa.lisp`). Four values
26112        // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
26113        // gate upstream admits (short root-path, dashed, param-shaped,
26114        // deep-hierarchy).
26115        for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
26116            let c = WitContract {
26117                de: "cart".into(),
26118                para: "catalog".into(),
26119                wit: "wasi:http/proxy".into(),
26120                endpoint: Some(endpoint.into()),
26121                subject: None,
26122                slot: None,
26123            };
26124            assert_eq!(
26125                c.endpoint(),
26126                Some(endpoint),
26127                "WitContract::endpoint must return :contratos :endpoint \
26128                 verbatim (got {:?}, expected Some({endpoint:?}))",
26129                c.endpoint(),
26130            );
26131            assert_eq!(
26132                c.endpoint(),
26133                c.endpoint.as_deref(),
26134                "WitContract::endpoint must byte-equal the .endpoint \
26135                 field's `.as_deref()` projection",
26136            );
26137        }
26138    }
26139
26140    #[test]
26141    fn wit_contract_endpoint_none_when_field_is_none() {
26142        // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
26143        // payload-carrier accessor pin: when the typed slot is absent —
26144        // the canonical shape under a non-HTTP `:wit` world per the
26145        // [`WitContract::target`]-enforced shape ↔ target partition
26146        // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
26147        // carries `:slot`, [`WitTarget::Capability`] carries none) —
26148        // [`WitContract::endpoint`] must return `None`. Pins against a
26149        // future silent detour that projected the absent slot to a
26150        // `Some("")` empty-string default (the canonical `Option<String>`
26151        // → `String` collapse footgun the sibling M2
26152        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
26153        // emptiness predicates already guard on the peer M2 typed-slot
26154        // surfaces), a `Some("None")` stringified-None round-trip, or a
26155        // `Some` arm whose contents were derived from a sibling slot (an
26156        // accidental fallback to the `:subject` / `:slot` payload that
26157        // read the pub-sub / store payload into the endpoint axis).
26158        // Three contracts sweep the accept-set every non-HTTP `:wit`
26159        // world lands on — pub-sub NATS, key/value, and payload-less
26160        // capability.
26161        for (wit, subject, slot) in [
26162            ("nats:pub-sub", Some("orders.paid"), None),
26163            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
26164            ("wasi:cli/environment", None, None),
26165        ] {
26166            let c = WitContract {
26167                de: "cart".into(),
26168                para: "downstream".into(),
26169                wit: wit.into(),
26170                endpoint: None,
26171                subject: subject.map(str::to_string),
26172                slot: slot.map(str::to_string),
26173            };
26174            assert!(
26175                c.endpoint().is_none(),
26176                "WitContract::endpoint must return None when the typed \
26177                 slot is absent under :wit {wit:?} (got {:?})",
26178                c.endpoint(),
26179            );
26180            assert_eq!(
26181                c.endpoint(),
26182                c.endpoint.as_deref(),
26183                "WitContract::endpoint must byte-equal the .endpoint \
26184                 field's `.as_deref()` projection in the absent arm",
26185            );
26186        }
26187    }
26188
26189    #[test]
26190    fn wit_contract_endpoint_borrows_from_endpoint_storage() {
26191        // The borrow-not-copy pin: [`WitContract::endpoint`] must return
26192        // an `Option<&str>` whose `Some` arm borrows from the typed
26193        // slot's own [`String`] storage — same-address invariant with
26194        // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
26195        // detour that allocated a fresh `String`
26196        // (`self.endpoint.clone().map(...)` in the body would type-check
26197        // but silently drop the borrow, and every downstream consumer
26198        // that assumed the returned slice outlives `&self` would break
26199        // on a stale-reference use-after-free — the [`WitContract::target`]
26200        // Http-arm payload extraction rebinds the returned `Option<&str>`
26201        // through `.ok_or_else(...)` and threads the `&str` payload into
26202        // [`WitTarget::Http { endpoint: &'a str }`], the
26203        // [`AplicacaoSpec::validate`] duplicate-`:contratos`
26204        // [`ContratoIdentity`] dedup key threads the returned
26205        // `Option<&str>` into the six-tuple's HTTP arm — each borrow
26206        // from the WitContract's own storage and each would silently
26207        // misbehave if this accessor produced a detached copy). Peer of
26208        // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
26209        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
26210        // shaped optional-scalar axes — first extension of the
26211        // `Option<&str>` borrow-not-copy discipline onto the
26212        // per-`:contratos` HTTP-shaped payload-carrier axis.
26213        let c = WitContract {
26214            de: "cart".into(),
26215            para: "catalog".into(),
26216            wit: "wasi:http/proxy".into(),
26217            endpoint: Some("/lookup".into()),
26218            subject: None,
26219            slot: None,
26220        };
26221        let ep = c.endpoint().expect("Some arm");
26222        let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
26223        assert_eq!(
26224            ep.as_ptr(),
26225            storage_slice.as_ptr(),
26226            "WitContract::endpoint must borrow from the .endpoint \
26227             String's backing storage — a fresh allocation here means \
26228             the accessor no longer names the substrate-primitive typed \
26229             dispatch and every downstream consumer would silently \
26230             carry a detached copy",
26231        );
26232        assert_eq!(
26233            ep.len(),
26234            storage_slice.len(),
26235            "WitContract::endpoint and .endpoint.as_deref() must byte-\
26236             equal in length as well as in address",
26237        );
26238    }
26239
26240    #[test]
26241    fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
26242        // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
26243        // pin: [`WitContract::subject`] must return the `:contratos
26244        // :subject` field byte-for-byte, borrowed from the typed slot's
26245        // own `Option<String>` storage. Peer of the sibling per-`:contratos`
26246        // [`WitContract::endpoint`] (7020470) accessor pin on the M3
26247        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
26248        // optional-scalar axis — same "the substrate-primitive accessor
26249        // must byte-equal the raw field access verbatim across every
26250        // author-declared value" discipline extended to the pub-sub arm.
26251        // Pins against a future silent detour that re-canonicalized the
26252        // subject (an accidental `.to_lowercase()` normalization that
26253        // didn't reach the peer field-access site at the dedup key, a
26254        // per-CR fully-qualified prefix rewrite the operator authors on
26255        // one consumer without the other, or an M4 typed-subject-template
26256        // `Display` re-canonicalization that silently drifted the printer
26257        // output from the source `caixa.lisp`). Four values sweep the
26258        // NATS accept-set every pub-sub author-declared subject lands on
26259        // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
26260        for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
26261            let c = WitContract {
26262                de: "cart".into(),
26263                para: "notifier".into(),
26264                wit: "nats:pub-sub".into(),
26265                endpoint: None,
26266                subject: Some(subject.into()),
26267                slot: None,
26268            };
26269            assert_eq!(
26270                c.subject(),
26271                Some(subject),
26272                "WitContract::subject must return :contratos :subject \
26273                 verbatim (got {:?}, expected Some({subject:?}))",
26274                c.subject(),
26275            );
26276            assert_eq!(
26277                c.subject(),
26278                c.subject.as_deref(),
26279                "WitContract::subject must byte-equal the .subject \
26280                 field's `.as_deref()` projection",
26281            );
26282        }
26283    }
26284
26285    #[test]
26286    fn wit_contract_subject_none_when_field_is_none() {
26287        // The absent-`:subject` arm of the per-`:contratos` pub-sub-
26288        // shaped payload-carrier accessor pin: when the typed slot is
26289        // absent — the canonical shape under a non-pub-sub `:wit` world
26290        // per the [`WitContract::target`]-enforced shape ↔ target
26291        // partition ([`WitTarget::Http`] carries `:endpoint`,
26292        // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
26293        // carries none) — [`WitContract::subject`] must return `None`.
26294        // Pins against a future silent detour that projected the absent
26295        // slot to a `Some("")` empty-string default (the canonical
26296        // `Option<String>` → `String` collapse footgun the sibling M2
26297        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
26298        // emptiness predicates already guard on the peer M2 typed-slot
26299        // surfaces), a `Some("None")` stringified-None round-trip, or a
26300        // `Some` arm whose contents were derived from a sibling slot (an
26301        // accidental fallback to the `:endpoint` / `:slot` payload that
26302        // read the HTTP / store payload into the subject axis). Three
26303        // contracts sweep the accept-set every non-pub-sub `:wit` world
26304        // lands on — HTTP proxy, key/value store, and payload-less
26305        // capability.
26306        for (wit, endpoint, slot) in [
26307            ("wasi:http/proxy", Some("/lookup"), None),
26308            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
26309            ("wasi:cli/environment", None, None),
26310        ] {
26311            let c = WitContract {
26312                de: "cart".into(),
26313                para: "downstream".into(),
26314                wit: wit.into(),
26315                endpoint: endpoint.map(str::to_string),
26316                subject: None,
26317                slot: slot.map(str::to_string),
26318            };
26319            assert!(
26320                c.subject().is_none(),
26321                "WitContract::subject must return None when the typed \
26322                 slot is absent under :wit {wit:?} (got {:?})",
26323                c.subject(),
26324            );
26325            assert_eq!(
26326                c.subject(),
26327                c.subject.as_deref(),
26328                "WitContract::subject must byte-equal the .subject \
26329                 field's `.as_deref()` projection in the absent arm",
26330            );
26331        }
26332    }
26333
26334    #[test]
26335    fn wit_contract_subject_borrows_from_subject_storage() {
26336        // The borrow-not-copy pin: [`WitContract::subject`] must return
26337        // an `Option<&str>` whose `Some` arm borrows from the typed
26338        // slot's own [`String`] storage — same-address invariant with
26339        // `c.subject.as_deref().unwrap()`. Pins against a future silent
26340        // detour that allocated a fresh `String`
26341        // (`self.subject.clone().map(...)` in the body would type-check
26342        // but silently drop the borrow, and every downstream consumer
26343        // that assumed the returned slice outlives `&self` would break
26344        // on a stale-reference use-after-free — the [`WitContract::target`]
26345        // PubSub-arm payload extraction rebinds the returned
26346        // `Option<&str>` through `.ok_or_else(...)` and threads the
26347        // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
26348        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
26349        // [`ContratoIdentity`] dedup key threads the returned
26350        // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
26351        // from the WitContract's own storage and each would silently
26352        // misbehave if this accessor produced a detached copy). Peer of
26353        // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
26354        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
26355        // shaped optional-scalar axis — second extension of the
26356        // `Option<&str>` borrow-not-copy discipline onto the
26357        // per-`:contratos` payload-carrier family, this time on the
26358        // pub-sub arm.
26359        let c = WitContract {
26360            de: "cart".into(),
26361            para: "notifier".into(),
26362            wit: "nats:pub-sub".into(),
26363            endpoint: None,
26364            subject: Some("orders.paid".into()),
26365            slot: None,
26366        };
26367        let sub = c.subject().expect("Some arm");
26368        let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
26369        assert_eq!(
26370            sub.as_ptr(),
26371            storage_slice.as_ptr(),
26372            "WitContract::subject must borrow from the .subject \
26373             String's backing storage — a fresh allocation here means \
26374             the accessor no longer names the substrate-primitive typed \
26375             dispatch and every downstream consumer would silently \
26376             carry a detached copy",
26377        );
26378        assert_eq!(
26379            sub.len(),
26380            storage_slice.len(),
26381            "WitContract::subject and .subject.as_deref() must byte-\
26382             equal in length as well as in address",
26383        );
26384    }
26385
26386    #[test]
26387    fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
26388        // The canonical per-`:contratos` key/value-store-shaped
26389        // `:slot`-scalar pin: [`WitContract::slot`] must return the
26390        // `:contratos :slot` field byte-for-byte, borrowed from the
26391        // typed slot's own `Option<String>` storage. Peer of the
26392        // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
26393        // [`WitContract::subject`] (90de675) accessor pins on the M3
26394        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
26395        // optional-scalar axis — same "the substrate-primitive
26396        // accessor must byte-equal the raw field access verbatim
26397        // across every author-declared value" discipline extended to
26398        // the store arm. Pins against a future silent detour that
26399        // re-canonicalized the slot template (an accidental
26400        // `.to_lowercase()` bucket-prefix normalization that didn't
26401        // reach the peer field-access site at the dedup key, a per-CR
26402        // fully-qualified prefix rewrite the operator authors on one
26403        // consumer without the other, or an M4 typed-key-template
26404        // `Display` re-canonicalization that silently drifted the
26405        // printer output from the source `caixa.lisp`). Four values
26406        // sweep the wasi:keyvalue accept-set every store-shaped
26407        // author-declared slot lands on (flat bucket, single-param
26408        // template, multi-param template, nested-hierarchy template).
26409        for slot in [
26410            "sessions",
26411            "carts/{cart_id}",
26412            "orders/{tenant}/{order_id}",
26413            "cache/tenant-a/orders/{id}",
26414        ] {
26415            let c = WitContract {
26416                de: "cart".into(),
26417                para: "kv".into(),
26418                wit: "wasi:keyvalue/store".into(),
26419                endpoint: None,
26420                subject: None,
26421                slot: Some(slot.into()),
26422            };
26423            assert_eq!(
26424                c.slot(),
26425                Some(slot),
26426                "WitContract::slot must return :contratos :slot \
26427                 verbatim (got {:?}, expected Some({slot:?}))",
26428                c.slot(),
26429            );
26430            assert_eq!(
26431                c.slot(),
26432                c.slot.as_deref(),
26433                "WitContract::slot must byte-equal the .slot field's \
26434                 `.as_deref()` projection",
26435            );
26436        }
26437    }
26438
26439    #[test]
26440    fn wit_contract_slot_none_when_field_is_none() {
26441        // The absent-`:slot` arm of the per-`:contratos` store-shaped
26442        // payload-carrier accessor pin: when the typed slot is absent —
26443        // the canonical shape under a non-store `:wit` world per the
26444        // [`WitContract::target`]-enforced shape ↔ target partition
26445        // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
26446        // carries `:subject`, [`WitTarget::Capability`] carries none) —
26447        // [`WitContract::slot`] must return `None`. Pins against a
26448        // future silent detour that projected the absent slot to a
26449        // `Some("")` empty-string default (the canonical
26450        // `Option<String>` → `String` collapse footgun the sibling M2
26451        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
26452        // emptiness predicates already guard on the peer M2 typed-slot
26453        // surfaces), a `Some("None")` stringified-None round-trip, or
26454        // a `Some` arm whose contents were derived from a sibling
26455        // slot (an accidental fallback to the `:endpoint` / `:subject`
26456        // payload that read the HTTP / pub-sub payload into the store
26457        // axis). Three contracts sweep the accept-set every non-store
26458        // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
26459        // payload-less capability.
26460        for (wit, endpoint, subject) in [
26461            ("wasi:http/proxy", Some("/lookup"), None),
26462            ("nats:pub-sub", None, Some("orders.paid")),
26463            ("wasi:cli/environment", None, None),
26464        ] {
26465            let c = WitContract {
26466                de: "cart".into(),
26467                para: "downstream".into(),
26468                wit: wit.into(),
26469                endpoint: endpoint.map(str::to_string),
26470                subject: subject.map(str::to_string),
26471                slot: None,
26472            };
26473            assert!(
26474                c.slot().is_none(),
26475                "WitContract::slot must return None when the typed \
26476                 slot is absent under :wit {wit:?} (got {:?})",
26477                c.slot(),
26478            );
26479            assert_eq!(
26480                c.slot(),
26481                c.slot.as_deref(),
26482                "WitContract::slot must byte-equal the .slot field's \
26483                 `.as_deref()` projection in the absent arm",
26484            );
26485        }
26486    }
26487
26488    #[test]
26489    fn wit_contract_slot_borrows_from_slot_storage() {
26490        // The borrow-not-copy pin: [`WitContract::slot`] must return
26491        // an `Option<&str>` whose `Some` arm borrows from the typed
26492        // slot's own [`String`] storage — same-address invariant with
26493        // `c.slot.as_deref().unwrap()`. Pins against a future silent
26494        // detour that allocated a fresh `String`
26495        // (`self.slot.clone().map(...)` in the body would type-check
26496        // but silently drop the borrow, and every downstream consumer
26497        // that assumed the returned slice outlives `&self` would
26498        // break on a stale-reference use-after-free — the
26499        // [`WitContract::target`] Store-arm payload extraction rebinds
26500        // the returned `Option<&str>` through `.ok_or_else(...)` and
26501        // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
26502        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
26503        // [`ContratoIdentity`] dedup key threads the returned
26504        // `Option<&str>` into the six-tuple's store arm — each borrow
26505        // from the WitContract's own storage and each would silently
26506        // misbehave if this accessor produced a detached copy). Peer
26507        // of the sibling per-`:contratos` [`WitContract::endpoint`]
26508        // (7020470) / [`WitContract::subject`] (90de675)
26509        // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
26510        // shaped optional-scalar axis — third and final extension of
26511        // the `Option<&str>` borrow-not-copy discipline onto the
26512        // per-`:contratos` payload-carrier family, this time on the
26513        // store arm.
26514        let c = WitContract {
26515            de: "cart".into(),
26516            para: "kv".into(),
26517            wit: "wasi:keyvalue/store".into(),
26518            endpoint: None,
26519            subject: None,
26520            slot: Some("carts/{cart_id}".into()),
26521        };
26522        let slot = c.slot().expect("Some arm");
26523        let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
26524        assert_eq!(
26525            slot.as_ptr(),
26526            storage_slice.as_ptr(),
26527            "WitContract::slot must borrow from the .slot String's \
26528             backing storage — a fresh allocation here means the \
26529             accessor no longer names the substrate-primitive typed \
26530             dispatch and every downstream consumer would silently \
26531             carry a detached copy",
26532        );
26533        assert_eq!(
26534            slot.len(),
26535            storage_slice.len(),
26536            "WitContract::slot and .slot.as_deref() must byte-equal \
26537             in length as well as in address",
26538        );
26539    }
26540
26541    #[test]
26542    fn membro_nome_returns_caixa_byte_equal_across_permutations() {
26543        // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
26544        // [`Membro::nome`] must return the `:membros :caixa` field
26545        // byte-for-byte, borrowed from the typed slot's own [`String`]
26546        // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
26547        // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
26548        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
26549        // slot-atom scalar-value axes — same "the substrate-primitive
26550        // accessor must byte-equal the raw field access verbatim across
26551        // every author-declared value" discipline extended to the
26552        // per-`:membros` member-identity arm. Pins against a future
26553        // silent detour that re-normalized the member identity (an
26554        // accidental `.to_lowercase()` — every `:membros :caixa` is
26555        // validated as a DNS-1123 label upstream via
26556        // [`validate_membro_caixa`], so any re-normalization is
26557        // redundant + a drift surface between the validator and the
26558        // accessor), a namespace-prefix rewrite (an accidental
26559        // `format!("{namespace}/{caixa}")` per-CR fully-qualified
26560        // rewrite that didn't land on the peer axes), or a per-cluster
26561        // alias stamp the operator authors on one consumer without the
26562        // other. Four values sweep the accept-set the DNS-1123 gate
26563        // upstream admits (short single-word / dashed / v-suffixed
26564        // member names).
26565        for name in ["cart", "checkout", "catalog", "orders-v2"] {
26566            let m = Membro {
26567                caixa: name.into(),
26568                versao: "^0.1".into(),
26569            };
26570            assert_eq!(
26571                m.nome(),
26572                name,
26573                "Membro::nome must return :membros :caixa verbatim \
26574                 (got {:?}, expected {name:?})",
26575                m.nome(),
26576            );
26577            assert_eq!(
26578                m.nome(),
26579                m.caixa.as_str(),
26580                "Membro::nome must byte-equal the .caixa field access",
26581            );
26582        }
26583    }
26584
26585    #[test]
26586    fn membro_nome_borrows_from_caixa_storage() {
26587        // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
26588        // slice that borrows from the typed slot's own [`String`]
26589        // storage — same-address invariant with `m.caixa.as_str()`. Pins
26590        // against a future silent detour that allocated a fresh `String`
26591        // (`self.caixa.clone()` in the body would type-check but
26592        // silently drop the borrow, and every downstream consumer that
26593        // assumed the returned slice outlives `&self` would break on a
26594        // stale-reference use-after-free — the `HashSet<&str>` collector
26595        // at [`AplicacaoSpec::validate`]'s `names` seed, the
26596        // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
26597        // [`AplicacaoSpec::detect_sync_cycles`], the
26598        // [`crate::render::insert_first_seen`] dedup key at
26599        // [`AplicacaoSpec::validate_membros`] — each borrow from the
26600        // Membro's own storage and each would silently misbehave if
26601        // this accessor produced a detached copy). Peer of the sibling
26602        // per-`:contratos` [`WitContract::source`] /
26603        // [`WitContract::destination`] and per-`:entrada`
26604        // [`Entrada::destination`] borrow-invariant pins on the mesh-
26605        // slot-atom scalar-value axes.
26606        let m = Membro {
26607            caixa: "checkout".into(),
26608            versao: "^0.1".into(),
26609        };
26610        let name = m.nome();
26611        let caixa_slice = m.caixa.as_str();
26612        assert_eq!(
26613            name.as_ptr(),
26614            caixa_slice.as_ptr(),
26615            "Membro::nome must borrow from the .caixa String's backing \
26616             storage — a fresh allocation here means the accessor no \
26617             longer names the substrate-primitive typed dispatch and \
26618             every downstream consumer would silently carry a detached \
26619             copy",
26620        );
26621        assert_eq!(
26622            name.len(),
26623            caixa_slice.len(),
26624            "Membro::nome and .caixa.as_str() must byte-equal in length \
26625             as well as in address",
26626        );
26627    }
26628
26629    #[test]
26630    fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
26631        // The canonical per-`:membros` member-`:versao`-scalar pin:
26632        // [`Membro::versao_requirement`] must return the
26633        // `:membros :versao` field byte-for-byte, borrowed from the typed
26634        // slot's own [`String`] storage. Sibling of the peer
26635        // `membro_nome_returns_caixa_byte_equal_across_permutations`
26636        // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
26637        // — same "the substrate-primitive accessor must byte-equal the
26638        // raw field access verbatim across every author-declared value"
26639        // discipline extended to the per-`:membros` member-`:versao`
26640        // requirement-string arm. Pins against a future silent detour
26641        // that re-canonicalized the requirement (an accidental
26642        // `.to_string()` via [`parse_requirement`] → [`Display`] round-
26643        // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
26644        // drifted the printer output away from the source `caixa.lisp`,
26645        // an accidental whitespace trim on `"^ 0.1"` that no consumer
26646        // ever produced from the field-access side, an accidental
26647        // per-cluster lacre-projected concrete-version rewrite that
26648        // didn't land on the peer field-access sites). Five values sweep
26649        // the accept-set the shared
26650        // [`crate::render::require_valid_versao_requirement`] gate
26651        // admits (caret / tilde / exact / wildcard / bare-major).
26652        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
26653            let m = Membro {
26654                caixa: "cart".into(),
26655                versao: req.into(),
26656            };
26657            assert_eq!(
26658                m.versao_requirement(),
26659                req,
26660                "Membro::versao_requirement must return :membros :versao \
26661                 verbatim (got {:?}, expected {req:?})",
26662                m.versao_requirement(),
26663            );
26664            assert_eq!(
26665                m.versao_requirement(),
26666                m.versao.as_str(),
26667                "Membro::versao_requirement must byte-equal the .versao \
26668                 field access",
26669            );
26670        }
26671    }
26672
26673    #[test]
26674    fn membro_versao_requirement_borrows_from_versao_storage() {
26675        // The borrow-not-copy pin: [`Membro::versao_requirement`] must
26676        // return a `&str` slice that borrows from the typed slot's own
26677        // [`String`] storage — same-address invariant with
26678        // `m.versao.as_str()`. Pins against a future silent detour that
26679        // allocated a fresh `String` (`self.versao.clone()` in the body
26680        // would type-check but silently drop the borrow, and every
26681        // downstream consumer that assumed the returned slice outlives
26682        // `&self` would break on a stale-reference use-after-free). Peer
26683        // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
26684        // per-`:contratos` [`WitContract::source`] /
26685        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
26686        // [`Entrada::destination`] (6db982c) borrow-invariant pins on
26687        // the mesh-slot-atom scalar-value axes.
26688        let m = Membro {
26689            caixa: "checkout".into(),
26690            versao: "^0.1".into(),
26691        };
26692        let req = m.versao_requirement();
26693        let versao_slice = m.versao.as_str();
26694        assert_eq!(
26695            req.as_ptr(),
26696            versao_slice.as_ptr(),
26697            "Membro::versao_requirement must borrow from the .versao \
26698             String's backing storage — a fresh allocation here means \
26699             the accessor no longer names the substrate-primitive typed \
26700             dispatch and every downstream consumer would silently carry \
26701             a detached copy",
26702        );
26703        assert_eq!(
26704            req.len(),
26705            versao_slice.len(),
26706            "Membro::versao_requirement and .versao.as_str() must byte-\
26707             equal in length as well as in address",
26708        );
26709    }
26710
26711    #[test]
26712    fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
26713        // Sibling-pair invariant pin composing both per-`:membros`
26714        // substrate-primitive typed dispatches — [`Membro::nome`]
26715        // (4a32abf) and [`Membro::versao_requirement`] — at the joint
26716        // `(nome(), versao_requirement())` call shape every renderer
26717        // that fans on per-member identity + version pin keys off. The
26718        // invariant, evaluated per-member:
26719        //
26720        //   (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
26721        //
26722        // Closes the last unlifted per-`:membros` scalar axis — every
26723        // downstream consumer that reads the pair now routes through
26724        // exactly two typed dispatches on the substrate primitive, not
26725        // one typed + one open-coded field access. A future refactor
26726        // that silently split either accessor's projection (an
26727        // accidental `nome()` namespace-prefix rewrite that didn't
26728        // reach the peer, an accidental `versao_requirement()` lacre-
26729        // projected concrete-version rewrite that didn't land on the
26730        // `nome()` peer) surfaces at caixa-core build time. Peer of the
26731        // sibling per-`:entrada` `(hostname(), destination())` and
26732        // per-`:contratos` `(source(), destination())` pair invariants
26733        // on the mesh-slot-atom scalar-value axes.
26734        for (caixa, versao) in [
26735            ("cart", "^0.1"),
26736            ("checkout", "~0.1.2"),
26737            ("catalog", "0.1.0"),
26738            ("orders-v2", "*"),
26739        ] {
26740            let m = Membro {
26741                caixa: caixa.into(),
26742                versao: versao.into(),
26743            };
26744            assert_eq!(
26745                (m.nome(), m.versao_requirement()),
26746                (m.caixa.as_str(), m.versao.as_str()),
26747                "(Membro::nome, Membro::versao_requirement) must project \
26748                 (.caixa, .versao) verbatim across every author-declared \
26749                 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
26750                m.nome(),
26751                m.versao_requirement(),
26752            );
26753        }
26754    }
26755
26756    #[test]
26757    fn validate_membros_empty_gate_routes_through_nome_accessor() {
26758        // Composition pin: [`AplicacaoSpec::validate_membros`]'s
26759        // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
26760        // not the raw `.caixa` field access. Structurally: setting
26761        // ONLY the `.caixa` field to `""` on an otherwise-well-formed
26762        // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
26763        // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
26764        // (i.e. the empty string) — so the emptiness predicate the
26765        // refusal arm reaches under is the accessor-projected value,
26766        // not a peer field that would silently drift under a future
26767        // accessor-side rewrite.
26768        //
26769        // Pins against a future silent detour that (a) re-derived the
26770        // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
26771        // instead of `self.nome().is_empty()`, silently disagreeing with
26772        // every peer consumer (the `validate_membro_caixa(m.nome())`
26773        // per-slot helper — which now owns the emptiness arm outright —
26774        // the dedup-key `insert_first_seen(&mut seen, m.nome(), …)`
26775        // below, and the emit-side per-`programs[]` entry-`name:` at
26776        // caixa-mesh/src/lib.rs:133), (b) accessor-side introduced a
26777        // per-tenant alias arm the caller was unaware of, silently
26778        // rewriting an author-declared `:caixa "checkout"` to `""` —
26779        // the raw-field-access gate would fail-open while the
26780        // accessor-routed peer consumers would fail-closed, splitting
26781        // the diagnostic from the actual failure surface.
26782        //
26783        // Peer of the sibling
26784        // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
26785        // (c0110f1) composition pin — same "the shape-gate predicate
26786        // must route through the substrate-primitive typed dispatch"
26787        // discipline extended onto the per-`:membros` empty-`:caixa`
26788        // refusal-arm axis. Closes the last unlifted `.caixa` production-
26789        // code read site on `Membro` — after this converge every
26790        // caixa-core `.caixa` field access outside the accessor's own
26791        // body is either a test-side field-setter (in-module tests
26792        // constructing invalid-shape inputs) or a doc-comment reference.
26793        let mut s = three_member_spec();
26794        s.membros[1].caixa = String::new();
26795        assert!(
26796            s.membros[1].nome().is_empty(),
26797            "Membro::nome must byte-equal the .caixa field access — an \
26798             accessor-side detour that no longer projects the raw field \
26799             would silently split this drift-detection test from the \
26800             validate() refusal arm",
26801        );
26802        assert_eq!(
26803            s.membros[1].nome(),
26804            s.membros[1].caixa.as_str(),
26805            "Membro::nome and .caixa.as_str() must byte-equal on an \
26806             empty-`:caixa` entry — the emptiness gate keys off the \
26807             accessor by construction",
26808        );
26809        assert_eq!(
26810            s.validate().unwrap_err(),
26811            AplicacaoError::MembroCaixaEmpty,
26812            "validate_membros' emptiness gate must fire MembroCaixaEmpty \
26813             on an entry whose accessor-projected `nome()` is empty",
26814        );
26815    }
26816
26817    #[test]
26818    fn validate_membros_empty_arm_is_owned_by_validate_membro_caixa_alone() {
26819        // Convergence pin, paired with the deletion of the redundant
26820        // outer `if m.nome().is_empty() { return Err(MembroCaixaEmpty); }`
26821        // guard formerly inline in [`AplicacaoSpec::validate_membros`]:
26822        // after the collapse, the `MembroCaixaEmpty` refusal on every
26823        // empty-`:caixa` per-member input is owned solely by the shared
26824        // [`validate_membro_caixa`] helper — the same per-slot substrate
26825        // primitive routing empty + shape arms uniformly onto
26826        // [`crate::render::require_valid_dns_1123_label`] that every
26827        // peer M3 mesh-slot per-slot gate ([`validate_placement_cluster`]
26828        // on `:placement :clusters`, [`validate_entrada_para`] on
26829        // `:entrada :para`, [`validate_contrato_caixa`] on `:contratos
26830        // :de`/`:para`) already funnels its own empty arm through.
26831        //
26832        // Two arms pin the collapse:
26833        //
26834        //   (1) The per-slot helper called with the empty string returns
26835        //       byte-equal to the previous inline arm's diagnostic — so
26836        //       a future rebrand of [`validate_membro_caixa`] that
26837        //       (accidentally) stopped returning [`MembroCaixaEmpty`] on
26838        //       empty input (an inadvertent switch to
26839        //       [`AplicacaoError::MembroCaixaInvalid`] via the parse-side
26840        //       `on_invalid` arm, an accidental re-routing to a shared
26841        //       `MembroError::Empty` under a future error-hierarchy
26842        //       flattening) would silently split the drift from the
26843        //       [`validate_membros`] caller and surface the wrong
26844        //       diagnostic on the author-facing empty-`:caixa` footgun.
26845        //
26846        //   (2) The whole-spec equivalence: an empty-`:caixa` entry
26847        //       anywhere in the `:membros` fan-out still trips
26848        //       [`MembroCaixaEmpty`] end-to-end via [`validate`], with
26849        //       no outer inline guard needed. Same shape as the
26850        //       whole-spec arm on [`validate_placement_cluster`] /
26851        //       [`validate_entrada_para`] / [`validate_contrato_caixa`]:
26852        //       one substrate primitive per axis, folding empty + shape.
26853        //
26854        // Same PRIME DIRECTIVE convergence the peer per-slot gate lifts
26855        // (906a5c6 validate_contratos, 20cd523 validate_entrada, f03a154
26856        // MeshPolicy::validate) already extend across the M3 mesh-slot
26857        // family — closes the last per-slot gate on the family carrying
26858        // an inline empty guard duplicating its own helper.
26859        assert_eq!(
26860            validate_membro_caixa(""),
26861            Err(AplicacaoError::MembroCaixaEmpty),
26862            "validate_membro_caixa must own the empty arm outright — a \
26863             regression here would silently split MembroCaixaEmpty from \
26864             validate_membros' end-to-end refusal shape after the outer \
26865             inline `if m.nome().is_empty()` guard collapse",
26866        );
26867        let mut s = three_member_spec();
26868        s.membros[0].caixa = String::new();
26869        assert_eq!(
26870            s.validate().unwrap_err(),
26871            AplicacaoError::MembroCaixaEmpty,
26872            "an empty-`:caixa` :membros head entry must trip \
26873             MembroCaixaEmpty end-to-end via validate() with the outer \
26874             inline guard removed — the per-slot helper alone is now \
26875             load-bearing",
26876        );
26877        let mut s = three_member_spec();
26878        s.membros[2].caixa = String::new();
26879        assert_eq!(
26880            s.validate().unwrap_err(),
26881            AplicacaoError::MembroCaixaEmpty,
26882            "an empty-`:caixa` :membros tail entry must trip \
26883             MembroCaixaEmpty end-to-end via validate() with the outer \
26884             inline guard removed — the per-slot helper alone reaches \
26885             every fan-out position",
26886        );
26887    }
26888
26889    #[test]
26890    fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
26891        // The canonical per-`:placement` Akka-cluster-sharding
26892        // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
26893        // the `:placement :shard-key` field byte-for-byte, borrowed
26894        // from the typed slot's own `Option<String>` storage. Peer of
26895        // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
26896        // per-`:contratos` [`WitContract::source`] /
26897        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
26898        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
26899        // slot-atom scalar-value axes — same "the substrate-primitive
26900        // accessor must byte-equal the raw field access verbatim across
26901        // every author-declared value" discipline extended to the
26902        // per-`:placement` Akka-cluster-sharding key extractor arm.
26903        // Pins against a future silent detour that re-normalized the
26904        // key (an accidental `.to_lowercase()` — every non-empty
26905        // `:shard-key` is validated as a printable-ASCII single-token
26906        // reference upstream via [`validate_placement_shard_key`], so
26907        // any re-normalization is redundant + a drift surface between
26908        // the validator and the accessor), a per-cluster alias rewrite
26909        // the operator authors on one consumer without the other, or an
26910        // accidental variable-prefix strip (`$tenantId` → `tenantId`)
26911        // that didn't land on the peer field-access sites. Four values
26912        // sweep the accept-set the shape gate admits — bare identifier,
26913        // `$`-prefixed variable, dotted path, `${}`-quoted variable —
26914        // the four canonical Akka-style entity-id extractor shapes the
26915        // future M4 cluster-sharding reconciler hashes.
26916        for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
26917            let p = Placement {
26918                estrategia: PlacementStrategy::Sharded,
26919                clusters: vec!["rio".into()],
26920                affinity: None,
26921                shard_key: Some(key.into()),
26922            };
26923            assert_eq!(
26924                p.shard_key(),
26925                Some(key),
26926                "Placement::shard_key must return :placement :shard-key \
26927                 verbatim (got {:?}, expected Some({key:?}))",
26928                p.shard_key(),
26929            );
26930            assert_eq!(
26931                p.shard_key(),
26932                p.shard_key.as_deref(),
26933                "Placement::shard_key must byte-equal the .shard_key \
26934                 field's `.as_deref()` projection",
26935            );
26936        }
26937    }
26938
26939    #[test]
26940    fn placement_shard_key_none_when_field_is_none() {
26941        // The absent-`:shard-key` arm of the per-`:placement`
26942        // Akka-cluster-sharding accessor pin: when the typed slot is
26943        // absent — the canonical shape under `:estrategia Replicated` /
26944        // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
26945        // enforced `shard_key.is_some() == matches!(estrategia,
26946        // Sharded)` partition — [`Placement::shard_key`] must return
26947        // `None`. Pins against a future silent detour that projected
26948        // the absent slot to a `Some("")` empty-string default (the
26949        // canonical `Option<String>` → `String` collapse footgun the
26950        // sibling M2 [`crate::LimitsSpec::is_empty`] /
26951        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
26952        // already guard on the peer M2 typed-slot surfaces), a
26953        // `Some("None")` stringified-None round-trip, or a `Some` arm
26954        // whose contents were derived from a sibling slot (an
26955        // accidental fallback to `estrategia.as_str()` that read the
26956        // strategy discriminator into the key axis). Two placements
26957        // sweep the accept-set every `validate`-passing non-`Sharded`
26958        // shape lands on — `Replicated` (Erlang/OTP distributed-app
26959        // takeover) and `SingleNode` (single-node hosting).
26960        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
26961            let p = Placement {
26962                estrategia,
26963                clusters: vec!["rio".into()],
26964                affinity: None,
26965                shard_key: None,
26966            };
26967            assert!(
26968                p.shard_key().is_none(),
26969                "Placement::shard_key must return None when the typed \
26970                 slot is absent under :estrategia {estrategia:?} (got {:?})",
26971                p.shard_key(),
26972            );
26973            assert_eq!(
26974                p.shard_key(),
26975                p.shard_key.as_deref(),
26976                "Placement::shard_key must byte-equal the .shard_key \
26977                 field's `.as_deref()` projection in the absent arm",
26978            );
26979        }
26980    }
26981
26982    #[test]
26983    fn placement_shard_key_borrows_from_shard_key_storage() {
26984        // The borrow-not-copy pin: [`Placement::shard_key`] must return
26985        // an `Option<&str>` whose `Some` arm borrows from the typed
26986        // slot's own [`String`] storage — same-address invariant with
26987        // `p.shard_key.as_deref().unwrap()`. Pins against a future
26988        // silent detour that allocated a fresh `String`
26989        // (`self.shard_key.clone().map(...)` in the body would type-
26990        // check but silently drop the borrow, and every downstream
26991        // consumer that assumed the returned slice outlives `&self`
26992        // would break on a stale-reference use-after-free — the
26993        // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
26994        // gate's `Some(k)`-bound match arm reads `k: &str` under the
26995        // accessor's return type and would silently misbehave if this
26996        // accessor produced a detached copy). Peer of the sibling
26997        // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
26998        // [`WitContract::source`] / [`WitContract::destination`]
26999        // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
27000        // (6db982c) borrow-invariant pins on the mesh-slot-atom
27001        // scalar-value axes — first extension of the discipline onto
27002        // an `Option<String>`-shaped optional-scalar axis.
27003        let p = Placement {
27004            estrategia: PlacementStrategy::Sharded,
27005            clusters: vec!["rio".into()],
27006            affinity: None,
27007            shard_key: Some("tenantId".into()),
27008        };
27009        let key = p.shard_key().expect("Some arm");
27010        let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
27011        assert_eq!(
27012            key.as_ptr(),
27013            storage_slice.as_ptr(),
27014            "Placement::shard_key must borrow from the .shard_key \
27015             String's backing storage — a fresh allocation here means \
27016             the accessor no longer names the substrate-primitive typed \
27017             dispatch and every downstream consumer would silently \
27018             carry a detached copy",
27019        );
27020        assert_eq!(
27021            key.len(),
27022            storage_slice.len(),
27023            "Placement::shard_key and .shard_key.as_deref() must byte-\
27024             equal in length as well as in address",
27025        );
27026    }
27027
27028    #[test]
27029    fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
27030        // The canonical per-`:placement` M3-Adaptive-compression-hint
27031        // scalar pin: [`Placement::affinity`] must return the
27032        // `:placement :affinity` field byte-for-byte, borrowed from the
27033        // typed slot's own `Option<String>` storage. Peer of the sibling
27034        // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
27035        // pin on the sibling `Option<&str>` optional-scalar axis — same
27036        // "the substrate-primitive accessor must byte-equal the raw
27037        // field access verbatim across every author-declared value"
27038        // discipline extended to the peer per-`:placement` M3-Adaptive-
27039        // compression-hint arm. Pins against a future silent detour
27040        // that re-normalized the hint (an accidental `.to_lowercase()`
27041        // — every `:affinity` is already validated as a DNS-1123 label
27042        // upstream via [`validate_placement_affinity`], so any re-
27043        // normalization is redundant + a drift surface between the
27044        // validator and the accessor), a per-cluster alias rewrite the
27045        // operator authors on one consumer without the other, or an
27046        // accidental hint-family collapse (`low-latency` → `latency`
27047        // that dropped the qualifier prefix). Four values sweep the
27048        // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
27049        // canonical adaptive-compression-weight biases the future M4
27050        // placement engine reads.
27051        for hint in [
27052            "data-locality",
27053            "low-latency",
27054            "high-throughput",
27055            "cost-optimized",
27056        ] {
27057            let p = Placement {
27058                estrategia: PlacementStrategy::Replicated,
27059                clusters: vec!["rio".into()],
27060                affinity: Some(hint.into()),
27061                shard_key: None,
27062            };
27063            assert_eq!(
27064                p.affinity(),
27065                Some(hint),
27066                "Placement::affinity must return :placement :affinity \
27067                 verbatim (got {:?}, expected Some({hint:?}))",
27068                p.affinity(),
27069            );
27070            assert_eq!(
27071                p.affinity(),
27072                p.affinity.as_deref(),
27073                "Placement::affinity must byte-equal the .affinity \
27074                 field's `.as_deref()` projection",
27075            );
27076        }
27077    }
27078
27079    #[test]
27080    fn placement_affinity_none_when_field_is_none() {
27081        // The absent-`:affinity` arm of the per-`:placement`
27082        // M3-Adaptive-compression-hint accessor pin: when the typed
27083        // slot is absent — the canonical shape of an Aplicacao that
27084        // leaves the compression weighting up to the placement engine's
27085        // cluster-default arm — [`Placement::affinity`] must return
27086        // `None`. Pins against a future silent detour that projected
27087        // the absent slot to a `Some("")` empty-string default (the
27088        // canonical `Option<String>` → `String` collapse footgun the
27089        // sibling M2 [`crate::LimitsSpec::is_empty`] /
27090        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
27091        // already guard on the peer M2 typed-slot surfaces), a
27092        // `Some("None")` stringified-None round-trip, a `Some` arm
27093        // whose contents were derived from a sibling slot (an
27094        // accidental fallback to `estrategia.as_str()` that read the
27095        // strategy discriminator into the hint axis), or a
27096        // `Some("default")` implicit-default that would silently biases
27097        // the routing without the author having written one. Three
27098        // placements sweep the accept-set every `validate`-passing
27099        // `:affinity None` shape lands on — one per PlacementStrategy
27100        // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
27101        // with a shard-key), since `:affinity` is orthogonal to
27102        // `:estrategia` in the typed grammar.
27103        for (estrategia, shard_key) in [
27104            (PlacementStrategy::SingleNode, None),
27105            (PlacementStrategy::Replicated, None),
27106            (PlacementStrategy::Sharded, Some("tenantId".to_string())),
27107        ] {
27108            let p = Placement {
27109                estrategia,
27110                clusters: vec!["rio".into()],
27111                affinity: None,
27112                shard_key,
27113            };
27114            assert!(
27115                p.affinity().is_none(),
27116                "Placement::affinity must return None when the typed \
27117                 slot is absent under :estrategia {estrategia:?} (got {:?})",
27118                p.affinity(),
27119            );
27120            assert_eq!(
27121                p.affinity(),
27122                p.affinity.as_deref(),
27123                "Placement::affinity must byte-equal the .affinity \
27124                 field's `.as_deref()` projection in the absent arm",
27125            );
27126        }
27127    }
27128
27129    #[test]
27130    fn placement_affinity_borrows_from_affinity_storage() {
27131        // The borrow-not-copy pin: [`Placement::affinity`] must return
27132        // an `Option<&str>` whose `Some` arm borrows from the typed
27133        // slot's own [`String`] storage — same-address invariant with
27134        // `p.affinity.as_deref().unwrap()`. Pins against a future
27135        // silent detour that allocated a fresh `String`
27136        // (`self.affinity.clone().map(...)` in the body would type-
27137        // check but silently drop the borrow, and every downstream
27138        // consumer that assumed the returned slice outlives `&self`
27139        // would break on a stale-reference use-after-free — the
27140        // [`AplicacaoSpec::validate_placement`] per-hint value-shape
27141        // gate reads the accessor's `&str` return through the
27142        // [`validate_placement_affinity`] `&str` parameter and would
27143        // silently misbehave if this accessor produced a detached
27144        // copy). Peer of the sibling per-`:placement`
27145        // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
27146        // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
27147        // extends the discipline onto the sibling per-`:placement`
27148        // M3-Adaptive-compression-hint arm.
27149        let p = Placement {
27150            estrategia: PlacementStrategy::Replicated,
27151            clusters: vec!["rio".into()],
27152            affinity: Some("data-locality".into()),
27153            shard_key: None,
27154        };
27155        let hint = p.affinity().expect("Some arm");
27156        let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
27157        assert_eq!(
27158            hint.as_ptr(),
27159            storage_slice.as_ptr(),
27160            "Placement::affinity must borrow from the .affinity \
27161             String's backing storage — a fresh allocation here means \
27162             the accessor no longer names the substrate-primitive typed \
27163             dispatch and every downstream consumer would silently \
27164             carry a detached copy",
27165        );
27166        assert_eq!(
27167            hint.len(),
27168            storage_slice.len(),
27169            "Placement::affinity and .affinity.as_deref() must byte-\
27170             equal in length as well as in address",
27171        );
27172    }
27173
27174    #[test]
27175    fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
27176        // The canonical per-`:placement` distribution-strategy-scalar
27177        // pin: [`Placement::estrategia`] must return the `:placement
27178        // :estrategia` field verbatim as a [`PlacementStrategy`],
27179        // `Copy`-projected from the typed slot's own `PlacementStrategy`
27180        // storage across every variant in the closed accept-set
27181        // (`SingleNode` — Erlang/OTP distributed-app takeover;
27182        // `Replicated` — active-active across every named cluster;
27183        // `Sharded` — Akka-style hash-keyed entity distribution). Pins
27184        // against a future silent detour that re-derived the strategy
27185        // from a peer axis (an accidental fallback to
27186        // `if shard_key.is_some() { Sharded } else { Replicated }`
27187        // collapse that read the shard-key axis into the strategy
27188        // discriminator), a variant remap the operator authors on one
27189        // consumer without the other, or a stale-derive detour that
27190        // substituted [`PlacementStrategy::default`] when the field
27191        // held any explicit variant (which would silently collapse the
27192        // distinction between "author explicitly declared `:estrategia
27193        // Replicated`" and "author omitted the slot and inherited the
27194        // default" the future per-cluster override slot depends on).
27195        // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
27196        // pin on the `Copy`-return `u16` scalar axis — same "the
27197        // substrate-primitive accessor must byte-equal the raw field
27198        // access verbatim across every author-declared value" discipline
27199        // extended onto the per-`:placement` distribution-strategy
27200        // `Copy`-composite-enum scalar axis.
27201        for estrategia in [
27202            PlacementStrategy::SingleNode,
27203            PlacementStrategy::Replicated,
27204            PlacementStrategy::Sharded,
27205        ] {
27206            // Route the paired `:shard-key` fixture-builder through the
27207            // typed cross-slot invariant predicate
27208            // [`PlacementStrategy::requires_shard_key`] rather than the
27209            // [`gen_platform::IsVariant`]-derived [`PlacementStrategy::is_sharded`]
27210            // arm-identity predicate — same discipline the sibling
27211            // `placement_strategy_variants_round_trip` fixture builder now
27212            // reads through.
27213            let shard_key = estrategia
27214                .requires_shard_key()
27215                .then(|| "tenantId".to_string());
27216            let p = Placement {
27217                estrategia,
27218                clusters: vec!["rio".into()],
27219                affinity: None,
27220                shard_key,
27221            };
27222            assert_eq!(
27223                p.estrategia(),
27224                estrategia,
27225                "Placement::estrategia must return :placement :estrategia \
27226                 verbatim (got {:?}, expected {estrategia:?})",
27227                p.estrategia(),
27228            );
27229            assert_eq!(
27230                p.estrategia(),
27231                p.estrategia,
27232                "Placement::estrategia accessor and .estrategia field \
27233                 access must byte-equal — the accessor is the substrate-\
27234                 primitive typed dispatch every downstream distribution-\
27235                 strategy consumer must route through",
27236            );
27237        }
27238    }
27239
27240    #[test]
27241    fn validate_placement_reads_through_lifted_estrategia_accessor() {
27242        // Three-consumer coherence pin: the
27243        // [`AplicacaoSpec::validate_placement`]
27244        // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
27245        // `estrategia:` field (which reads through
27246        // [`Placement::estrategia`] to name the strategy the empty
27247        // `:clusters` list was declared against), the same method's
27248        // `Sharded ↔ non-Sharded` `match` partition dispatch (which
27249        // reads through [`Placement::estrategia`] to fan across the
27250        // shape-gate cascades), and the non-`Sharded`-arm
27251        // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
27252        // `estrategia:` field (which reads through
27253        // [`Placement::estrategia`] to name the strategy the declared-
27254        // but-inert `:shard-key` was authored under) must all key off
27255        // the lifted accessor, so any future rebrand on the typed
27256        // slot's reader shape lands at exactly one place. Pins the
27257        // three-site coherence by exercising each error surface end-
27258        // to-end and asserting the surfaced `estrategia:` field byte-
27259        // equals the accessor's return. Peer of the sibling per-
27260        // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
27261        // pin on the M3 mesh-slot `Copy`-return scalar axis.
27262
27263        // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
27264        // whose `estrategia:` field must byte-equal the accessor's return
27265        // for every variant in the closed accept-set.
27266        for estrategia in [
27267            PlacementStrategy::SingleNode,
27268            PlacementStrategy::Replicated,
27269            PlacementStrategy::Sharded,
27270        ] {
27271            let mut spec = three_member_spec();
27272            spec.placement.estrategia = estrategia;
27273            spec.placement.clusters = Vec::new();
27274            // Route the paired `:shard-key` spec-mutator through the typed
27275            // cross-slot invariant predicate
27276            // [`PlacementStrategy::requires_shard_key`] rather than the
27277            // [`gen_platform::IsVariant`]-derived
27278            // [`PlacementStrategy::is_sharded`] arm-identity predicate —
27279            // same discipline the sibling
27280            // `placement_strategy_variants_round_trip` and
27281            // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
27282            // fixture builders now read through.
27283            spec.placement.shard_key = estrategia
27284                .requires_shard_key()
27285                .then(|| "tenantId".to_string());
27286            let err = spec.validate().unwrap_err();
27287            match err {
27288                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
27289                    assert_eq!(
27290                        e,
27291                        spec.placement.estrategia(),
27292                        "PlacementWithoutClusters.estrategia must byte-equal \
27293                         Placement::estrategia() — the error carrier reads \
27294                         through the lifted accessor",
27295                    );
27296                }
27297                other => panic!(
27298                    "expected PlacementWithoutClusters, got {other:?} for \
27299                     estrategia={estrategia:?}"
27300                ),
27301            }
27302        }
27303
27304        // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
27305        // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
27306        // must byte-equal the accessor's return for both non-`Sharded`
27307        // strategies.
27308        for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
27309            let mut spec = three_member_spec();
27310            spec.placement.estrategia = estrategia;
27311            spec.placement.shard_key = Some("tenantId".into());
27312            let err = spec.validate().unwrap_err();
27313            match err {
27314                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
27315                    assert_eq!(
27316                        e,
27317                        spec.placement.estrategia(),
27318                        "ShardKeyOnNonSharded.estrategia must byte-equal \
27319                         Placement::estrategia() — the non-Sharded-arm \
27320                         refusal reads through the lifted accessor",
27321                    );
27322                }
27323                other => panic!(
27324                    "expected ShardKeyOnNonSharded, got {other:?} for \
27325                     estrategia={estrategia:?}"
27326                ),
27327            }
27328        }
27329    }
27330
27331    // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
27332    //
27333    // The [`Placement::clusters`] accessor lift is the second slice-return
27334    // (`&[T]`) accessor on any typed slot — sibling to the seed M2
27335    // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
27336    // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
27337    // below cover (1) the accessor's byte-equal projection against the raw
27338    // field access across the empty / singleton / cohort fixtures the
27339    // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
27340    // and the per-cluster validate loop fan between, and (2) the two-
27341    // consumer coherence of the paired pre-flight refusal probe and the
27342    // per-cluster validate loop routing through the accessor on both arms.
27343
27344    #[test]
27345    fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
27346        // The canonical per-`:placement` cluster-pool-scalar-shape pin:
27347        // [`Placement::clusters`] must return the `:placement :clusters`
27348        // typed `Vec<String>` verbatim as a `&[String]` slice-view over
27349        // the same backing buffer the raw `self.clusters.as_slice()`
27350        // field access borrows from, byte-equal across every
27351        // representative fixture in the accept-set — the empty slice
27352        // (the pre-validation sentinel every
27353        // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
27354        // the singleton slice (the minimal `SingleNode`-shape cohort),
27355        // and multi-entry cohorts (the peer `Replicated` / `Sharded`
27356        // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
27357        //
27358        // Pins against a future silent detour that returned
27359        // `&Vec<String>` (which would type-check but leak the storage-
27360        // side `Vec`'s grow/push/reserve surface no consumer of the
27361        // typed view reaches for), a fresh-allocated `Vec<String>` copy
27362        // (which would type-check via a coercion but silently break
27363        // every downstream caller that relied on the slice sharing the
27364        // backing buffer's identity), or an out-of-order or length-
27365        // drifted projection (which would silently split the paired
27366        // pre-flight `.is_empty()` refusal probe's input from the per-
27367        // cluster validate loop's traversal input).
27368        //
27369        // Peer of the sibling M2
27370        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
27371        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
27372        // `:supervisor` static-child-list axis, extended onto the M3
27373        // per-`:placement` distribution-target-list `Vec`-carry axis.
27374        let fixtures: Vec<Vec<String>> = vec![
27375            Vec::new(),
27376            vec!["rio".into()],
27377            vec!["rio".into(), "mar".into()],
27378            vec!["rio".into(), "mar".into(), "plo".into()],
27379        ];
27380        for clusters in fixtures {
27381            let p = Placement {
27382                clusters: clusters.clone(),
27383                ..Placement::default()
27384            };
27385            assert_eq!(
27386                p.clusters(),
27387                clusters.as_slice(),
27388                "Placement::clusters must return :placement :clusters \
27389                 verbatim (got {:?}, expected {:?})",
27390                p.clusters(),
27391                clusters.as_slice(),
27392            );
27393            assert_eq!(
27394                p.clusters(),
27395                p.clusters.as_slice(),
27396                "Placement::clusters accessor and .clusters.as_slice() \
27397                 field access must byte-equal — the accessor is the \
27398                 substrate-primitive typed dispatch every downstream \
27399                 cluster-pool consumer must route through",
27400            );
27401            assert_eq!(
27402                p.clusters().len(),
27403                p.clusters.len(),
27404                "Placement::clusters().len() must byte-equal \
27405                 self.clusters.len() — a length-drift would silently \
27406                 split the paired pre-flight `.is_empty()` refusal \
27407                 probe input from the per-cluster validate loop's \
27408                 traversal input",
27409            );
27410        }
27411    }
27412
27413    #[test]
27414    fn validate_placement_reads_through_lifted_clusters_accessor() {
27415        // Two-consumer coherence pin: the
27416        // [`AplicacaoSpec::validate_placement`] pre-flight
27417        // `self.placement.clusters().is_empty()` refusal probe (which
27418        // must trip [`AplicacaoError::PlacementWithoutClusters`] when
27419        // the accessor projects the empty slice) and the per-cluster
27420        // validate loop's `for c in self.placement.clusters()`
27421        // traversal (which must reach every entry in the same order
27422        // the accessor projects, so both the per-entry value-shape
27423        // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
27424        // and the duplicate-detection HashSet insert that trips
27425        // [`AplicacaoError::PlacementClusterDuplicate`] key off the
27426        // accessor's projection) must both key off the lifted
27427        // accessor, so any future rebrand on the typed slot's reader
27428        // shape lands at exactly one place. Pins the two-site
27429        // coherence by exercising each production consumer end-to-end:
27430        // (1) the `PlacementWithoutClusters` refusal under the empty
27431        // slice, (2) the `PlacementClusterInvalid` refusal fires on
27432        // the second entry of a two-cluster cohort whose head is
27433        // valid but tail is not (which requires the loop to reach the
27434        // second entry through the accessor), and (3) the
27435        // `PlacementClusterDuplicate` refusal fires on the second
27436        // entry of a two-cluster cohort that shares a name (which
27437        // requires the loop to reach both entries — a first-entry-only
27438        // projection would silently pass since the dedup HashSet has
27439        // room for the first insert).
27440        //
27441        // Peer of the sibling M2
27442        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
27443        // (bc92bce) coherence pin on the per-`:supervisor` static-
27444        // child-list axis, extended onto the M3 per-`:placement`
27445        // distribution-target-list `Vec`-carry axis.
27446
27447        // (1) Pre-flight `.is_empty()` probe: the empty slice must
27448        // trip `PlacementWithoutClusters`.
27449        let mut spec = three_member_spec();
27450        spec.placement.clusters = Vec::new();
27451        match spec.validate().unwrap_err() {
27452            AplicacaoError::PlacementWithoutClusters { .. } => {}
27453            other => panic!("expected PlacementWithoutClusters, got {other:?}"),
27454        }
27455        assert!(
27456            spec.placement.clusters().is_empty(),
27457            "the pre-flight refusal input must be the empty slice per \
27458             the accessor's projection",
27459        );
27460
27461        // (2) Per-cluster validate loop: a two-cluster cohort with an
27462        // invalid tail entry must trip `PlacementClusterInvalid` on
27463        // the tail — the loop must reach the second entry through
27464        // the accessor.
27465        let mut spec = three_member_spec();
27466        spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
27467        match spec.validate().unwrap_err() {
27468            AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
27469                assert_eq!(
27470                    cluster, "BAD_CLUSTER",
27471                    "PlacementClusterInvalid.cluster must carry the \
27472                     tail entry the loop reached through the accessor",
27473                );
27474            }
27475            other => panic!("expected PlacementClusterInvalid, got {other:?}"),
27476        }
27477        assert_eq!(
27478            spec.placement.clusters().len(),
27479            2,
27480            "the per-cluster validate loop's traversal input must be \
27481             a two-element slice per the accessor's projection",
27482        );
27483
27484        // (3) Per-cluster validate loop: a two-cluster cohort that
27485        // shares a name must trip `PlacementClusterDuplicate` on the
27486        // second entry — the loop must reach both entries through the
27487        // accessor for the dedup HashSet's second insert to collide.
27488        let mut spec = three_member_spec();
27489        spec.placement.clusters = vec!["rio".into(), "rio".into()];
27490        match spec.validate().unwrap_err() {
27491            AplicacaoError::PlacementClusterDuplicate { cluster } => {
27492                assert_eq!(
27493                    cluster, "rio",
27494                    "PlacementClusterDuplicate.cluster must carry the \
27495                     shared cluster name verbatim",
27496                );
27497            }
27498            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
27499        }
27500        assert_eq!(
27501            spec.placement.clusters().len(),
27502            2,
27503            "the per-cluster validate loop's traversal input must be \
27504             a two-element slice per the accessor's projection",
27505        );
27506    }
27507
27508    #[test]
27509    fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
27510        // The canonical per-`:membros` member-list-slice-shape pin:
27511        // [`AplicacaoSpec::membros`] must return the `:membros` typed
27512        // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
27513        // same backing buffer the raw `self.membros.as_slice()` field
27514        // access borrows from, byte-equal across every representative
27515        // fixture in the accept-set — the empty slice (the pre-
27516        // validation sentinel every [`AplicacaoError::NoMembros`]
27517        // refusal keys off), the singleton slice (the minimal one-
27518        // Servico Aplicacao shape), and multi-entry cohorts (the peer
27519        // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
27520        // load-bearing identity of the application graph).
27521        //
27522        // Pins against a future silent detour that returned
27523        // `&Vec<Membro>` (which would type-check but leak the storage-
27524        // side `Vec`'s grow/push/reserve surface no consumer of the
27525        // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
27526        // (which would type-check via a coercion but silently break
27527        // every downstream caller that relied on the slice sharing the
27528        // backing buffer's identity), or an out-of-order or length-
27529        // drifted projection (which would silently split the paired
27530        // `HashSet<&str>` name-set seed's collect input from the
27531        // pre-flight `.is_empty()` refusal probe's input from the per-
27532        // member validate loop's traversal input from the
27533        // programs.yaml emitter's per-entry fan-out loop's input from
27534        // the `feira app graph` per-member print traversal's input).
27535        //
27536        // Peer of the sibling M2
27537        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
27538        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
27539        // `:supervisor` static-child-list axis and the sibling M3
27540        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
27541        // (a6e18d7) `&[String]` byte-equal pin on the per-
27542        // `:placement` distribution-target-list axis — extends the
27543        // slice-return-accessor byte-equal-projection discipline onto
27544        // the outermost M3 mesh-slot type's per-Aplicacao member-list
27545        // `Vec`-carry axis.
27546        let fixtures: Vec<Vec<Membro>> = vec![
27547            Vec::new(),
27548            vec![membro("catalog", "^0.1")],
27549            vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
27550            vec![
27551                membro("catalog", "^0.1"),
27552                membro("cart", "^0.1"),
27553                membro("payment", "^0.2"),
27554            ],
27555        ];
27556        for membros in fixtures {
27557            let s = AplicacaoSpec {
27558                membros: membros.clone(),
27559                contratos: Vec::new(),
27560                politicas: MeshPolicy::default(),
27561                placement: Placement::default(),
27562                entrada: None,
27563            };
27564            assert_eq!(
27565                s.membros(),
27566                membros.as_slice(),
27567                "AplicacaoSpec::membros must return :membros verbatim \
27568                 (got {:?}, expected {:?})",
27569                s.membros(),
27570                membros.as_slice(),
27571            );
27572            assert_eq!(
27573                s.membros(),
27574                s.membros.as_slice(),
27575                "AplicacaoSpec::membros accessor and .membros.as_slice() \
27576                 field access must byte-equal — the accessor is the \
27577                 substrate-primitive typed dispatch every downstream \
27578                 member-list consumer must route through",
27579            );
27580            assert_eq!(
27581                s.membros().len(),
27582                s.membros.len(),
27583                "AplicacaoSpec::membros().len() must byte-equal \
27584                 self.membros.len() — a length-drift would silently \
27585                 split the paired `HashSet<&str>` name-set seed's \
27586                 collect input from the pre-flight `.is_empty()` \
27587                 refusal probe input from the per-member validate \
27588                 loop's traversal input",
27589            );
27590        }
27591    }
27592
27593    #[test]
27594    fn validate_reads_through_lifted_membros_accessor() {
27595        // Three-consumer coherence pin: the
27596        // [`AplicacaoSpec::validate_membros`] pre-flight
27597        // `self.membros().is_empty()` refusal probe (which must trip
27598        // [`AplicacaoError::NoMembros`] when the accessor projects the
27599        // empty slice), the same method's per-member validate loop's
27600        // `for m in self.membros()` traversal (which must reach every
27601        // entry in the same order the accessor projects, so both the
27602        // per-entry empty-`:caixa` gate that trips
27603        // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
27604        // detection `insert_first_seen` that trips
27605        // [`AplicacaoError::MembroDuplicate`] key off the accessor's
27606        // projection), and the peer [`AplicacaoSpec::validate`]'s
27607        // `HashSet<&str>` name-set seed's
27608        // `self.membros().iter().map(Membro::nome).collect()` collect
27609        // input (which every `:contratos` `:de` / `:para` membership
27610        // lookup rejects an unknown name against) must all three key
27611        // off the lifted accessor, so any future rebrand on the typed
27612        // slot's reader shape lands at exactly one place. Pins the
27613        // three-site coherence by exercising each production consumer
27614        // end-to-end: (1) the `NoMembros` refusal under the empty
27615        // slice, (2) the `MembroCaixaEmpty` refusal fires on the
27616        // second entry of a two-member cohort whose head is valid but
27617        // tail has an empty `:caixa` (which requires the loop to
27618        // reach the second entry through the accessor), and (3) the
27619        // `MembroDuplicate` refusal fires on the second entry of a
27620        // two-member cohort that shares a `:caixa` name (which
27621        // requires the loop to reach both entries through the
27622        // accessor for the dedup HashSet's second insert to collide).
27623        //
27624        // Peer of the sibling M2
27625        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
27626        // (bc92bce) coherence pin on the per-`:supervisor` static-
27627        // child-list axis and the sibling M3
27628        // `validate_placement_reads_through_lifted_clusters_accessor`
27629        // (a6e18d7) coherence pin on the per-`:placement` distribution-
27630        // target-list axis — extends the slice-return-accessor
27631        // multi-consumer coherence discipline onto the outermost M3
27632        // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
27633
27634        // (1) Pre-flight `.is_empty()` probe: the empty slice must
27635        // trip `NoMembros`.
27636        let mut spec = three_member_spec();
27637        spec.membros = Vec::new();
27638        assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
27639        assert!(
27640            spec.membros().is_empty(),
27641            "the pre-flight refusal input must be the empty slice per \
27642             the accessor's projection",
27643        );
27644
27645        // (2) Per-member validate loop: a two-member cohort with an
27646        // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
27647        // the tail — the loop must reach the second entry through
27648        // the accessor.
27649        let mut spec = three_member_spec();
27650        spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
27651        assert_eq!(
27652            spec.validate().unwrap_err(),
27653            AplicacaoError::MembroCaixaEmpty,
27654        );
27655        assert_eq!(
27656            spec.membros().len(),
27657            2,
27658            "the per-member validate loop's traversal input must be \
27659             a two-element slice per the accessor's projection",
27660        );
27661
27662        // (3) Per-member validate loop: a two-member cohort that
27663        // shares a `:caixa` name must trip `MembroDuplicate` on the
27664        // second entry — the loop must reach both entries through the
27665        // accessor for the dedup HashSet's second insert to collide.
27666        let mut spec = three_member_spec();
27667        spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
27668        match spec.validate().unwrap_err() {
27669            AplicacaoError::MembroDuplicate { caixa } => {
27670                assert_eq!(
27671                    caixa, "catalog",
27672                    "MembroDuplicate.caixa must carry the shared \
27673                     member name verbatim",
27674                );
27675            }
27676            other => panic!("expected MembroDuplicate, got {other:?}"),
27677        }
27678        assert_eq!(
27679            spec.membros().len(),
27680            2,
27681            "the per-member validate loop's traversal input must be \
27682             a two-element slice per the accessor's projection",
27683        );
27684    }
27685
27686    #[test]
27687    fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
27688        // The canonical per-`:contratos` contract-list-slice-shape pin:
27689        // [`AplicacaoSpec::contratos`] must return the `:contratos`
27690        // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
27691        // slice-view over the same backing buffer the raw
27692        // `self.contratos.as_slice()` field access borrows from, byte-
27693        // equal across every representative fixture in the accept-set —
27694        // the empty slice (the pre-validation "internal-only mesh" shape
27695        // an Aplicacao whose members exchange no typed edges renders
27696        // through), the singleton slice (the minimal one-edge Aplicacao
27697        // shape), and multi-entry cohorts (the peer multi-edge shapes
27698        // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
27699        // of the application graph).
27700        //
27701        // Pins against a future silent detour that returned
27702        // `&Vec<WitContract>` (which would type-check but leak the
27703        // storage-side `Vec`'s grow/push/reserve surface no consumer of
27704        // the typed view reaches for), a fresh-allocated
27705        // `Vec<WitContract>` copy (which would type-check via a coercion
27706        // but silently break every downstream caller that relied on the
27707        // slice sharing the backing buffer's identity), or an out-of-
27708        // order or length-drifted projection (which would silently split
27709        // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
27710        // seed's traversal input from the `detect_sync_cycles` per-edge
27711        // adjacency-list seed's traversal input from the
27712        // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
27713        // BTreeMap grouping loop's traversal input from the
27714        // `feira app graph` per-contract print traversal's input).
27715        //
27716        // Peer of the immediately-adjacent sibling M3
27717        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
27718        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
27719        // node-list axis, the sibling M3
27720        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
27721        // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
27722        // distribution-target-list axis, and the sibling M2
27723        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
27724        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
27725        // `:supervisor` static-child-list axis — extends the slice-
27726        // return-accessor byte-equal-projection discipline onto the
27727        // outermost M3 mesh-slot type's per-Aplicacao contract-list
27728        // `Vec`-carry axis, closing the last unlifted per-
27729        // `AplicacaoSpec` `Vec`-carry axis.
27730        let fixtures: Vec<Vec<WitContract>> = vec![
27731            Vec::new(),
27732            vec![contract_http("cart", "catalog", "/products/:id")],
27733            vec![
27734                contract_http("cart", "catalog", "/products/:id"),
27735                contract_http("cart", "payment", "/charge"),
27736            ],
27737            vec![
27738                contract_http("cart", "catalog", "/products/:id"),
27739                contract_http("cart", "payment", "/charge"),
27740                contract_http("payment", "catalog", "/audit"),
27741            ],
27742        ];
27743        for contratos in fixtures {
27744            let s = AplicacaoSpec {
27745                membros: vec![
27746                    membro("catalog", "^0.1"),
27747                    membro("cart", "^0.1"),
27748                    membro("payment", "^0.2"),
27749                ],
27750                contratos: contratos.clone(),
27751                politicas: MeshPolicy::default(),
27752                placement: Placement::default(),
27753                entrada: None,
27754            };
27755            assert_eq!(
27756                s.contratos(),
27757                contratos.as_slice(),
27758                "AplicacaoSpec::contratos must return :contratos verbatim \
27759                 (got {:?}, expected {:?})",
27760                s.contratos(),
27761                contratos.as_slice(),
27762            );
27763            assert_eq!(
27764                s.contratos(),
27765                s.contratos.as_slice(),
27766                "AplicacaoSpec::contratos accessor and \
27767                 .contratos.as_slice() field access must byte-equal — \
27768                 the accessor is the substrate-primitive typed dispatch \
27769                 every downstream contract-list consumer must route \
27770                 through",
27771            );
27772            assert_eq!(
27773                s.contratos().len(),
27774                s.contratos.len(),
27775                "AplicacaoSpec::contratos().len() must byte-equal \
27776                 self.contratos.len() — a length-drift would silently \
27777                 split the paired per-edge validate-loop's traversal \
27778                 input from the sync-cycle adjacency-list seed's \
27779                 traversal input from the cilium_network_policies \
27780                 per-`(:de, :para)` BTreeMap grouping loop's traversal \
27781                 input from the `feira app graph` per-contract print \
27782                 traversal's input",
27783            );
27784        }
27785    }
27786
27787    #[test]
27788    fn validate_reads_through_lifted_contratos_accessor() {
27789        // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
27790        // per-`:contratos` validate-loop's `for c in self.contratos()`
27791        // traversal (which must reach every entry in the same order the
27792        // accessor projects, so both the per-entry
27793        // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
27794        // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
27795        // dedup `HashSet` insert key off the accessor's projection),
27796        // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
27797        // `for c in self.contratos()` adjacency-list seed (which drives
27798        // the sync-subgraph deadlock-detection gate via
27799        // [`AplicacaoError::SyncCycle`]), and the peer
27800        // [`caixa_mesh::cilium_network_policies`]'s
27801        // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
27802        // grouping loop (which drives the per-CNP fan-out) must all
27803        // three key off the lifted accessor, so any future rebrand on
27804        // the typed slot's reader shape lands at exactly one place. Pins
27805        // the three-site coherence by exercising the two caixa-core
27806        // production consumers end-to-end: (1) the empty-`:contratos`
27807        // slice must validate without a per-edge diagnostic (the
27808        // per-edge loop is a no-op under the empty projection), (2) the
27809        // `ContratoMemberMissing` refusal fires on the second entry of a
27810        // two-edge cohort whose head references a valid member but tail
27811        // references a phantom name (which requires the loop to reach
27812        // the second entry through the accessor), and (3) the
27813        // `SyncCycle` refusal fires on a self-referential two-edge
27814        // cohort through the sync-cycle detector's peer projection
27815        // (which requires the detector to iterate the accessor's
27816        // projection to add the back-edge to its adjacency list).
27817        //
27818        // Peer of the sibling M3
27819        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
27820        // three-consumer coherence pin on the per-`:membros` node-list
27821        // axis and the sibling M3
27822        // `validate_placement_reads_through_lifted_clusters_accessor`
27823        // (a6e18d7) coherence pin on the per-`:placement` distribution-
27824        // target-list axis — extends the slice-return-accessor multi-
27825        // consumer coherence discipline onto the outermost M3 mesh-slot
27826        // type's per-Aplicacao contract-list `Vec`-carry axis.
27827
27828        // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
27829        // and no per-edge diagnostic surfaces. Validate succeeds on
27830        // the well-formed `:membros` head.
27831        let mut spec = three_member_spec();
27832        spec.contratos = Vec::new();
27833        assert!(
27834            spec.validate().is_ok(),
27835            "empty :contratos must validate — the per-edge loop is a \
27836             no-op under the accessor's empty projection",
27837        );
27838        assert!(
27839            spec.contratos().is_empty(),
27840            "the per-edge validate loop's traversal input must be the \
27841             empty slice per the accessor's projection",
27842        );
27843
27844        // (2) Per-edge validate loop: a two-edge cohort whose tail
27845        // references a phantom `:para` member must trip
27846        // `ContratoMemberMissing` on the tail — the loop must reach
27847        // the second entry through the accessor for the membership
27848        // lookup to fail on the phantom name.
27849        let mut spec = three_member_spec();
27850        spec.contratos = vec![
27851            contract_http("cart", "catalog", "/products/:id"),
27852            contract_http("cart", "phantom", "/x"),
27853        ];
27854        let err = spec.validate().unwrap_err();
27855        assert!(
27856            matches!(
27857                err,
27858                AplicacaoError::ContratoMemberMissing { ref caixa }
27859                    if caixa == "phantom"
27860            ),
27861            "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
27862        );
27863        assert_eq!(
27864            spec.contratos().len(),
27865            2,
27866            "the per-edge validate loop's traversal input must be \
27867             a two-element slice per the accessor's projection",
27868        );
27869
27870        // (3) Sync-cycle detector: a two-edge synchronous cohort
27871        // whose second edge closes the sync-subgraph back onto the
27872        // first must trip [`AplicacaoError::ContratoCycle`] — the
27873        // detector must iterate the accessor's projection to add
27874        // both edges to its adjacency list, so a length-drift on
27875        // the accessor's projection would silently disagree with
27876        // the sync-cycle detector on which edge closes the loop.
27877        // Peer projection to the `validate` per-edge loop above:
27878        // the sync-cycle detector routes through the same lifted
27879        // accessor, so a rebrand of the reader shape lands at one
27880        // place. Uses a two-edge cohort (cart → catalog → cart)
27881        // because the per-edge `ContratoSelfLoop` gate fires before
27882        // the sync-cycle detector on a single self-referential edge
27883        // (`cart → cart`) — the cycle-detector's input must be a
27884        // multi-edge cohort for its per-edge traversal input to be
27885        // observably wider than the per-edge validate loop's input.
27886        let mut spec = three_member_spec();
27887        spec.contratos = vec![
27888            contract_http("cart", "catalog", "/products/:id"),
27889            contract_http("catalog", "cart", "/callback"),
27890        ];
27891        let err = spec.validate().unwrap_err();
27892        assert!(
27893            matches!(err, AplicacaoError::ContratoCycle { .. }),
27894            "expected ContratoCycle from the sync-cycle detector on a \
27895             two-edge back-edge cohort, got {err:?}",
27896        );
27897        assert_eq!(
27898            spec.contratos().len(),
27899            2,
27900            "the sync-cycle detector's traversal input must be a \
27901             two-element slice per the accessor's projection",
27902        );
27903    }
27904
27905    #[test]
27906    fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
27907        // The canonical per-`:politicas` outer-composite-reference-shape
27908        // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
27909        // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
27910        // the same backing storage the raw `&self.politicas` field
27911        // access borrows from, byte-equal across every representative
27912        // fixture in the accept-set — the default `MeshPolicy` (the
27913        // author-empty "no policy on any axis" shape whose
27914        // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
27915        // shapes carrying one axis at a time
27916        // (`{mtls_required, timeout, retries, circuit_breaker,
27917        // rate_limit}` — the minimal five-axis fan-out over the
27918        // per-axis lifted accessor family every downstream mesh-artifact
27919        // emitter dispatches on), and the multi-axis composite (the
27920        // canonical `three_member_spec` fixture's `{timeout, retries,
27921        // mtls_required}` triple — the load-bearing shape every
27922        // Aplicacao-scoped fixture in this suite constructs).
27923        //
27924        // Pins against a future silent detour that returned a fresh-
27925        // cloned `MeshPolicy` copy (which would type-check via a `Clone`
27926        // impl but silently break every downstream caller that relied
27927        // on the reference sharing the composite's backing identity), a
27928        // reference to an operator-resolved overlay (the future
27929        // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
27930        // acknowledges — its resolution must land at exactly this
27931        // accessor body, not silently divert the raw slot away from a
27932        // second consumer), or an axis-shuffled projection (a future
27933        // detour that swapped `timeout` and `retries` through the
27934        // accessor would silently split the paired `validate_politicas`
27935        // per-axis bracket-dispatch's traversal input from the peer
27936        // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
27937        // emitter's fan-out input from the peer
27938        // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
27939        // overlay emitter's fan-out input).
27940        //
27941        // Peer of the sibling M3
27942        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
27943        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
27944        // node-list `Vec`-carry axis and the sibling M3
27945        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
27946        // (0dcc926) `&[WitContract]` byte-equal pin on the per-
27947        // `:contratos` edge-list `Vec`-carry axis — extends the outer-
27948        // accessor byte-equal-projection discipline onto the outermost
27949        // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
27950        // reference axis, the first `&Composite`-return accessor on the
27951        // outer [`AplicacaoSpec`] type.
27952        let fixtures: Vec<MeshPolicy> = vec![
27953            MeshPolicy::default(),
27954            MeshPolicy {
27955                mtls_required: Some(true),
27956                ..MeshPolicy::default()
27957            },
27958            MeshPolicy {
27959                mtls_required: Some(false),
27960                ..MeshPolicy::default()
27961            },
27962            MeshPolicy {
27963                timeout: Some(Duration::from_secs(30)),
27964                ..MeshPolicy::default()
27965            },
27966            MeshPolicy {
27967                retries: Some(3),
27968                ..MeshPolicy::default()
27969            },
27970            MeshPolicy {
27971                circuit_breaker: Some(CircuitBreaker {
27972                    max_failures: 5,
27973                    window: Duration::from_secs(30),
27974                }),
27975                ..MeshPolicy::default()
27976            },
27977            MeshPolicy {
27978                rate_limit: Some(RateLimit {
27979                    rate: 100,
27980                    window: Duration::from_secs(1),
27981                }),
27982                ..MeshPolicy::default()
27983            },
27984            MeshPolicy {
27985                timeout: Some(Duration::from_secs(30)),
27986                retries: Some(3),
27987                mtls_required: Some(true),
27988                ..MeshPolicy::default()
27989            },
27990        ];
27991        for politicas in fixtures {
27992            let s = AplicacaoSpec {
27993                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
27994                contratos: Vec::new(),
27995                politicas: politicas.clone(),
27996                placement: Placement::default(),
27997                entrada: None,
27998            };
27999            assert_eq!(
28000                *s.politicas(),
28001                politicas,
28002                "AplicacaoSpec::politicas must return :politicas verbatim \
28003                 (got {:?}, expected {:?})",
28004                s.politicas(),
28005                politicas,
28006            );
28007            assert!(
28008                std::ptr::eq(s.politicas(), &s.politicas),
28009                "AplicacaoSpec::politicas accessor and &self.politicas \
28010                 field access must borrow the same backing storage — \
28011                 the accessor is the substrate-primitive typed dispatch \
28012                 every downstream mesh-policy composite consumer must \
28013                 route through, and a reference-identity split would \
28014                 silently break every consumer that relied on the \
28015                 borrow sharing the composite's storage",
28016            );
28017            assert_eq!(
28018                s.politicas().is_empty(),
28019                s.politicas.is_empty(),
28020                "AplicacaoSpec::politicas().is_empty() must byte-equal \
28021                 self.politicas.is_empty() — an emptiness-drift would \
28022                 silently split the paired `validate_politicas` \
28023                 per-axis bracket-dispatch's seed from the peer \
28024                 caixa-mesh CNP mTLS-overlay emitter's key from the \
28025                 peer caixa-mesh HTTPRoute timeout+retry overlay \
28026                 emitter's key",
28027            );
28028        }
28029    }
28030
28031    #[test]
28032    fn validate_politicas_reads_through_lifted_politicas_accessor() {
28033        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
28034        // per-axis bracket-dispatch seed (`let p = self.politicas();`,
28035        // followed by the per-axis fan-out `p.timeout()` /
28036        // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
28037        // the lifted axis-level accessor family) must key off the
28038        // lifted outer accessor, so any future rebrand on the typed
28039        // slot's outer-composite reader shape lands at exactly one
28040        // place. Pins the multi-axis coherence by exercising each
28041        // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
28042        // a `Some(Duration::ZERO)` timeout under the outer accessor's
28043        // reference projection, (2) `PolicyRetriesZero` fires on a
28044        // `Some(0)` retries under the same projection, and (3) an
28045        // empty [`MeshPolicy::default`] passes `validate_politicas` —
28046        // the outer accessor's reference-projection reaches every
28047        // per-axis branch without silently short-circuiting any.
28048        //
28049        // Peer of the sibling M3
28050        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
28051        // three-consumer coherence pin on the per-`:membros` node-list
28052        // axis and the sibling M3
28053        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
28054        // three-consumer coherence pin on the per-`:contratos`
28055        // edge-list axis — extends the multi-consumer coherence
28056        // discipline onto the outermost M3 mesh-slot type's per-
28057        // Aplicacao mesh-policy composite-reference axis, the first
28058        // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
28059        // type.
28060
28061        // (1) `PolicyTimeoutZero` refusal under the outer accessor's
28062        // reference projection: a `Some(Duration::ZERO)` timeout must
28063        // trip the zero-floor gate. The bracket-dispatch's first arm
28064        // reads `p.timeout()` on the reference returned by the outer
28065        // accessor.
28066        let mut spec = three_member_spec();
28067        spec.politicas.timeout = Some(Duration::ZERO);
28068        spec.politicas.retries = None;
28069        spec.politicas.circuit_breaker = None;
28070        spec.politicas.rate_limit = None;
28071        assert_eq!(
28072            spec.validate().unwrap_err(),
28073            AplicacaoError::PolicyTimeoutZero,
28074        );
28075        assert!(
28076            std::ptr::eq(spec.politicas(), &spec.politicas),
28077            "the `validate_politicas` per-axis bracket-dispatch's \
28078             traversal input must be the same backing composite the \
28079             accessor's reference projection borrows from",
28080        );
28081
28082        // (2) `PolicyRetriesZero` refusal under the outer accessor's
28083        // reference projection: a `Some(0)` retries must trip the
28084        // zero-floor gate. The bracket-dispatch's second arm reads
28085        // `p.retries()` on the reference returned by the outer accessor.
28086        let mut spec = three_member_spec();
28087        spec.politicas.timeout = None;
28088        spec.politicas.retries = Some(0);
28089        spec.politicas.circuit_breaker = None;
28090        spec.politicas.rate_limit = None;
28091        assert_eq!(
28092            spec.validate().unwrap_err(),
28093            AplicacaoError::PolicyRetriesZero,
28094        );
28095
28096        // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
28097        // — every per-axis arm short-circuits on `None`, so the outer
28098        // accessor's reference projection reaches the fall-through
28099        // `Ok(())` without any per-axis refusal firing.
28100        let mut spec = three_member_spec();
28101        spec.politicas = MeshPolicy::default();
28102        assert!(
28103            spec.validate().is_ok(),
28104            "an empty `MeshPolicy` must pass `validate_politicas` — \
28105             every per-axis arm short-circuits on `None` under the \
28106             outer accessor's reference projection",
28107        );
28108        assert!(
28109            spec.politicas().is_empty(),
28110            "the outer accessor's reference projection must be the \
28111             empty composite per the `MeshPolicy::default()` fixture",
28112        );
28113    }
28114
28115    #[test]
28116    #[allow(clippy::too_many_lines)]
28117    fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
28118        // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
28119        // per-axis bracket-dispatch's `:timeout` and `:retries` arms
28120        // must both key off the lifted axis-level accessors
28121        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
28122        // the peer `:circuit-breaker` / `:rate-limit` arms already
28123        // routing through [`MeshPolicy::circuit_breaker`] /
28124        // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
28125        // per axis on the substrate primitive" shape at the fan-out
28126        // (four axes, four accessors, no raw-field-access site
28127        // anywhere on the bracket-dispatch). Pins the per-axis
28128        // coherence at the accept-set boundaries the bracket carves:
28129        //   1. accessor byte-equal to raw field on every representative
28130        //      accept-set value (`None`, sub-cap, at-cap, past-cap
28131        //      sentinel) — a future accessor drift that no longer
28132        //      shipped the raw slot verbatim would surface here,
28133        //   2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
28134        //      routed through the accessor's projection, proving the
28135        //      first arm reads through the accessor rather than a
28136        //      silent-detour peer-axis field access,
28137        //   3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
28138        //      through the accessor's projection, proving the second
28139        //      arm reads through the accessor,
28140        //   4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
28141        //      passes validate under the accessor projection (paired
28142        //      with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
28143        //      sibling axis), pinning the upper-boundary accept-arm
28144        //      also routes through the accessor.
28145        //
28146        // Peer of the sibling M3
28147        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
28148        // outer-composite-reference coherence pin (which asserts the
28149        // `let p = self.politicas()` seed); extends the discipline onto
28150        // the per-axis fan-out layer that consumes the seed's
28151        // reference. Same shape as
28152        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
28153        // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
28154        // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
28155        // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
28156
28157        // (1) Accessor byte-equal to raw field on the `:timeout` axis
28158        // across the accept-set boundaries the bracket dispatch's
28159        // three-arm gate carves out
28160        // ([`crate::render::require_positive_canonical_bounded_duration`]
28161        // — zero-floor + canonical-form + upper-cap).
28162        for timeout in [
28163            None,
28164            Some(Duration::ZERO),
28165            Some(Duration::from_millis(1)),
28166            Some(POLICY_TIMEOUT_MAX),
28167        ] {
28168            let p = MeshPolicy {
28169                timeout,
28170                ..MeshPolicy::default()
28171            };
28172            assert_eq!(
28173                p.timeout(),
28174                p.timeout,
28175                "MeshPolicy::timeout accessor must byte-equal the raw \
28176                 .timeout field across every accept-set boundary the \
28177                 validate_politicas :timeout arm carves out — a drift \
28178                 here would silently split the validate bracket's arm \
28179                 from the peer caixa-mesh HTTPRoute timeout-overlay \
28180                 emitter's read",
28181            );
28182        }
28183
28184        // (2) Accessor byte-equal to raw field on the `:retries` axis
28185        // across the accept-set boundaries the bracket dispatch's
28186        // two-arm gate carves out
28187        // ([`crate::render::require_positive_bounded_u32`] — zero-floor
28188        // + upper-cap).
28189        for retries in [
28190            None,
28191            Some(0u32),
28192            Some(1u32),
28193            Some(POLICY_RETRIES_MAX),
28194            Some(POLICY_RETRIES_MAX + 1),
28195            Some(u32::MAX),
28196        ] {
28197            let p = MeshPolicy {
28198                retries,
28199                ..MeshPolicy::default()
28200            };
28201            assert_eq!(
28202                p.retries(),
28203                p.retries,
28204                "MeshPolicy::retries accessor must byte-equal the raw \
28205                 .retries field across every accept-set boundary the \
28206                 validate_politicas :retries arm carves out — a drift \
28207                 here would silently split the validate bracket's arm \
28208                 from the peer caixa-mesh HTTPRoute retry-overlay \
28209                 emitter's read",
28210            );
28211        }
28212
28213        // (3) `PolicyTimeoutZero` fires on the accessor-projected
28214        // zero-floor boundary. A silent detour that no longer read
28215        // through `p.timeout()` (a peer-axis field read, an accidental
28216        // Option::and-then chain that collapsed the None arm to Some,
28217        // an accessor rebrand that clamped the return through the
28218        // upper cap) would fail to refuse here.
28219        let mut spec = three_member_spec();
28220        spec.politicas.timeout = Some(Duration::ZERO);
28221        spec.politicas.retries = None;
28222        spec.politicas.circuit_breaker = None;
28223        spec.politicas.rate_limit = None;
28224        assert_eq!(
28225            spec.politicas().timeout(),
28226            Some(Duration::ZERO),
28227            "the accessor projection must reflect the fixture's \
28228             `Some(Duration::ZERO)` :timeout verbatim",
28229        );
28230        assert_eq!(
28231            spec.validate().unwrap_err(),
28232            AplicacaoError::PolicyTimeoutZero,
28233            "the validate_politicas :timeout zero-floor arm must fire \
28234             through the lifted accessor's projection — a silent \
28235             detour to a peer-axis field would fail to refuse",
28236        );
28237
28238        // (4) `PolicyRetriesZero` fires on the accessor-projected
28239        // zero-floor boundary on the sibling `:retries` axis.
28240        let mut spec = three_member_spec();
28241        spec.politicas.timeout = None;
28242        spec.politicas.retries = Some(0);
28243        spec.politicas.circuit_breaker = None;
28244        spec.politicas.rate_limit = None;
28245        assert_eq!(
28246            spec.politicas().retries(),
28247            Some(0),
28248            "the accessor projection must reflect the fixture's \
28249             `Some(0)` :retries verbatim",
28250        );
28251        assert_eq!(
28252            spec.validate().unwrap_err(),
28253            AplicacaoError::PolicyRetriesZero,
28254            "the validate_politicas :retries zero-floor arm must fire \
28255             through the lifted accessor's projection — a silent \
28256             detour to a peer-axis field would fail to refuse",
28257        );
28258
28259        // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
28260        // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
28261        // must pass validate under the accessor projection — pins the
28262        // upper-boundary accept-arm also routes through the lifted
28263        // accessor (a drift that clamped or short-circuited at the
28264        // upper boundary would fail the whole-spec validate here).
28265        let mut spec = three_member_spec();
28266        spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
28267        spec.politicas.retries = Some(POLICY_RETRIES_MAX);
28268        spec.politicas.circuit_breaker = None;
28269        spec.politicas.rate_limit = None;
28270        assert_eq!(
28271            spec.politicas().timeout(),
28272            Some(POLICY_TIMEOUT_MAX),
28273            "the accessor projection must reflect the fixture's \
28274             at-cap :timeout verbatim",
28275        );
28276        assert_eq!(
28277            spec.politicas().retries(),
28278            Some(POLICY_RETRIES_MAX),
28279            "the accessor projection must reflect the fixture's \
28280             at-cap :retries verbatim",
28281        );
28282        assert!(
28283            spec.validate().is_ok(),
28284            "at-cap :timeout + :retries must pass validate under the \
28285             accessor projection — the upper-boundary accept-arm on \
28286             both axes routes through the lifted accessor",
28287        );
28288    }
28289
28290    #[test]
28291    fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
28292        // The canonical per-`:placement` outer-composite-reference-shape
28293        // pin: [`AplicacaoSpec::placement`] must return the `:placement`
28294        // typed `Placement` verbatim as a `&Placement` reference over the
28295        // same backing storage the raw `&self.placement` field access
28296        // borrows from, byte-equal across every representative fixture in
28297        // the accept-set — the default `Placement` (the substrate seed
28298        // shape whose [`PlacementStrategy::default`] evaluates to
28299        // `SingleNode` with an empty `:clusters` pool and both
28300        // optional-scalar axes `None`), and every canonical strategy /
28301        // cluster-pool / optional-scalar combination the
28302        // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
28303        // three [`PlacementStrategy`] variants — `SingleNode`,
28304        // `Replicated`, `Sharded` — cross-projected with a non-empty
28305        // `:clusters` pool and, on the `Sharded` arm, a non-empty
28306        // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
28307        // canonical `three_member_spec` `Replicated` fixture's
28308        // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
28309        //
28310        // Pins against a future silent detour that returned a fresh-
28311        // cloned `Placement` copy (which would type-check via a `Clone`
28312        // impl but silently break every downstream caller that relied on
28313        // the reference sharing the composite's backing identity), a
28314        // reference to an operator-resolved overlay (the future per-
28315        // cluster `:placement-overrides` slot MESH-COMPOSITION §V
28316        // acknowledges — its resolution must land at exactly this
28317        // accessor body, not silently divert the raw slot away from a
28318        // second consumer), or an axis-shuffled projection (a future
28319        // detour that swapped `clusters` and `affinity` through the
28320        // accessor would silently split the paired `validate_placement`
28321        // per-axis bracket-dispatch's traversal input from the peer
28322        // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
28323        // programs.yaml distribution-annotation emitter's fan-out input
28324        // from the peer `feira app graph` per-Aplicacao print line's
28325        // input).
28326        //
28327        // Peer of the sibling M3
28328        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
28329        // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
28330        // outer mesh-policy composite-reference axis, and of the sibling
28331        // slice-return `aplicacao_spec_membros_returns_membros_slice_
28332        // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
28333        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
28334        // across_permutations` (0dcc926) `&[WitContract]` pins — extends
28335        // the outer-accessor byte-equal-projection discipline onto the
28336        // outermost M3 mesh-slot type's per-Aplicacao distribution
28337        // composite-reference axis, the second `&Composite`-return
28338        // accessor on the outer [`AplicacaoSpec`] type.
28339        let fixtures: Vec<Placement> = vec![
28340            Placement::default(),
28341            Placement {
28342                estrategia: PlacementStrategy::SingleNode,
28343                clusters: vec!["rio".into()],
28344                affinity: None,
28345                shard_key: None,
28346            },
28347            Placement {
28348                estrategia: PlacementStrategy::Replicated,
28349                clusters: vec!["rio".into(), "mar".into()],
28350                affinity: None,
28351                shard_key: None,
28352            },
28353            Placement {
28354                estrategia: PlacementStrategy::Replicated,
28355                clusters: vec!["rio".into(), "mar".into()],
28356                affinity: Some("data-locality".into()),
28357                shard_key: None,
28358            },
28359            Placement {
28360                estrategia: PlacementStrategy::Sharded,
28361                clusters: vec!["rio".into(), "mar".into()],
28362                affinity: None,
28363                shard_key: Some("tenantId".into()),
28364            },
28365            Placement {
28366                estrategia: PlacementStrategy::Sharded,
28367                clusters: vec!["rio".into(), "mar".into(), "sol".into()],
28368                affinity: Some("low-latency".into()),
28369                shard_key: Some("metadata.tenantId".into()),
28370            },
28371        ];
28372        for placement in fixtures {
28373            let s = AplicacaoSpec {
28374                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
28375                contratos: Vec::new(),
28376                politicas: MeshPolicy::default(),
28377                placement: placement.clone(),
28378                entrada: None,
28379            };
28380            assert_eq!(
28381                *s.placement(),
28382                placement,
28383                "AplicacaoSpec::placement must return :placement verbatim \
28384                 (got {:?}, expected {:?})",
28385                s.placement(),
28386                placement,
28387            );
28388            assert!(
28389                std::ptr::eq(s.placement(), &s.placement),
28390                "AplicacaoSpec::placement accessor and &self.placement \
28391                 field access must borrow the same backing storage — the \
28392                 accessor is the substrate-primitive typed dispatch every \
28393                 downstream distribution-composite consumer must route \
28394                 through, and a reference-identity split would silently \
28395                 break every consumer that relied on the borrow sharing \
28396                 the composite's storage",
28397            );
28398            assert_eq!(
28399                s.placement().estrategia(),
28400                s.placement.estrategia,
28401                "AplicacaoSpec::placement().estrategia() must byte-equal \
28402                 self.placement.estrategia — a strategy-drift would \
28403                 silently split the paired `validate_placement` \
28404                 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
28405                 peer caixa-mesh programs.yaml `placement.estrategia` \
28406                 emitter's key from the peer `feira app graph` printer's \
28407                 strategy label",
28408            );
28409            assert_eq!(
28410                s.placement().clusters(),
28411                s.placement.clusters.as_slice(),
28412                "AplicacaoSpec::placement().clusters() must byte-equal \
28413                 self.placement.clusters — a cluster-pool drift would \
28414                 silently split the paired `validate_placement` \
28415                 pre-flight `.is_empty()` refusal probe's traversal from \
28416                 the peer caixa-mesh programs.yaml `placement.clusters` \
28417                 emitter's fan-out from the peer `feira app graph` \
28418                 printer's cluster list",
28419            );
28420        }
28421    }
28422
28423    #[test]
28424    fn validate_placement_reads_through_lifted_placement_accessor() {
28425        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
28426        // per-axis bracket-dispatch seed (`let p = self.placement();`,
28427        // followed by the per-axis fan-out `p.clusters()` /
28428        // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
28429        // lifted axis-level accessor family) must key off the lifted
28430        // outer accessor, so any future rebrand on the typed slot's
28431        // outer-composite reader shape lands at exactly one place. Pins
28432        // the multi-axis coherence by exercising each per-axis refusal
28433        // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
28434        // `:clusters` pool under the outer accessor's reference
28435        // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
28436        // strategy with a `None` `:shard-key` under the same projection,
28437        // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
28438        // with a `Some` `:shard-key` under the same projection, and
28439        // (4) the canonical `three_member_spec` `Replicated` fixture
28440        // passes `validate_placement` under the outer accessor's
28441        // reference projection — the accessor's reference-projection
28442        // reaches every per-axis branch (cluster-pool refusal, `Sharded`
28443        // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
28444        // without silently short-circuiting any.
28445        //
28446        // Peer of the sibling M3
28447        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
28448        // (534dc21) multi-axis coherence pin on the per-`:politicas`
28449        // outer mesh-policy composite-reference axis — extends the
28450        // multi-consumer coherence discipline onto the outermost M3
28451        // mesh-slot type's per-Aplicacao distribution composite-
28452        // reference axis, the second `&Composite`-return accessor on
28453        // the outer [`AplicacaoSpec`] type.
28454
28455        // (1) `PlacementWithoutClusters` refusal under the outer
28456        // accessor's reference projection: an empty `:clusters` pool
28457        // must trip the pre-flight refusal probe. The bracket-dispatch's
28458        // first arm reads `p.clusters()` on the reference returned by
28459        // the outer accessor.
28460        let mut spec = three_member_spec();
28461        spec.placement.clusters = Vec::new();
28462        assert_eq!(
28463            spec.validate().unwrap_err(),
28464            AplicacaoError::PlacementWithoutClusters {
28465                estrategia: PlacementStrategy::Replicated,
28466            },
28467        );
28468        assert!(
28469            std::ptr::eq(spec.placement(), &spec.placement),
28470            "the `validate_placement` per-axis bracket-dispatch's \
28471             traversal input must be the same backing composite the \
28472             accessor's reference projection borrows from",
28473        );
28474
28475        // (2) `ShardedWithoutKey` refusal under the outer accessor's
28476        // reference projection: a `Sharded` strategy with a `None`
28477        // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
28478        // The bracket-dispatch's third arm reads `p.estrategia()` for
28479        // the match scrutinee then `p.shard_key()` for the cascade
28480        // scrutinee, both on the reference returned by the outer
28481        // accessor.
28482        let mut spec = three_member_spec();
28483        spec.placement.estrategia = PlacementStrategy::Sharded;
28484        spec.placement.shard_key = None;
28485        assert_eq!(
28486            spec.validate().unwrap_err(),
28487            AplicacaoError::ShardedWithoutKey,
28488        );
28489
28490        // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
28491        // reference projection: a non-`Sharded` strategy with a `Some`
28492        // `:shard-key` must trip the declared-but-inert refusal. The
28493        // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
28494        // + `p.estrategia()` for the diagnostic on the reference
28495        // returned by the outer accessor.
28496        let mut spec = three_member_spec();
28497        spec.placement.estrategia = PlacementStrategy::Replicated;
28498        spec.placement.shard_key = Some("tenantId".into());
28499        assert_eq!(
28500            spec.validate().unwrap_err(),
28501            AplicacaoError::ShardKeyOnNonSharded {
28502                estrategia: PlacementStrategy::Replicated,
28503                shard_key: "tenantId".into(),
28504            },
28505        );
28506
28507        // (4) Canonical `three_member_spec` `Replicated` fixture passes
28508        // `validate_placement` — every per-axis arm reaches the fall-
28509        // through `Ok(())` without any per-axis refusal firing under the
28510        // outer accessor's reference projection.
28511        let spec = three_member_spec();
28512        assert!(
28513            spec.validate().is_ok(),
28514            "the canonical Replicated placement fixture must pass \
28515             `validate_placement` — every per-axis arm short-circuits on \
28516             valid input under the outer accessor's reference projection",
28517        );
28518        assert_eq!(
28519            spec.placement().estrategia(),
28520            PlacementStrategy::Replicated,
28521            "the outer accessor's reference projection must be the \
28522             canonical Replicated fixture's strategy",
28523        );
28524        assert_eq!(
28525            spec.placement().clusters(),
28526            &["rio", "mar"],
28527            "the outer accessor's reference projection must be the \
28528             canonical Replicated fixture's cluster pool",
28529        );
28530    }
28531
28532    #[test]
28533    fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
28534        // The canonical per-`:entrada` outer-composite-optional-
28535        // reference-shape pin: [`AplicacaoSpec::entrada`] must return
28536        // the `:entrada` typed `Option<Entrada>` verbatim as an
28537        // `Option<&Entrada>` reference over the same backing storage
28538        // the raw `self.entrada.as_ref()` field access borrows from,
28539        // byte-equal across every representative fixture in the
28540        // accept-set — the author-omitted `None` shape (the
28541        // "internal-only mesh" partition every downstream external-
28542        // gateway emitter treats as "emit nothing"), the minimal
28543        // singleton `:entrada` composite (host + destination + empty
28544        // paths + default port), the paths-carrying composite (the
28545        // canonical `three_member_spec` fixture's ["/api" "/health"]
28546        // path-list shape every HTTPRoute per-rule fan-out emitter
28547        // reads), and the non-default port composite (the canonical
28548        // custom-port shape the port-fallback resolver reads).
28549        //
28550        // Pins against a future silent detour that returned a fresh-
28551        // cloned `Entrada` copy (which would type-check via a `Clone`
28552        // impl but silently break every downstream caller that
28553        // relied on the reference sharing the composite's backing
28554        // identity), a reference to an operator-resolved overlay
28555        // (the future per-cluster `:entrada-overrides` slot the
28556        // MESH-COMPOSITION §V federation roadmap acknowledges — its
28557        // resolution must land at exactly this accessor body, not
28558        // silently divert the raw slot away from a second consumer),
28559        // a `None` → `Some(Entrada::default)` cluster-default
28560        // projection (which would collapse the load-bearing
28561        // "author-omitted `:entrada` ⇒ internal-only mesh" partition
28562        // the peer `gateway_routes` early-return + `feira app graph`
28563        // internal-only-mesh partition both read), or an axis-
28564        // shuffled projection (a future detour that swapped
28565        // `host` and `para` through the accessor would silently
28566        // split the paired `validate` per-`:entrada` shape-and-
28567        // membership gate's traversal input from the peer
28568        // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
28569        // fan-out input from the peer `feira app graph` external-
28570        // gateway summary line).
28571        //
28572        // Peer of the sibling M3
28573        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
28574        // (534dc21) `&MeshPolicy` byte-equal pin on the per-
28575        // `:politicas` outer mesh-policy composite-reference axis
28576        // and of the sibling M3
28577        // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
28578        // (9abb8f0) `&Placement` byte-equal pin on the per-
28579        // `:placement` outer distribution-composite composite-
28580        // reference axis — extends the outer-accessor byte-equal-
28581        // projection discipline onto the last unlifted outermost M3
28582        // mesh-slot type's per-Aplicacao external-gateway composite-
28583        // reference axis, the third and final `&Composite`-return
28584        // accessor on the outer [`AplicacaoSpec`] type.
28585        let fixtures: Vec<Option<Entrada>> = vec![
28586            None,
28587            Some(Entrada {
28588                host: "checkout.quero.cloud".into(),
28589                para: "cart".into(),
28590                paths: Vec::new(),
28591                port: DEFAULT_SERVICO_PORT,
28592            }),
28593            Some(Entrada {
28594                host: "checkout.quero.cloud".into(),
28595                para: "cart".into(),
28596                paths: vec!["/api".into(), "/health".into()],
28597                port: DEFAULT_SERVICO_PORT,
28598            }),
28599            Some(Entrada {
28600                host: "checkout.quero.cloud".into(),
28601                para: "cart".into(),
28602                paths: vec!["/api".into()],
28603                port: 9443,
28604            }),
28605        ];
28606        for entrada in fixtures {
28607            let s = AplicacaoSpec {
28608                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
28609                contratos: Vec::new(),
28610                politicas: MeshPolicy::default(),
28611                placement: Placement::default(),
28612                entrada: entrada.clone(),
28613            };
28614            assert_eq!(
28615                s.entrada(),
28616                entrada.as_ref(),
28617                "AplicacaoSpec::entrada must return :entrada verbatim \
28618                 (got {:?}, expected {:?})",
28619                s.entrada(),
28620                entrada.as_ref(),
28621            );
28622            match (s.entrada(), s.entrada.as_ref()) {
28623                (Some(a), Some(b)) => assert!(
28624                    std::ptr::eq(a, b),
28625                    "AplicacaoSpec::entrada accessor and \
28626                     self.entrada.as_ref() field access must borrow \
28627                     the same backing storage — the accessor is the \
28628                     substrate-primitive typed dispatch every \
28629                     downstream external-gateway composite consumer \
28630                     must route through, and a reference-identity \
28631                     split would silently break every consumer that \
28632                     relied on the borrow sharing the composite's \
28633                     storage",
28634                ),
28635                (None, None) => {}
28636                _ => panic!(
28637                    "AplicacaoSpec::entrada presence bit must byte-\
28638                     equal self.entrada.is_some() — a presence-bit \
28639                     drift would silently split the paired `validate` \
28640                     per-`:entrada` shape-and-membership gate's \
28641                     traversal head from the peer \
28642                     caixa-mesh gateway_routes early-return partition \
28643                     from the peer `feira app graph` internal-only-\
28644                     mesh partition",
28645                ),
28646            }
28647            assert_eq!(
28648                s.entrada().is_some(),
28649                s.entrada.is_some(),
28650                "AplicacaoSpec::entrada().is_some() must byte-equal \
28651                 self.entrada.is_some() — a presence-bit drift would \
28652                 silently split every downstream `Option<&Entrada>` \
28653                 consumer's partition on the internal-only-mesh arm",
28654            );
28655        }
28656    }
28657
28658    #[test]
28659    fn validate_reads_through_lifted_entrada_accessor() {
28660        // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
28661        // per-`:entrada` shape-and-membership gate (`if let Some(e) =
28662        // self.entrada() { … }`, followed by the per-axis fan-out
28663        // `validate_entrada_para(&e.para)` /
28664        // `EntradaMemberMissing` membership lookup /
28665        // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
28666        // per-`e.paths` `validate_entrada_path` traversal) must key
28667        // off the lifted outer accessor, so any future rebrand on
28668        // the typed slot's outer-composite reader shape lands at
28669        // exactly one place. Pins the multi-axis coherence by
28670        // exercising each per-axis refusal end-to-end: (1) the
28671        // author-omitted `None` shape short-circuits past every
28672        // per-`:entrada` refusal (the internal-only mesh partition
28673        // the accessor's `None` arm names), (2) `EntradaMemberMissing`
28674        // fires on a well-shaped but phantom `:para` under the outer
28675        // accessor's reference projection, and (3) the canonical
28676        // `three_member_spec` `:entrada` fixture passes `validate`
28677        // under the outer accessor's reference projection.
28678        //
28679        // Peer of the sibling M3
28680        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
28681        // (534dc21) multi-axis coherence pin on the per-`:politicas`
28682        // outer mesh-policy composite-reference axis and the sibling
28683        // M3
28684        // [`validate_placement_reads_through_lifted_placement_accessor`]
28685        // (9abb8f0) multi-axis coherence pin on the per-`:placement`
28686        // outer distribution-composite composite-reference axis —
28687        // extends the multi-consumer coherence discipline onto the
28688        // last unlifted outermost M3 mesh-slot type's per-Aplicacao
28689        // external-gateway composite-reference axis, the third and
28690        // final `&Composite`-return accessor on the outer
28691        // [`AplicacaoSpec`] type.
28692
28693        // (1) `None` :entrada — the internal-only-mesh partition
28694        // short-circuits past every per-`:entrada` refusal. The outer
28695        // accessor's reference projection reaches the fall-through
28696        // `Ok(())` on the `None` arm without any per-axis refusal
28697        // firing.
28698        let mut spec = three_member_spec();
28699        spec.entrada = None;
28700        assert!(
28701            spec.validate().is_ok(),
28702            "an author-omitted `:entrada` must pass `validate` — the \
28703             internal-only-mesh partition short-circuits past every \
28704             per-`:entrada` refusal under the outer accessor's \
28705             reference projection",
28706        );
28707        assert!(
28708            spec.entrada().is_none(),
28709            "the outer accessor's reference projection must name the \
28710             internal-only-mesh partition per the `None` fixture",
28711        );
28712
28713        // (2) `EntradaMemberMissing` refusal under the outer accessor's
28714        // reference projection: a well-shaped but phantom `:para` must
28715        // trip the membership-lookup refusal. The gate's second arm
28716        // reads `e.para` on the reference returned by the outer
28717        // accessor.
28718        let mut spec = three_member_spec();
28719        if let Some(e) = spec.entrada.as_mut() {
28720            e.para = "phantom".into();
28721        }
28722        assert_eq!(
28723            spec.validate().unwrap_err(),
28724            AplicacaoError::EntradaMemberMissing {
28725                para: "phantom".into(),
28726            },
28727        );
28728        match (spec.entrada(), spec.entrada.as_ref()) {
28729            (Some(a), Some(b)) => assert!(
28730                std::ptr::eq(a, b),
28731                "the `validate` per-`:entrada` gate's traversal head \
28732                 must be the same backing composite the accessor's \
28733                 reference projection borrows from",
28734            ),
28735            _ => panic!("fixture must carry Some(:entrada)"),
28736        }
28737
28738        // (3) Canonical `three_member_spec` `:entrada` fixture passes
28739        // `validate` — every per-axis arm reaches the fall-through
28740        // `Ok(())` without any per-axis refusal firing under the
28741        // outer accessor's reference projection.
28742        let spec = three_member_spec();
28743        assert!(
28744            spec.validate().is_ok(),
28745            "the canonical `:entrada` fixture must pass `validate` — \
28746             every per-axis arm short-circuits on valid input under \
28747             the outer accessor's reference projection",
28748        );
28749        assert!(
28750            spec.entrada().is_some(),
28751            "the outer accessor's reference projection must be the \
28752             canonical `:entrada` fixture's composite",
28753        );
28754    }
28755
28756    #[test]
28757    fn membro_names_matches_inline_membros_projection() {
28758        // Substrate-primitive ≡ inline-projection pin on
28759        // [`AplicacaoSpec::membro_names`]: the lifted membership oracle
28760        // must be byte-for-byte the set the pre-lift inline
28761        // `self.membros().iter().map(Membro::nome).collect()` builder
28762        // produced, on every membership shape the three
28763        // Servico-name-*reference* axes (`:contratos :de`, `:contratos
28764        // :para`, `:entrada :para`) resolve against. Pins the
28765        // projection so a future rebrand of the node-identity axis
28766        // lands at the primitive rather than diverging between the
28767        // per-`:contratos` membership arms still inline at `validate`
28768        // and the lifted `validate_entrada` gate.
28769        for membros in [
28770            vec![],
28771            vec![membro("cart", "^0.1")],
28772            vec![
28773                membro("catalog", "^0.1"),
28774                membro("cart", "^0.1"),
28775                membro("payment", "^0.2"),
28776            ],
28777        ] {
28778            let mut spec = three_member_spec();
28779            spec.membros = membros;
28780            let inline: std::collections::HashSet<&str> =
28781                spec.membros().iter().map(Membro::nome).collect();
28782            assert_eq!(
28783                spec.membro_names(),
28784                inline,
28785                "the lifted membership oracle must discriminate the \
28786                 same node set as the pre-lift inline projection",
28787            );
28788        }
28789    }
28790
28791    #[test]
28792    fn validate_entrada_matches_gate_on_every_per_axis_shape() {
28793        // Per-slot-gate ≡ validate equivalence pin on the lifted
28794        // [`AplicacaoSpec::validate_entrada`]: the named per-slot gate
28795        // must discriminate the same set as [`AplicacaoSpec::validate`]
28796        // on every `:entrada`-covered input, so a future consumer that
28797        // re-validates the one slot (the M4 admission webhook
28798        // re-checking `:entrada` after a gateway-host patch) accepts
28799        // exactly what `feira build` accepts and surfaces the same
28800        // diagnostic on the same input. Covers each of the five gated
28801        // axes plus the two clean-pass shapes (`None` — the
28802        // internal-only-mesh partition — and the canonical fixture).
28803        //
28804        // Peer of the sibling per-slot equivalence pins
28805        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
28806        // / `_on_cross_axis_and_clean_pass_shapes` (f03a154) on the
28807        // `:politicas` slot's compound entry gate, extended here onto
28808        // the `:entrada` slot's newly-named per-slot gate.
28809        /// One `:entrada` equivalence case: a label, the per-axis
28810        /// mutation applied to the canonical fixture's composite, and
28811        /// the diagnostic both the per-slot gate and `validate` must
28812        /// surface on it (`None` = clean pass).
28813        type EntradaCase = (&'static str, fn(&mut Entrada), Option<AplicacaoError>);
28814
28815        let cases: &[EntradaCase] = &[
28816            (
28817                ":para shape — empty",
28818                |e| e.para = String::new(),
28819                Some(AplicacaoError::EntradaParaEmpty),
28820            ),
28821            (
28822                ":para membership — well-shaped phantom",
28823                |e| e.para = "phantom".into(),
28824                Some(AplicacaoError::EntradaMemberMissing {
28825                    para: "phantom".into(),
28826                }),
28827            ),
28828            (
28829                ":host emptiness",
28830                |e| e.host = String::new(),
28831                Some(AplicacaoError::EmptyEntradaHost),
28832            ),
28833            (
28834                ":port structural floor",
28835                |e| e.port = 0,
28836                Some(AplicacaoError::EntradaPortZero),
28837            ),
28838            (
28839                ":paths per-entry emptiness",
28840                |e| e.paths = vec![String::new()],
28841                Some(AplicacaoError::EntradaPathEmpty),
28842            ),
28843            (
28844                ":paths leading-slash grammar",
28845                |e| e.paths = vec!["api/cart".into()],
28846                Some(AplicacaoError::EntradaPathNotAbsolute {
28847                    path: "api/cart".into(),
28848                }),
28849            ),
28850            (
28851                ":paths set-not-multiset",
28852                |e| e.paths = vec!["/api/cart".into(), "/api/cart".into()],
28853                Some(AplicacaoError::EntradaPathDuplicate {
28854                    path: "/api/cart".into(),
28855                }),
28856            ),
28857            ("clean pass — canonical fixture", |_| {}, None),
28858        ];
28859        for (label, mutate, expected) in cases {
28860            let mut spec = three_member_spec();
28861            mutate(spec.entrada.as_mut().expect("fixture carries :entrada"));
28862            assert_eq!(
28863                spec.validate_entrada().err(),
28864                *expected,
28865                "per-slot gate disagreed with the expected diagnostic on {label}",
28866            );
28867            assert_eq!(
28868                spec.validate().err(),
28869                *expected,
28870                "`validate` disagreed with the per-slot gate on {label}",
28871            );
28872        }
28873
28874        // The `None` arm is the internal-only-mesh partition: a clean
28875        // pass through both the per-slot gate and `validate`, not a
28876        // refusal.
28877        let mut spec = three_member_spec();
28878        spec.entrada = None;
28879        assert_eq!(spec.validate_entrada().err(), None);
28880        assert_eq!(spec.validate().err(), None);
28881    }
28882
28883    #[test]
28884    fn validate_entrada_resolves_membership_through_own_oracle() {
28885        // Self-containment pin on the lifted per-slot gate:
28886        // [`AplicacaoSpec::validate_entrada`] resolves `:entrada :para`
28887        // against the oracle *it* builds through
28888        // [`AplicacaoSpec::membro_names`], not one threaded down from
28889        // [`AplicacaoSpec::validate`]. A spec whose `:membros` no
28890        // longer contains the `:entrada :para` target must trip
28891        // `EntradaMemberMissing` when the per-slot gate is called
28892        // directly — the shape a future single-slot re-validator
28893        // (the M4 admission webhook) reaches the axis through, without
28894        // re-walking `:membros` / `:contratos` / the sync-cycle
28895        // detector first. Same self-contained posture
28896        // [`AplicacaoSpec::detect_sync_cycles`] already carries for
28897        // the M4 per-edge policy resolver.
28898        let mut spec = three_member_spec();
28899        spec.membros.retain(|m| m.nome() != "cart");
28900        assert_eq!(
28901            spec.validate_entrada().unwrap_err(),
28902            AplicacaoError::EntradaMemberMissing {
28903                para: "cart".into(),
28904            },
28905            "the per-slot gate must resolve `:para` against the oracle \
28906             it builds itself, with no membership set threaded in",
28907        );
28908        assert!(
28909            !spec.membro_names().contains("cart"),
28910            "fixture must have dropped the `:entrada :para` target \
28911             from the graph's node set",
28912        );
28913    }
28914
28915    #[test]
28916    fn validate_contratos_matches_gate_on_every_per_axis_shape() {
28917        // Per-slot-gate ≡ validate equivalence pin on the lifted
28918        // [`AplicacaoSpec::validate_contratos`]: the named per-slot
28919        // gate must discriminate the same set as
28920        // [`AplicacaoSpec::validate`] on every `:contratos`-covered
28921        // input, so a future consumer that re-validates the one slot
28922        // (the M4 admission webhook re-checking `:contratos` after a
28923        // per-`(:de, :para)` edge patch, the per-`:contratos`-edge
28924        // `:politicas` override MESH-COMPOSITION §III.2 #3
28925        // acknowledges — which resolves an effective per-edge
28926        // [`MeshPolicy`] and must re-check the edge's identity closure
28927        // before it can key a per-edge override off the endpoint
28928        // tuple) accepts exactly what `feira build` accepts and
28929        // surfaces the same diagnostic on the same input. Covers each
28930        // of the six gated axes (`:de`/`:para` per-arm shape,
28931        // per-arm graph-membership, structural self-loop, `:wit`
28932        // emptiness) plus the clean-pass canonical fixture; the
28933        // reason-carrying arms (`ContratoCaixaInvalid` on `:de`/`:para`
28934        // shape, `ContratoWitInvalid` on WIT-shape ↔ target dispatch,
28935        // `ContratoDuplicate` on whole-edge dedup) whose `reason:` /
28936        // `target:` carriers depend on library implementation
28937        // details are pinned separately below with a `matches!`
28938        // predicate on the arm identity plus the mirror equivalence
28939        // between the two entry points.
28940        //
28941        // Peer of the sibling per-slot equivalence pins
28942        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
28943        // / `_on_cross_axis_and_clean_pass_shapes` (f03a154) on the
28944        // `:politicas` slot's compound entry gate, and
28945        // `validate_entrada_matches_gate_on_every_per_axis_shape`
28946        // (20cd523) on the `:entrada` slot's per-slot gate — extended
28947        // here onto the `:contratos` slot's newly-named per-slot gate,
28948        // closing the last unlifted per-slot gate on the M3 mesh-slot
28949        // family.
28950        /// One `:contratos` equivalence case: a label, the per-axis
28951        /// mutation applied to the canonical fixture's spec, and the
28952        /// diagnostic both the per-slot gate and `validate` must
28953        /// surface on it (`None` = clean pass).
28954        type ContratoCase = (&'static str, fn(&mut AplicacaoSpec), Option<AplicacaoError>);
28955
28956        let cases: &[ContratoCase] = &[
28957            (
28958                ":de shape — empty",
28959                |s| s.contratos[0].de = String::new(),
28960                Some(AplicacaoError::ContratoCaixaEmpty {
28961                    slot: crate::render::CONTRATO_AUTHOR_KEY_DE,
28962                }),
28963            ),
28964            (
28965                ":para shape — empty",
28966                |s| s.contratos[0].para = String::new(),
28967                Some(AplicacaoError::ContratoCaixaEmpty {
28968                    slot: crate::render::CONTRATO_AUTHOR_KEY_PARA,
28969                }),
28970            ),
28971            (
28972                ":de membership — well-shaped phantom",
28973                |s| s.contratos[0].de = "phantom".into(),
28974                Some(AplicacaoError::ContratoMemberMissing {
28975                    caixa: "phantom".into(),
28976                }),
28977            ),
28978            (
28979                ":para membership — well-shaped phantom",
28980                |s| s.contratos[0].para = "phantom".into(),
28981                Some(AplicacaoError::ContratoMemberMissing {
28982                    caixa: "phantom".into(),
28983                }),
28984            ),
28985            (
28986                "structural self-loop",
28987                |s| s.contratos[0].para = "cart".into(),
28988                Some(AplicacaoError::ContratoSelfLoop {
28989                    caixa: "cart".into(),
28990                    wit: "wasi:http/proxy".into(),
28991                }),
28992            ),
28993            (
28994                ":wit emptiness",
28995                |s| s.contratos[0].wit = String::new(),
28996                Some(AplicacaoError::EmptyWit {
28997                    de: "cart".into(),
28998                    para: "catalog".into(),
28999                }),
29000            ),
29001            ("clean pass — canonical fixture", |_| {}, None),
29002        ];
29003        for (label, mutate, expected) in cases {
29004            let mut spec = three_member_spec();
29005            mutate(&mut spec);
29006            assert_eq!(
29007                spec.validate_contratos().err(),
29008                *expected,
29009                "per-slot gate disagreed with the expected diagnostic on {label}",
29010            );
29011            assert_eq!(
29012                spec.validate().err(),
29013                *expected,
29014                "`validate` disagreed with the per-slot gate on {label}",
29015            );
29016        }
29017    }
29018
29019    #[test]
29020    fn validate_contratos_matches_gate_on_reason_carrying_arms() {
29021        // Companion pin to
29022        // [`validate_contratos_matches_gate_on_every_per_axis_shape`]:
29023        // the per-slot gate ≡ `validate` equivalence on the three
29024        // `:contratos` refusal arms whose diagnostic carries a
29025        // library-owned string ([`AplicacaoError::ContratoCaixaInvalid`]
29026        // and [`AplicacaoError::ContratoWrongTarget`] via the paired
29027        // `is_dns_1123_label` / `WitContract::target` shape helpers,
29028        // and [`AplicacaoError::ContratoDuplicate`] via [`WitTarget::label`]'s
29029        // library-formatted `target:` scalar). Value equality between
29030        // the per-slot gate and `validate` outputs pins the full
29031        // `Option<AplicacaoError>` (including reason-strings), and the
29032        // per-arm `matches!` predicate pins the arm-discriminator
29033        // identity on the specific `Contrato*` variant. Split from
29034        // the primary equivalence pin so each pin body stays under
29035        // [`clippy::too_many_lines`], the same shape the peer
29036        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
29037        // / `_on_cross_axis_and_clean_pass_shapes` split (f03a154)
29038        // carries on the `:politicas` slot's compound entry gate.
29039        type ContratoReasonCase = (
29040            &'static str,
29041            fn(&mut AplicacaoSpec),
29042            fn(&AplicacaoError) -> bool,
29043        );
29044        let cases: &[ContratoReasonCase] = &[
29045            (
29046                ":de shape — DNS-1123 invalid",
29047                |s| s.contratos[0].de = "Cart".into(),
29048                |err| {
29049                    matches!(
29050                        err,
29051                        AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. }
29052                            if *slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
29053                    )
29054                },
29055            ),
29056            (
29057                ":wit target-shape mismatch — payload on capability arm",
29058                |s| s.contratos[0].wit = "wasi:junk/nope".into(),
29059                |err| {
29060                    matches!(
29061                        err,
29062                        AplicacaoError::ContratoWrongTarget { de, para, wit, .. }
29063                            if de == "cart" && para == "catalog" && wit == "wasi:junk/nope"
29064                    )
29065                },
29066            ),
29067            (
29068                "whole-edge dedup — six-axis identity collision",
29069                |s| {
29070                    let dup = s.contratos[0].clone();
29071                    s.contratos.push(dup);
29072                },
29073                |err| {
29074                    matches!(
29075                        err,
29076                        AplicacaoError::ContratoDuplicate { de, para, wit, .. }
29077                            if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
29078                    )
29079                },
29080            ),
29081        ];
29082        for (label, mutate, arm_matches) in cases {
29083            let mut spec = three_member_spec();
29084            mutate(&mut spec);
29085            let per_slot = spec.validate_contratos().err();
29086            let gate = spec.validate().err();
29087            assert_eq!(
29088                per_slot, gate,
29089                "per-slot gate and `validate` must return byte-equal \
29090                 `Option<AplicacaoError>` on {label} (including \
29091                 library-owned reason strings)",
29092            );
29093            let err = per_slot
29094                .as_ref()
29095                .unwrap_or_else(|| panic!("expected refusal on {label}, got clean pass"));
29096            assert!(
29097                arm_matches(err),
29098                "per-slot gate surfaced the wrong arm on {label}: got {err:?}",
29099            );
29100        }
29101    }
29102
29103    #[test]
29104    fn validate_contratos_resolves_membership_through_own_oracle() {
29105        // Self-containment pin on the lifted per-slot gate:
29106        // [`AplicacaoSpec::validate_contratos`] resolves each edge's
29107        // `:de` / `:para` against the oracle *it* builds through
29108        // [`AplicacaoSpec::membro_names`], not one threaded down from
29109        // [`AplicacaoSpec::validate`]. A spec whose `:membros` no
29110        // longer contains a `:contratos` edge's endpoint must trip
29111        // `ContratoMemberMissing` when the per-slot gate is called
29112        // directly — the shape a future single-slot re-validator
29113        // (the M4 admission webhook re-checking `:contratos` after a
29114        // per-`(:de, :para)` edge patch, the M4 per-edge policy
29115        // resolver on the `:politicas` override axis) reaches the
29116        // axis through, without re-walking `:membros` / `:entrada` /
29117        // `:placement` / `:politicas` first. Same self-contained
29118        // posture the peer per-slot gates
29119        // [`AplicacaoSpec::detect_sync_cycles`] and
29120        // [`AplicacaoSpec::validate_entrada`] already carry for the
29121        // same M4 consumers.
29122        let mut spec = three_member_spec();
29123        spec.membros.retain(|m| m.nome() != "catalog");
29124        assert_eq!(
29125            spec.validate_contratos().unwrap_err(),
29126            AplicacaoError::ContratoMemberMissing {
29127                caixa: "catalog".into(),
29128            },
29129            "the per-slot gate must resolve `:de` / `:para` against \
29130             the oracle it builds itself, with no membership set \
29131             threaded in",
29132        );
29133        assert!(
29134            !spec.membro_names().contains("catalog"),
29135            "fixture must have dropped the `:contratos` edge's \
29136             `:para` target from the graph's node set",
29137        );
29138    }
29139
29140    #[test]
29141    fn validate_contratos_folds_cycle_axis_matches_gate() {
29142        // Fold-into-per-slot-gate equivalence pin on the
29143        // cross-edge cycle axis: an [`AplicacaoError::ContratoCycle`]
29144        // surfaces byte-equal through both
29145        // [`AplicacaoSpec::validate_contratos`] and
29146        // [`AplicacaoSpec::validate`] on a fixture whose only defect is
29147        // a synchronous-edge cycle in `:contratos`. Pins the fold that
29148        // moved the cross-edge cycle axis onto the per-slot gate — a
29149        // future silent regression that de-folded the axis back to the
29150        // outer [`AplicacaoSpec::validate`] dispatch (a rebase artifact,
29151        // a peer per-slot gate lift that skipped the cross-axis half of
29152        // the [`MeshPolicy::validate`]-analogous discipline) would
29153        // surface here as `Some(ContratoCycle)` from `validate` and
29154        // `None` from `validate_contratos`.
29155        //
29156        // Cycle fixture is the same shape as the peer
29157        // [`rejects_three_node_synchronous_cycle`] test carries: a
29158        // clean 3-cycle over the HTTP subgraph (catalog → cart →
29159        // payment → catalog), so the per-entry cascade (shape +
29160        // membership + self-loop + `:wit` emptiness + WIT-target +
29161        // whole-edge dedup) passes cleanly and the sole surviving
29162        // refusal shape is the cross-edge cycle axis. The `cycle`
29163        // vector is normalized to a sorted body set for the equality
29164        // compare (the traversal path's starting node depends on
29165        // BTreeMap iteration order, which is deterministic but is not
29166        // the load-bearing property this pin covers).
29167        //
29168        // Peer of the sibling per-slot ≡ `validate` equivalence pins
29169        // [`validate_contratos_matches_gate_on_every_per_axis_shape`]
29170        // (per-entry axes) and
29171        // [`validate_contratos_matches_gate_on_reason_carrying_arms`]
29172        // (parser-owned reason arms) already carry on the six
29173        // per-entry axes — this extends the discipline onto the
29174        // cross-edge cycle axis newly folded into the per-slot gate,
29175        // matching the peer per-slot compound gate
29176        // [`AplicacaoSpec::validate_politicas`] (f03a154) which folded
29177        // both per-axis and cross-axis surfaces on `:politicas`.
29178        let mut spec = three_member_spec();
29179        spec.contratos = vec![
29180            contract_http("catalog", "cart", "/x"),
29181            contract_http("cart", "payment", "/y"),
29182            contract_http("payment", "catalog", "/z"),
29183        ];
29184        let per_slot_err = spec.validate_contratos().unwrap_err();
29185        let gate_err = spec.validate().unwrap_err();
29186        assert_eq!(
29187            per_slot_err, gate_err,
29188            "the per-slot gate and `validate` must return byte-equal \
29189             `AplicacaoError::ContratoCycle` on a cycle-only fixture \
29190             — the fold pins the cross-edge axis onto the per-slot \
29191             gate the same way the peer `validate_politicas` fold \
29192             pinned the `:politicas` cross-axis surface",
29193        );
29194        match per_slot_err {
29195            AplicacaoError::ContratoCycle { ref cycle } => {
29196                assert_eq!(
29197                    cycle.first(),
29198                    cycle.last(),
29199                    "cycle traversal must close on the back-edge \
29200                     target — the diagnostic shape the peer \
29201                     `rejects_three_node_synchronous_cycle` pins",
29202                );
29203                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
29204                assert_eq!(body.len(), 3, "3-cycle must visit 3 distinct nodes");
29205                assert!(body.contains("cart"));
29206                assert!(body.contains("catalog"));
29207                assert!(body.contains("payment"));
29208            }
29209            other => panic!("expected ContratoCycle, got {other:?}"),
29210        }
29211    }
29212
29213    #[test]
29214    fn validate_contratos_per_entry_arm_fires_before_cycle_arm() {
29215        // Diagnostic-ordering pin on the fold: a `:contratos` fixture
29216        // carrying *both* a per-entry defect (a self-loop, the
29217        // structural-self-edge arm on the per-entry cascade — chosen
29218        // because it never masks or is masked by the cycle diagnostic
29219        // on the peer arms) *and* a would-be synchronous-edge cycle in
29220        // the remaining edges must surface the per-entry diagnostic
29221        // first through both [`AplicacaoSpec::validate_contratos`] and
29222        // [`AplicacaoSpec::validate`] — pinning the fold's canonical
29223        // per-entry-before-cross-edge dispatch ordering, byte-equal to
29224        // the pre-fold `validate`-side sequence
29225        // (`validate_contratos()? → detect_sync_cycles()?`) the
29226        // dispatch encoded verbatim. A silent regression that reversed
29227        // the ordering inside the fold would surface here as a cycle
29228        // diagnostic on a fixture carrying an earlier per-entry defect
29229        // — masking the narrower "this edge is degenerate" arm behind
29230        // the coarser "this graph deadlocks" arm.
29231        //
29232        // Peer of the diagnostic-ordering property the pre-fold
29233        // dispatch encoded at the [`AplicacaoSpec::validate`]
29234        // altitude (`validate_contratos()? → detect_sync_cycles()?`),
29235        // now enforced inside the per-slot gate's own body, so a future
29236        // consumer that reaches only the per-slot gate (the M4
29237        // admission webhook re-checking `:contratos` after a per-edge
29238        // patch) inherits the ordering property by construction.
29239        let mut spec = three_member_spec();
29240        // The three-member fixture already has cart → catalog and
29241        // cart → payment; adding catalog → cart closes a 2-cycle on
29242        // the HTTP subgraph.
29243        spec.contratos
29244            .push(contract_http("catalog", "cart", "/refresh"));
29245        // Add a self-loop on `payment` — the per-entry structural-
29246        // self-edge arm — which must surface first.
29247        spec.contratos
29248            .push(contract_http("payment", "payment", "/loop"));
29249        let per_slot_err = spec.validate_contratos().unwrap_err();
29250        let gate_err = spec.validate().unwrap_err();
29251        assert_eq!(
29252            per_slot_err, gate_err,
29253            "per-slot gate and `validate` must agree on the ordering \
29254             fixture's surfaced diagnostic — a divergence here means \
29255             the fold reshaped one dispatch's ordering without the \
29256             other",
29257        );
29258        assert!(
29259            matches!(
29260                per_slot_err,
29261                AplicacaoError::ContratoSelfLoop { ref caixa, .. }
29262                    if caixa == "payment"
29263            ),
29264            "the per-entry structural-self-edge arm must fire before \
29265             the cross-edge cycle arm — pinning the fold's per-entry-\
29266             before-cross-edge dispatch ordering byte-equal to the \
29267             pre-fold `validate_contratos()? → detect_sync_cycles()?` \
29268             sequence; got {per_slot_err:?}",
29269        );
29270    }
29271
29272    #[test]
29273    fn validate_contratos_cycle_axis_is_self_contained_on_slot() {
29274        // Self-containment pin on the folded cross-edge cycle axis:
29275        // [`AplicacaoSpec::validate_contratos`] surfaces
29276        // [`AplicacaoError::ContratoCycle`] directly against `&self`
29277        // without depending on the peer per-slot gates
29278        // ([`AplicacaoSpec::validate_membros`],
29279        // [`AplicacaoSpec::validate_entrada`],
29280        // [`AplicacaoSpec::validate_placement`],
29281        // [`AplicacaoSpec::validate_politicas`]) running first — the
29282        // shape a future single-slot re-validator (the M4 admission
29283        // webhook re-checking `:contratos` after a per-`(:de, :para)`
29284        // edge patch, the per-edge policy resolver MESH-COMPOSITION
29285        // §III.2 #3 acknowledges) reaches *both* structural axes on
29286        // the slot through one call. A spec with a per-`:politicas`
29287        // refusal shape (zero `:timeout`, the first per-axis arm the
29288        // peer [`MeshPolicy::validate`] gate covers) AND a
29289        // synchronous-edge cycle in `:contratos` must:
29290        //
29291        //   - surface [`AplicacaoError::ContratoCycle`] through the
29292        //     per-slot gate `validate_contratos` directly (proves the
29293        //     cycle axis reaches the per-slot altitude without the
29294        //     peer `:politicas` gate running first);
29295        //   - surface [`AplicacaoError::ContratoCycle`] through
29296        //     `validate` (which reaches `validate_contratos` before
29297        //     `validate_politicas` per the fixed dispatch order), so
29298        //     the fold's cross-slot ordering (`:membros` →
29299        //     `:contratos` → `:entrada` → `:placement` → `:politicas`)
29300        //     is byte-equal to the pre-fold dispatch's ordering.
29301        //
29302        // Same self-contained-on-`&self` posture the peer per-slot
29303        // gates [`AplicacaoSpec::validate_entrada`] (20cd523),
29304        // [`AplicacaoSpec::validate_contratos`] per-entry axis
29305        // (906a5c6), and [`AplicacaoSpec::validate_politicas`]
29306        // (f03a154) already carry — extended here onto the newly-
29307        // folded cross-edge cycle axis. Peer of the sibling per-slot
29308        // self-containment pins
29309        // `validate_entrada_resolves_membership_through_own_oracle`
29310        // and `validate_contratos_resolves_membership_through_own_oracle`
29311        // on the per-entry membership axis — extends the discipline
29312        // onto the cross-edge cycle axis of the same per-slot gate.
29313        let mut spec = three_member_spec();
29314        // Poison `:politicas` — zero-`:timeout` trips the first per-
29315        // axis arm the [`MeshPolicy::validate`] gate covers, so any
29316        // dispatch that reached `:politicas` would surface a
29317        // `:politicas` diagnostic instead of `ContratoCycle`.
29318        spec.politicas.timeout = Some(Duration::from_secs(0));
29319        // Close a synchronous-edge cycle on the HTTP subgraph.
29320        spec.contratos
29321            .push(contract_http("catalog", "cart", "/refresh"));
29322        let per_slot_err = spec.validate_contratos().unwrap_err();
29323        assert!(
29324            matches!(per_slot_err, AplicacaoError::ContratoCycle { .. }),
29325            "the per-slot gate must surface `ContratoCycle` directly \
29326             against `&self` — a peer per-slot gate's regression \
29327             would surface a non-`ContratoCycle` diagnostic here; \
29328             got {per_slot_err:?}",
29329        );
29330        let gate_err = spec.validate().unwrap_err();
29331        assert!(
29332            matches!(gate_err, AplicacaoError::ContratoCycle { .. }),
29333            "`validate`'s five-slot dispatch must reach the fold's \
29334             cross-edge cycle axis on `:contratos` before the peer \
29335             `:politicas` gate — a dispatch-order regression would \
29336             surface a `:politicas` diagnostic here; got {gate_err:?}",
29337        );
29338        // Sanity: the poisoned `:politicas` alone would trip
29339        // [`MeshPolicy::validate`] under the peer per-slot gate, so
29340        // the cycle-first surfacing above is a real ordering property,
29341        // not a case where the `:politicas` axis silently accepts the
29342        // fixture.
29343        let mut politicas_only = three_member_spec();
29344        politicas_only.politicas.timeout = Some(Duration::from_secs(0));
29345        assert!(
29346            politicas_only.validate_politicas().is_err(),
29347            "the poisoned `:politicas` fixture must trip the peer \
29348             per-slot gate on its own — otherwise the self-contained \
29349             cycle-first surfacing above would not be an ordering \
29350             property",
29351        );
29352    }
29353
29354    #[test]
29355    fn wit_contract_require_endpoints_in_folds_per_arm_membership_cascade() {
29356        // Fail-before-pass-after equivalence pin on the lifted
29357        // per-edge substrate primitive [`WitContract::require_endpoints_in`]:
29358        // both arms (`:de` phantom and `:para` phantom) must fire the
29359        // `AplicacaoError::ContratoMemberMissing` diagnostic with a
29360        // `caixa` carrier byte-equal to the offending accessor's
29361        // projection, and `:de` must fire before `:para` when both
29362        // arms would trip on the same call — preserving the canonical
29363        // edge-direction order the peer per-arm shape gate
29364        // [`validate_contrato_caixa`], the [`WitContract::is_self_loop`]
29365        // diagnostic, and every peer per-arm ordering in
29366        // [`AplicacaoSpec::validate_contratos`] already carry.
29367        //
29368        // Two-endpoint oracle covers exactly enough graph nodes to
29369        // exercise each arm in isolation: the `:de` arm fires when
29370        // the source is off-oracle and the destination is on-oracle,
29371        // the `:para` arm fires when the source is on-oracle and the
29372        // destination is off-oracle, and the `:de`-before-`:para`
29373        // ordering falls out from a probe where *both* endpoints are
29374        // off-oracle — the diagnostic's `caixa` field must byte-equal
29375        // the source, not the destination, pinning the primitive's
29376        // arm ordering as `:de` first.
29377        let mut names: std::collections::HashSet<&str> = std::collections::HashSet::new();
29378        names.insert("cart");
29379        names.insert("catalog");
29380
29381        // `:de` phantom, `:para` on-oracle
29382        let de_phantom = contract_http("phantom-de", "catalog", "/x");
29383        let err = de_phantom.require_endpoints_in(&names).unwrap_err();
29384        assert_eq!(
29385            err,
29386            AplicacaoError::ContratoMemberMissing {
29387                caixa: de_phantom.source().to_string(),
29388            },
29389            "the `:de` phantom arm must fire ContratoMemberMissing \
29390             with `caixa` byte-equal to `WitContract::source` — a \
29391             bypass here (a raw `.de.clone()` regression, a divergent \
29392             accessor on a per-CR alias table) would silently split \
29393             the primitive's diagnostic from the substrate-primitive \
29394             scalar accessor every downstream consumer routes through",
29395        );
29396
29397        // `:de` on-oracle, `:para` phantom
29398        let para_phantom = contract_http("cart", "phantom-para", "/x");
29399        let err = para_phantom.require_endpoints_in(&names).unwrap_err();
29400        assert_eq!(
29401            err,
29402            AplicacaoError::ContratoMemberMissing {
29403                caixa: para_phantom.destination().to_string(),
29404            },
29405            "the `:para` phantom arm must fire ContratoMemberMissing \
29406             with `caixa` byte-equal to `WitContract::destination` — \
29407             symmetric callee-side pin to the `:de` arm above",
29408        );
29409
29410        // Both endpoints off-oracle: the `:de` arm must fire first,
29411        // pinning the primitive's canonical edge-direction order.
29412        let both_phantom = contract_http("phantom-de", "phantom-para", "/x");
29413        let err = both_phantom.require_endpoints_in(&names).unwrap_err();
29414        assert_eq!(
29415            err,
29416            AplicacaoError::ContratoMemberMissing {
29417                caixa: both_phantom.source().to_string(),
29418            },
29419            "when both endpoints are off-oracle, the `:de` arm must \
29420             fire before the `:para` arm — preserving byte-equal \
29421             ordering with the pre-lift inline cascade in \
29422             `validate_contratos` and with every peer per-arm \
29423             ordering the sibling per-edge substrate primitives \
29424             already carry",
29425        );
29426
29427        // Both endpoints on-oracle: clean pass.
29428        let clean = contract_http("cart", "catalog", "/x");
29429        clean.require_endpoints_in(&names).unwrap();
29430    }
29431
29432    #[test]
29433    fn validate_contratos_membership_gate_routes_through_require_endpoints_in() {
29434        // Convergence pin: the whole-spec end-to-end route through
29435        // [`AplicacaoSpec::validate_contratos`] must reach the
29436        // per-edge substrate primitive
29437        // [`WitContract::require_endpoints_in`] on every membership
29438        // arm — the diagnostic fired at the per-slot altitude must
29439        // byte-equal the diagnostic the primitive fires when called
29440        // directly on the same edge and the same oracle. Pins the
29441        // primitive as the sole load-bearing gate on the membership
29442        // axis, so any future silent detour that re-inlined the twin
29443        // `if !names.contains(...)` cascade back into the per-slot
29444        // gate (a rebase-artifact regression, an M4 admission-webhook
29445        // consumer that bypassed the primitive) would surface here as
29446        // a byte-equal miss between the two dispatches.
29447        //
29448        // Same equivalence-pin discipline the peer
29449        // [`validate_contratos_matches_gate_on_every_per_axis_shape`]
29450        // pin already carries on the per-slot gate ≡ `validate` axis,
29451        // extended here onto the per-slot gate ≡ per-edge primitive
29452        // axis at one altitude deeper.
29453        for phantom_edge in [
29454            contract_http("phantom-de", "catalog", "/x"),
29455            contract_http("cart", "phantom-para", "/x"),
29456        ] {
29457            let mut spec = three_member_spec();
29458            spec.contratos.push(phantom_edge.clone());
29459            let per_slot_err = spec.validate_contratos().unwrap_err();
29460            let primitive_err = phantom_edge
29461                .require_endpoints_in(&spec.membro_names())
29462                .unwrap_err();
29463            assert_eq!(
29464                per_slot_err, primitive_err,
29465                "the per-slot gate must reach the per-edge substrate \
29466                 primitive on every membership arm — a bypass here \
29467                 would silently split the two dispatches on the \
29468                 same edge + same oracle input",
29469            );
29470            // And the diagnostic's `caixa` carrier must byte-equal
29471            // the offending accessor's projection at both altitudes,
29472            // pinning the accessor routing across the whole-spec
29473            // path.
29474            let AplicacaoError::ContratoMemberMissing { ref caixa } = per_slot_err else {
29475                panic!("expected ContratoMemberMissing, got {per_slot_err:?}");
29476            };
29477            let expected = if spec.membro_names().contains(phantom_edge.source()) {
29478                phantom_edge.destination()
29479            } else {
29480                phantom_edge.source()
29481            };
29482            assert_eq!(
29483                caixa, expected,
29484                "the whole-spec ContratoMemberMissing.caixa carrier \
29485                 must byte-equal the offending edge's accessor \
29486                 projection — a bypass here would silently split \
29487                 the wrap envelope's `caixa` field from the \
29488                 substrate-primitive scalar accessor every \
29489                 downstream consumer routes through",
29490            );
29491        }
29492    }
29493
29494    #[test]
29495    fn port_for_destination_reads_through_lifted_entrada_accessor() {
29496        // Peer coherence pin: the
29497        // [`AplicacaoSpec::port_for_destination`] per-destination
29498        // L4-port fallback resolver's composite-projection seed
29499        // (`self.entrada().filter(…).map_or(…)`) must key off the
29500        // lifted outer accessor. Pins the coherence by exercising
29501        // the resolver end-to-end: (1) the `None` `:entrada` shape
29502        // falls through to `DEFAULT_SERVICO_PORT` under the outer
29503        // accessor's reference projection, (2) a non-matching
29504        // destination falls through to `DEFAULT_SERVICO_PORT` under
29505        // the outer accessor's reference projection, and (3) the
29506        // matching destination resolves to the `:entrada :port`
29507        // value under the outer accessor's reference projection.
29508        //
29509        // Peer of the sibling
29510        // [`validate_reads_through_lifted_entrada_accessor`] multi-
29511        // consumer coherence pin on the same per-`:entrada` outer-
29512        // composite axis — extends the multi-consumer coherence
29513        // discipline onto the second per-`:entrada` production
29514        // consumer, the L4-port fallback resolver.
29515
29516        // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
29517        // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
29518        // arm under the outer accessor's reference projection.
29519        let mut spec = three_member_spec();
29520        spec.entrada = None;
29521        assert_eq!(
29522            spec.port_for_destination("cart"),
29523            DEFAULT_SERVICO_PORT,
29524            "the port-fallback resolver must fall through to \
29525             DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
29526             under the outer accessor's reference projection",
29527        );
29528
29529        // (2) Non-matching destination — the resolver's `filter(…)`
29530        // arm rejects a mismatched destination and falls through
29531        // to `DEFAULT_SERVICO_PORT` under the outer accessor's
29532        // reference projection.
29533        let mut spec = three_member_spec();
29534        if let Some(e) = spec.entrada.as_mut() {
29535            e.para = "cart".into();
29536            e.port = 9443;
29537        }
29538        assert_eq!(
29539            spec.port_for_destination("catalog"),
29540            DEFAULT_SERVICO_PORT,
29541            "the port-fallback resolver must fall through to \
29542             DEFAULT_SERVICO_PORT on a non-matching destination \
29543             under the outer accessor's reference projection",
29544        );
29545
29546        // (3) Matching destination — the resolver's `map_or(…)` arm
29547        // returns the `:entrada :port` value under the outer
29548        // accessor's reference projection.
29549        let mut spec = three_member_spec();
29550        if let Some(e) = spec.entrada.as_mut() {
29551            e.para = "cart".into();
29552            e.port = 9443;
29553        }
29554        assert_eq!(
29555            spec.port_for_destination("cart"),
29556            9443,
29557            "the port-fallback resolver must return the \
29558             `:entrada :port` value on a matching destination \
29559             under the outer accessor's reference projection",
29560        );
29561    }
29562
29563    #[test]
29564    fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
29565        // The canonical per-`:politicas` `:mtls-required` mTLS-
29566        // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
29567        // must return the `:politicas :mtls-required` typed bool
29568        // verbatim as an `Option<bool>`, byte-equal to the raw field
29569        // access across every value in the three-way accept-set —
29570        // `None` (cluster default applies), `Some(true)` (mTLS
29571        // handshake enforced — the sandboxing-by-default arm the
29572        // MeshPolicy's docstring names), `Some(false)` (handshake
29573        // skipped — the explicit debug-edge opt-out).
29574        //
29575        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
29576        // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
29577        // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
29578        // shape — first `Option<Copy-T>`-return accessor on the M3
29579        // mesh-slot family. Pins against a future silent detour that
29580        // re-derived the toggle from a peer axis (an accidental
29581        // `.circuit_breaker.is_some()` collapse that assumed mTLS on
29582        // whenever a breaker is set), a `None` → `Some(false)` cluster-
29583        // default projection (the canonical `Option<bool>` → `bool`
29584        // collapse footgun the surrounding `is_empty()` predicate
29585        // guards on the peer emptiness axis), or a `Some(true)` /
29586        // `Some(false)` variant swap that landed on one consumer
29587        // without the other.
29588        for required in [None, Some(true), Some(false)] {
29589            let p = MeshPolicy {
29590                mtls_required: required,
29591                ..MeshPolicy::default()
29592            };
29593            assert_eq!(
29594                p.mtls_required(),
29595                required,
29596                "MeshPolicy::mtls_required must return :politicas \
29597                 :mtls-required verbatim (got {:?}, expected {required:?})",
29598                p.mtls_required(),
29599            );
29600            assert_eq!(
29601                p.mtls_required(),
29602                p.mtls_required,
29603                "MeshPolicy::mtls_required must byte-equal the raw \
29604                 .mtls_required field access across every value in the \
29605                 three-way accept-set",
29606            );
29607        }
29608    }
29609
29610    #[test]
29611    fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
29612        // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
29613        // arm must key off [`MeshPolicy::mtls_required`], not the raw
29614        // `.mtls_required` field access. Structurally: toggling ONLY
29615        // the `mtls_required` slot on an otherwise-default MeshPolicy
29616        // must flip `is_empty()` from `true` (all-`None`) to `false`
29617        // (one axis carries a value); the flip must be observed for
29618        // both `Some(true)` and `Some(false)` since the emptiness
29619        // semantic reads "any axis carries a value" — not "any axis
29620        // carries a truthy value" — the same non-collapsing shape the
29621        // sibling M2 [`crate::LimitsSpec::is_empty`] /
29622        // [`crate::BehaviorSpec::is_empty`] predicates carry on their
29623        // peer `Option<T>`-typed slot surfaces.
29624        //
29625        // Pins against a future silent detour that re-derived the
29626        // emptiness predicate off a peer axis (an accidental
29627        // `.rate_limit.is_none()`-only chain that dropped the
29628        // `mtls_required` arm entirely), a `mtls_required == Some(_)`
29629        // collapse to a truthy-only check (which would silently
29630        // classify `Some(false)` as empty), or an accessor-side
29631        // detour that no longer names the substrate-primitive typed
29632        // dispatch (an accidental `self.mtls_required.unwrap_or(false)
29633        // == false` fallback in the accessor that would silently
29634        // classify both `None` and `Some(false)` as the same value).
29635        //
29636        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
29637        // (7cd2a28) accessor-composition pin on the sibling optional-
29638        // scalar axis — same "the emptiness / shape-gate predicate
29639        // must route through the substrate-primitive typed dispatch"
29640        // discipline extended onto the peer per-`:politicas` emptiness
29641        // predicate.
29642        let empty = MeshPolicy::default();
29643        assert!(
29644            empty.is_empty(),
29645            "MeshPolicy::default() must be is_empty() — every axis \
29646             defaults to None",
29647        );
29648        for required in [Some(true), Some(false)] {
29649            let p = MeshPolicy {
29650                mtls_required: required,
29651                ..MeshPolicy::default()
29652            };
29653            assert!(
29654                !p.is_empty(),
29655                "MeshPolicy::is_empty must return false when \
29656                 :mtls-required is {required:?} — the emptiness \
29657                 predicate reads \"any axis carries a value\", not \
29658                 \"any axis carries a truthy value\"",
29659            );
29660            assert_eq!(
29661                p.mtls_required().is_none(),
29662                p.is_empty(),
29663                "when :mtls-required is the only set axis, \
29664                 is_empty() must equal mtls_required().is_none() — \
29665                 the accessor and the emptiness predicate must \
29666                 route through the same substrate-primitive typed \
29667                 dispatch on the :mtls-required arm",
29668            );
29669        }
29670    }
29671
29672    #[test]
29673    fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
29674        // The by-copy pin: [`MeshPolicy::mtls_required`] returns
29675        // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
29676        // accessor must return by value, not by reference. Peer of the
29677        // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
29678        // borrow-invariant pin on the sibling `Option<String>` slot,
29679        // but extended onto the peer `Option<bool>` copy-invariant
29680        // shape — the accessor's returned `Option<bool>` must outlive
29681        // `&self` (multiple calls must return equal values from a
29682        // dropped-`&self` copy, since the returned Option carries no
29683        // borrow), and calling the accessor twice on the same
29684        // MeshPolicy must yield the same `Option<bool>` verbatim
29685        // (idempotent, no side effects on `&self`).
29686        //
29687        // Pins against a future silent detour that returned
29688        // `Option<&bool>` (which would type-check but silently break
29689        // every downstream caller — [`single_field_overlay`]'s first
29690        // parameter is `Option<T: Clone>`, and `&bool` would fold to a
29691        // detached copy at the call site), an accidental
29692        // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
29693        // would also type-check but return `Option<&bool>`), or a
29694        // one-arm-only accessor that reads `Some(*b)` in the Some arm
29695        // but reads a fresh Default::default() in the None arm.
29696        for required in [None, Some(true), Some(false)] {
29697            let p = MeshPolicy {
29698                mtls_required: required,
29699                ..MeshPolicy::default()
29700            };
29701            let first = p.mtls_required();
29702            let second = p.mtls_required();
29703            assert_eq!(
29704                first, second,
29705                "MeshPolicy::mtls_required must be idempotent — two \
29706                 successive calls on the same &self must return the \
29707                 same Option<bool>",
29708            );
29709            assert_eq!(
29710                first, required,
29711                "MeshPolicy::mtls_required must return :politicas \
29712                 :mtls-required verbatim by copy — got {first:?}, \
29713                 expected {required:?}",
29714            );
29715        }
29716    }
29717
29718    #[test]
29719    fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
29720        // The canonical per-`:politicas` `:retries` transient-failure-
29721        // retry-budget scalar pin: [`MeshPolicy::retries`] must return
29722        // the `:politicas :retries` typed `u32` verbatim as an
29723        // `Option<u32>`, byte-equal to the raw field access across every
29724        // representative value in the accept-set — `None` (cluster
29725        // default applies — typically "no retries beyond a single
29726        // dispatch attempt" the caixa-mesh `retry_overlay` builder
29727        // documents), `Some(1)` (the lower boundary of the
29728        // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
29729        // `AplicacaoSpec::validate_politicas` gate carves out on the
29730        // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
29731        // (the upper boundary the same gate carves out on the sibling
29732        // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
29733        // past-the-guard sentinel that pins the accessor doesn't perform
29734        // a silent bounds-collapse at the return path).
29735        //
29736        // Sibling of the peer per-`:politicas`
29737        // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
29738        // sibling `Option<Copy-T>` optional-scalar axis, extended to the
29739        // peer per-`:politicas` `Option<u32>` shape — second
29740        // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
29741        // Pins against a future silent detour that re-derived the retry
29742        // cap from a peer axis (an accidental `.circuit_breaker
29743        // .as_ref().map(|b| b.max_failures)` collapse that read the
29744        // breaker's max-failure count as a retry budget), a
29745        // `None → Some(0)` cluster-default projection (which would
29746        // silently re-introduce the `PolicyRetriesZero` refusal case at
29747        // the emit boundary), or a bounds-collapsing accessor that
29748        // clamped the return through `POLICY_RETRIES_MAX` (the
29749        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
29750        // must ship the raw slot verbatim so a validate-time gate
29751        // regression surfaces at the emit boundary rather than being
29752        // silently absorbed).
29753        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
29754            let p = MeshPolicy {
29755                retries,
29756                ..MeshPolicy::default()
29757            };
29758            assert_eq!(
29759                p.retries(),
29760                retries,
29761                "MeshPolicy::retries must return :politicas :retries \
29762                 verbatim (got {:?}, expected {retries:?})",
29763                p.retries(),
29764            );
29765            assert_eq!(
29766                p.retries(),
29767                p.retries,
29768                "MeshPolicy::retries must byte-equal the raw .retries \
29769                 field access across every value in the accept-set",
29770            );
29771        }
29772    }
29773
29774    #[test]
29775    fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
29776        // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
29777        // must key off [`MeshPolicy::retries`], not the raw `.retries`
29778        // field access. Structurally: toggling ONLY the `retries` slot
29779        // on an otherwise-default MeshPolicy must flip `is_empty()`
29780        // from `true` (all-`None`) to `false` (one axis carries a
29781        // value); the flip must be observed for every value in the
29782        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
29783        // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
29784        // the emptiness semantic reads "any axis carries a value" —
29785        // not "any axis carries a value the validate gate accepts" —
29786        // the same non-collapsing shape the peer M2
29787        // [`crate::LimitsSpec::is_empty`] /
29788        // [`crate::BehaviorSpec::is_empty`] predicates carry.
29789        //
29790        // Pins against a future silent detour that re-derived the
29791        // emptiness predicate off a peer axis (an accidental
29792        // `.rate_limit.is_none()`-only chain that dropped the
29793        // `retries` arm entirely), a `retries == Some(_)` collapse
29794        // that key-off a validate-gate-clamped bounds check (which
29795        // would silently classify a past-the-guard `Some(u32::MAX)`
29796        // as empty because it fails the `1..=POLICY_RETRIES_MAX`
29797        // check), or an accessor-side detour that no longer names the
29798        // substrate-primitive typed dispatch.
29799        //
29800        // Sibling of the peer per-`:politicas`
29801        // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
29802        // pin on the sibling `Option<Copy-T>` optional-scalar axis —
29803        // same "the emptiness predicate must route through the
29804        // substrate-primitive typed dispatch" discipline extended onto
29805        // the peer per-`:politicas` `Option<u32>` axis.
29806        let empty = MeshPolicy::default();
29807        assert!(
29808            empty.is_empty(),
29809            "MeshPolicy::default() must be is_empty() — every axis \
29810             defaults to None",
29811        );
29812        for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
29813            let p = MeshPolicy {
29814                retries,
29815                ..MeshPolicy::default()
29816            };
29817            assert!(
29818                !p.is_empty(),
29819                "MeshPolicy::is_empty must return false when \
29820                 :retries is {retries:?} — the emptiness \
29821                 predicate reads \"any axis carries a value\", not \
29822                 \"any axis carries a value the validate gate \
29823                 accepts\"",
29824            );
29825            assert_eq!(
29826                p.retries().is_none(),
29827                p.is_empty(),
29828                "when :retries is the only set axis, is_empty() \
29829                 must equal retries().is_none() — the accessor and \
29830                 the emptiness predicate must route through the same \
29831                 substrate-primitive typed dispatch on the :retries \
29832                 arm",
29833            );
29834        }
29835    }
29836
29837    #[test]
29838    fn mesh_policy_retries_projects_option_u32_by_copy() {
29839        // The by-copy pin: [`MeshPolicy::retries`] returns
29840        // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
29841        // accessor must return by value, not by reference. Sibling of
29842        // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
29843        // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
29844        // extended onto the sibling `Option<u32>` copy-invariant
29845        // shape — the accessor's returned `Option<u32>` must outlive
29846        // `&self` (multiple calls must return equal values from a
29847        // dropped-`&self` copy, since the returned Option carries no
29848        // borrow), and calling the accessor twice on the same
29849        // MeshPolicy must yield the same `Option<u32>` verbatim
29850        // (idempotent, no side effects on `&self`).
29851        //
29852        // Pins against a future silent detour that returned
29853        // `Option<&u32>` (which would type-check but silently break
29854        // every downstream caller — [`crate::render::single_field_overlay`]'s
29855        // first parameter is `Option<T: Clone>`, and `&u32` would
29856        // fold to a detached copy at the call site), an accidental
29857        // `Option::as_ref()` projection (`self.retries.as_ref()` would
29858        // also type-check but return `Option<&u32>`), or a one-arm-
29859        // only accessor that reads `Some(*n)` in the Some arm but
29860        // reads a fresh `Default::default()` (`0_u32`) in the None
29861        // arm.
29862        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
29863            let p = MeshPolicy {
29864                retries,
29865                ..MeshPolicy::default()
29866            };
29867            let first = p.retries();
29868            let second = p.retries();
29869            assert_eq!(
29870                first, second,
29871                "MeshPolicy::retries must be idempotent — two \
29872                 successive calls on the same &self must return the \
29873                 same Option<u32>",
29874            );
29875            assert_eq!(
29876                first, retries,
29877                "MeshPolicy::retries must return :politicas :retries \
29878                 verbatim by copy — got {first:?}, expected {retries:?}",
29879            );
29880        }
29881    }
29882
29883    #[test]
29884    fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
29885        // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
29886        // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
29887        // return the `:politicas :timeout` typed [`Duration`] verbatim
29888        // as an `Option<Duration>`, byte-equal to the raw field access
29889        // across every representative value in the accept-set — `None`
29890        // (cluster default applies — typically the gateway class's
29891        // implementation-side per-request wall-clock cap the caixa-mesh
29892        // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
29893        // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
29894        // set the surrounding `AplicacaoSpec::validate_politicas` gate
29895        // carves out on the sibling `PolicyTimeoutZero` /
29896        // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
29897        // (the upper boundary the same gate carves out on the sibling
29898        // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
29899        // (a past-the-guard sentinel that pins the accessor doesn't
29900        // perform a silent bounds-collapse into `None` on the zero-
29901        // Duration arm — validate rejects zero but the accessor must
29902        // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
29903        // past-the-guard sentinel that pins the accessor doesn't
29904        // perform a silent bounds-collapse at the return path).
29905        //
29906        // Sibling of the peer per-`:politicas`
29907        // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
29908        // `Option<u32>` optional-scalar axis and the peer per-
29909        // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
29910        // pin on the sibling `Option<bool>` optional-scalar axis,
29911        // extended onto the peer per-`:politicas` `Option<Duration>`
29912        // shape — third `Option<Copy-T>`-return accessor on the M3
29913        // mesh-slot family. Pins against a future silent detour that
29914        // re-derived the per-call cap from a peer axis (an accidental
29915        // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
29916        // read the breaker's rolling-window duration as a per-call
29917        // deadline), a `None → Some(Duration::MAX)` cluster-default
29918        // projection (which would silently re-introduce the
29919        // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
29920        // blocking" arm at the emit boundary), or a bounds-collapsing
29921        // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
29922        // (the `AplicacaoSpec::validate` gate owns the bounds; the
29923        // accessor must ship the raw slot verbatim so a validate-time
29924        // gate regression surfaces at the emit boundary rather than
29925        // being silently absorbed).
29926        for timeout in [
29927            None,
29928            Some(Duration::from_millis(1)),
29929            Some(POLICY_TIMEOUT_MAX),
29930            Some(Duration::ZERO),
29931            Some(Duration::MAX),
29932        ] {
29933            let p = MeshPolicy {
29934                timeout,
29935                ..MeshPolicy::default()
29936            };
29937            assert_eq!(
29938                p.timeout(),
29939                timeout,
29940                "MeshPolicy::timeout must return :politicas :timeout \
29941                 verbatim (got {:?}, expected {timeout:?})",
29942                p.timeout(),
29943            );
29944            assert_eq!(
29945                p.timeout(),
29946                p.timeout,
29947                "MeshPolicy::timeout must byte-equal the raw .timeout \
29948                 field access across every value in the accept-set",
29949            );
29950        }
29951    }
29952
29953    #[test]
29954    fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
29955        // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
29956        // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
29957        // field access. Structurally: toggling ONLY the `timeout` slot
29958        // on an otherwise-default MeshPolicy must flip `is_empty()`
29959        // from `true` (all-`None`) to `false` (one axis carries a
29960        // value); the flip must be observed for every value in the
29961        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
29962        // gate accepts (`Some(Duration::from_millis(1))`,
29963        // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
29964        // reads "any axis carries a value" — not "any axis carries a
29965        // value the validate gate accepts" — the same non-collapsing
29966        // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
29967        // [`crate::BehaviorSpec::is_empty`] predicates carry.
29968        //
29969        // Pins against a future silent detour that re-derived the
29970        // emptiness predicate off a peer axis (an accidental
29971        // `.rate_limit.is_none()`-only chain that dropped the
29972        // `timeout` arm entirely), a `timeout == Some(_)` collapse
29973        // that key-off a validate-gate-clamped bounds check (which
29974        // would silently classify a past-the-guard `Some(Duration::MAX)`
29975        // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
29976        // check), or an accessor-side detour that no longer names the
29977        // substrate-primitive typed dispatch.
29978        //
29979        // Sibling of the peer per-`:politicas`
29980        // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
29981        // the sibling `Option<u32>` optional-scalar axis and the peer
29982        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
29983        // accessor-composition pin on the sibling `Option<bool>`
29984        // optional-scalar axis — same "the emptiness predicate must
29985        // route through the substrate-primitive typed dispatch"
29986        // discipline extended onto the peer per-`:politicas`
29987        // `Option<Duration>` axis.
29988        let empty = MeshPolicy::default();
29989        assert!(
29990            empty.is_empty(),
29991            "MeshPolicy::default() must be is_empty() — every axis \
29992             defaults to None",
29993        );
29994        for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
29995            let p = MeshPolicy {
29996                timeout,
29997                ..MeshPolicy::default()
29998            };
29999            assert!(
30000                !p.is_empty(),
30001                "MeshPolicy::is_empty must return false when \
30002                 :timeout is {timeout:?} — the emptiness \
30003                 predicate reads \"any axis carries a value\", not \
30004                 \"any axis carries a value the validate gate \
30005                 accepts\"",
30006            );
30007            assert_eq!(
30008                p.timeout().is_none(),
30009                p.is_empty(),
30010                "when :timeout is the only set axis, is_empty() \
30011                 must equal timeout().is_none() — the accessor and \
30012                 the emptiness predicate must route through the same \
30013                 substrate-primitive typed dispatch on the :timeout \
30014                 arm",
30015            );
30016        }
30017    }
30018
30019    #[test]
30020    fn mesh_policy_timeout_projects_option_duration_by_copy() {
30021        // The by-copy pin: [`MeshPolicy::timeout`] returns
30022        // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
30023        // and the accessor must return by value, not by reference.
30024        // Sibling of the peer per-`:politicas`
30025        // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
30026        // sibling `Option<u32>` optional-scalar axis and the peer
30027        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
30028        // by-copy pin on the sibling `Option<bool>` optional-scalar
30029        // axis, extended onto the peer per-`:politicas`
30030        // `Option<Duration>` copy-invariant shape — the accessor's
30031        // returned `Option<Duration>` must outlive `&self` (multiple
30032        // calls must return equal values from a dropped-`&self`
30033        // copy, since the returned Option carries no borrow), and
30034        // calling the accessor twice on the same MeshPolicy must
30035        // yield the same `Option<Duration>` verbatim (idempotent, no
30036        // side effects on `&self`).
30037        //
30038        // Pins against a future silent detour that returned
30039        // `Option<&Duration>` (which would type-check but silently
30040        // break every downstream caller — [`crate::render::single_field_overlay`]'s
30041        // first parameter is `Option<T: Clone>`, and `&Duration`
30042        // would fold to a detached copy at the call site), an
30043        // accidental `Option::as_ref()` projection
30044        // (`self.timeout.as_ref()` would also type-check but return
30045        // `Option<&Duration>`), or a one-arm-only accessor that
30046        // reads `Some(*d)` in the Some arm but reads a fresh
30047        // `Default::default()` (`Duration::ZERO`) in the None arm
30048        // (which would silently re-classify every unset `:timeout`
30049        // as the `PolicyTimeoutZero`-refused zero-Duration value at
30050        // the accessor boundary).
30051        for timeout in [
30052            None,
30053            Some(Duration::from_millis(1)),
30054            Some(POLICY_TIMEOUT_MAX),
30055            Some(Duration::ZERO),
30056            Some(Duration::MAX),
30057        ] {
30058            let p = MeshPolicy {
30059                timeout,
30060                ..MeshPolicy::default()
30061            };
30062            let first = p.timeout();
30063            let second = p.timeout();
30064            assert_eq!(
30065                first, second,
30066                "MeshPolicy::timeout must be idempotent — two \
30067                 successive calls on the same &self must return the \
30068                 same Option<Duration>",
30069            );
30070            assert_eq!(
30071                first, timeout,
30072                "MeshPolicy::timeout must return :politicas :timeout \
30073                 verbatim by copy — got {first:?}, expected {timeout:?}",
30074            );
30075        }
30076    }
30077
30078    #[test]
30079    fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
30080        // The canonical per-`:politicas` `:rate-limit` Envoy-
30081        // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
30082        // [`MeshPolicy::rate_limit`] must return the `:politicas
30083        // :rate-limit` typed [`RateLimit`] verbatim as an
30084        // `Option<RateLimit>`, byte-equal to the raw field access
30085        // across every representative value in the accept-set — `None`
30086        // (cluster default applies — no per-Aplicacao rate declaration,
30087        // the gateway-class per-listener default arm the future caixa-
30088        // mesh `local_rate_limit_overlay` emitter documents),
30089        // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
30090        // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
30091        // accept-set the surrounding
30092        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
30093        // sibling `PolicyRateLimitZero` refusal, paired with the
30094        // canonical-window "1 second" arm of the three-unit
30095        // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
30096        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
30097        // (the upper boundary the same gate carves out on the sibling
30098        // `PolicyRateLimitExceedsCap` refusal, paired with the
30099        // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
30100        // (a past-the-guard sentinel that pins the accessor doesn't
30101        // perform a silent bounds-collapse into `None` on the
30102        // zero-rate/zero-window arm — validate rejects zero but the
30103        // accessor must ship the raw slot verbatim so a validate-time
30104        // gate regression surfaces at the emit boundary rather than
30105        // being silently absorbed), and
30106        // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
30107        // (a past-the-guard sentinel that pins the accessor doesn't
30108        // perform a silent bounds-collapse at the return path).
30109        //
30110        // First `Option<Copy-composite-T>`-return accessor pin on the
30111        // M3 mesh-slot family (peer of the sibling per-`:politicas`
30112        // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
30113        // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
30114        // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
30115        // Copy accessor pins, extended onto the peer per-`:politicas`
30116        // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
30117        // and the accessor returns by value). Pins against a future
30118        // silent detour that re-derived the rate declaration from a
30119        // peer axis (an accidental
30120        // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
30121        // collapse that read the breaker's trip threshold + rolling
30122        // window as a rate declaration), a `None → Some(default())`
30123        // cluster-default projection (which would silently re-
30124        // introduce a "cluster default is 0/s" arm the emit boundary
30125        // would take as "declared but inert" — the canonical
30126        // declared-but-inert footgun the sibling
30127        // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
30128        // amplification-shape axis), a bounds-collapsing accessor
30129        // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
30130        // clamped `rl.window` through [`is_canonical_rate_limit_window`]
30131        // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
30132        // accessor must ship the raw slot verbatim), or a
30133        // by-reference detour (`Option<&RateLimit>`) that broke every
30134        // downstream consumer keying off `Option<RateLimit>` by-copy.
30135        for rl in [
30136            None,
30137            Some(RateLimit {
30138                rate: 1,
30139                window: Duration::from_secs(1),
30140            }),
30141            Some(RateLimit {
30142                rate: POLICY_RATE_LIMIT_MAX,
30143                window: Duration::from_secs(3600),
30144            }),
30145            Some(RateLimit {
30146                rate: 0,
30147                window: Duration::ZERO,
30148            }),
30149            Some(RateLimit {
30150                rate: u32::MAX,
30151                window: Duration::MAX,
30152            }),
30153        ] {
30154            let p = MeshPolicy {
30155                rate_limit: rl,
30156                ..MeshPolicy::default()
30157            };
30158            assert_eq!(
30159                p.rate_limit(),
30160                rl,
30161                "MeshPolicy::rate_limit must return :politicas :rate-limit \
30162                 verbatim (got {:?}, expected {rl:?})",
30163                p.rate_limit(),
30164            );
30165            assert_eq!(
30166                p.rate_limit(),
30167                p.rate_limit,
30168                "MeshPolicy::rate_limit must byte-equal the raw \
30169                 .rate_limit field access across every value in the \
30170                 accept-set",
30171            );
30172        }
30173    }
30174
30175    #[test]
30176    fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
30177        // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
30178        // must key off [`MeshPolicy::rate_limit`], not the raw
30179        // `.rate_limit` field access. Structurally: toggling ONLY the
30180        // `rate_limit` slot on an otherwise-default MeshPolicy must
30181        // flip `is_empty()` from `true` (all-`None`) to `false` (one
30182        // axis carries a value); the flip must be observed for every
30183        // representative value in the accept-set the surrounding
30184        // [`AplicacaoSpec::validate_politicas`] gate accepts
30185        // (`Some(RateLimit { rate: 1, window: 1s })`,
30186        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
30187        // since the emptiness semantic reads "any axis carries a
30188        // value" — not "any axis carries a value the validate gate
30189        // accepts" — the same non-collapsing shape the peer M2
30190        // [`crate::LimitsSpec::is_empty`] /
30191        // [`crate::BehaviorSpec::is_empty`] predicates carry.
30192        //
30193        // Pins against a future silent detour that re-derived the
30194        // emptiness predicate off a peer axis (an accidental
30195        // `.timeout.is_none()`-only chain that dropped the
30196        // `rate_limit` arm entirely — the last unlifted inline field
30197        // access on `is_empty` before this lift), a `rate_limit ==
30198        // Some(_)` collapse that key-off a validate-gate-clamped
30199        // bounds check (which would silently classify a past-the-
30200        // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
30201        // because it fails the value-shape gate), or an accessor-
30202        // side detour that no longer names the substrate-primitive
30203        // typed dispatch.
30204        //
30205        // Fourth "the emptiness predicate must route through the
30206        // substrate-primitive typed dispatch" composition pin on the
30207        // M3 mesh-slot family — closes the last unlifted composition
30208        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
30209        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
30210        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
30211        // 7073d0f is_empty-composition pins on the sibling primitive-
30212        // Copy axes, extended onto the peer per-`:politicas`
30213        // composite-Copy `Option<RateLimit>` axis).
30214        let empty = MeshPolicy::default();
30215        assert!(
30216            empty.is_empty(),
30217            "MeshPolicy::default() must be is_empty() — every axis \
30218             defaults to None",
30219        );
30220        for rl in [
30221            RateLimit {
30222                rate: 1,
30223                window: Duration::from_secs(1),
30224            },
30225            RateLimit {
30226                rate: POLICY_RATE_LIMIT_MAX,
30227                window: Duration::from_secs(3600),
30228            },
30229        ] {
30230            let p = MeshPolicy {
30231                rate_limit: Some(rl),
30232                ..MeshPolicy::default()
30233            };
30234            assert!(
30235                !p.is_empty(),
30236                "MeshPolicy::is_empty must return false when \
30237                 :rate-limit is {rl:?} — the emptiness predicate \
30238                 reads \"any axis carries a value\", not \"any axis \
30239                 carries a value the validate gate accepts\"",
30240            );
30241            assert_eq!(
30242                p.rate_limit().is_none(),
30243                p.is_empty(),
30244                "when :rate-limit is the only set axis, is_empty() \
30245                 must equal rate_limit().is_none() — the accessor \
30246                 and the emptiness predicate must route through the \
30247                 same substrate-primitive typed dispatch on the \
30248                 :rate-limit arm",
30249            );
30250        }
30251    }
30252
30253    #[test]
30254    fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
30255        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
30256        // `:rate-limit` value-shape gate must key off
30257        // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
30258        // field bind. Structurally: a `MeshPolicy` whose only set
30259        // axis is a `Some(RateLimit { rate: 0, .. })` must surface
30260        // the `PolicyRateLimitZero` refusal exactly, and the same
30261        // MeshPolicy with the rate at the canonical lower boundary
30262        // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
30263        // The pair jointly pins the accessor + validate-gate
30264        // composition: any future silent detour that had the accessor
30265        // omit the `Some(RateLimit { rate: 0, .. })` arm (a
30266        // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
30267        // silently absorb the `PolicyRateLimitZero` refusal at the
30268        // accessor boundary — the composition pin catches that at
30269        // caixa-core build time.
30270        //
30271        // Sibling of the peer [`validate_politicas`]
30272        // `:mtls-required` / `:retries` / `:timeout` composition pins
30273        // on the sibling primitive-Copy optional-scalar axes — same
30274        // "the validate / shape-gate predicate must route through the
30275        // substrate-primitive typed dispatch" discipline extended
30276        // onto the peer per-`:politicas` composite-Copy
30277        // `Option<RateLimit>` axis. Second composition-with-accessor
30278        // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
30279        // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
30280        let mut spec = three_member_spec();
30281        spec.politicas = MeshPolicy {
30282            rate_limit: Some(RateLimit {
30283                rate: 0,
30284                window: Duration::from_secs(1),
30285            }),
30286            ..MeshPolicy::default()
30287        };
30288        assert!(
30289            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
30290            "validate_politicas must reject rate == 0 with \
30291             PolicyRateLimitZero — the accessor and the validate gate \
30292             must route through the same substrate-primitive typed \
30293             dispatch on the :rate-limit zero-floor arm",
30294        );
30295        spec.politicas = MeshPolicy {
30296            rate_limit: Some(RateLimit {
30297                rate: 1,
30298                window: Duration::from_secs(1),
30299            }),
30300            ..MeshPolicy::default()
30301        };
30302        assert!(
30303            spec.validate().is_ok(),
30304            "validate_politicas must accept rate == 1 (the canonical \
30305             lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
30306             set) with a canonical 1s window",
30307        );
30308    }
30309
30310    #[test]
30311    fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
30312        // The canonical per-`:politicas` `:circuit-breaker` Envoy-
30313        // `outlier_detection`-mesh consecutive-failure-ejection scalar
30314        // pin: [`MeshPolicy::circuit_breaker`] must return the
30315        // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
30316        // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
30317        // raw field access across every representative value in the
30318        // accept-set — `None` (cluster default applies — no
30319        // per-Aplicacao breaker declaration, the gateway-class per-
30320        // listener default arm the future caixa-mesh
30321        // `outlier_detection_overlay` emitter documents),
30322        // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
30323        // (the lower boundary of the accept-set the surrounding
30324        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
30325        // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
30326        // refusals),
30327        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
30328        // (the upper boundary the same gate carves out on the sibling
30329        // `PolicyBreakerMaxFailuresExceedsCap` /
30330        // `PolicyBreakerWindowExceedsCap` refusals),
30331        // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
30332        // (a past-the-guard sentinel that pins the accessor doesn't
30333        // perform a silent bounds-collapse into `None` on the
30334        // zero-failures/zero-window arm — validate rejects zero but
30335        // the accessor must ship the raw slot verbatim so a validate-
30336        // time gate regression surfaces at the emit boundary rather
30337        // than being silently absorbed), and
30338        // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
30339        // (a past-the-guard sentinel that pins the accessor doesn't
30340        // perform a silent bounds-collapse at the return path).
30341        //
30342        // Second `Option<Copy-composite-T>`-return accessor pin on the
30343        // M3 mesh-slot family (peer of the sibling per-`:politicas`
30344        // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
30345        // composite-Copy accessor pin, and of the sibling per-
30346        // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
30347        // [`MeshPolicy::retries`] bdfb399 /
30348        // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
30349        // accessor pins). Pins against a future silent detour that
30350        // re-derived the breaker declaration from a peer axis (an
30351        // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
30352        // collapse that read the rate-limit's bucket capacity + refill
30353        // period as a breaker declaration), a `None → Some(default())`
30354        // cluster-default projection (which would silently re-
30355        // introduce the `PolicyBreakerZeroFailures` /
30356        // `PolicyBreakerZeroWindow` refusal cases at the emit
30357        // boundary), a bounds-collapsing accessor that clamped
30358        // `cb.max_failures` through
30359        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
30360        // through [`POLICY_BREAKER_WINDOW_MAX`] (the
30361        // [`AplicacaoSpec::validate`] gate owns the bounds; the
30362        // accessor must ship the raw slot verbatim), or a
30363        // by-reference detour (`Option<&CircuitBreaker>`) that broke
30364        // every downstream consumer keying off `Option<CircuitBreaker>`
30365        // by-copy.
30366        for cb in [
30367            None,
30368            Some(CircuitBreaker {
30369                max_failures: 1,
30370                window: Duration::from_millis(1),
30371            }),
30372            Some(CircuitBreaker {
30373                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
30374                window: POLICY_BREAKER_WINDOW_MAX,
30375            }),
30376            Some(CircuitBreaker {
30377                max_failures: 0,
30378                window: Duration::ZERO,
30379            }),
30380            Some(CircuitBreaker {
30381                max_failures: u32::MAX,
30382                window: Duration::MAX,
30383            }),
30384        ] {
30385            let p = MeshPolicy {
30386                circuit_breaker: cb,
30387                ..MeshPolicy::default()
30388            };
30389            assert_eq!(
30390                p.circuit_breaker(),
30391                cb,
30392                "MeshPolicy::circuit_breaker must return :politicas \
30393                 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
30394                p.circuit_breaker(),
30395            );
30396            assert_eq!(
30397                p.circuit_breaker(),
30398                p.circuit_breaker,
30399                "MeshPolicy::circuit_breaker must byte-equal the raw \
30400                 .circuit_breaker field access across every value in \
30401                 the accept-set",
30402            );
30403        }
30404    }
30405
30406    #[test]
30407    fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
30408        // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
30409        // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
30410        // `.circuit_breaker` field access. Structurally: toggling ONLY
30411        // the `circuit_breaker` slot on an otherwise-default MeshPolicy
30412        // must flip `is_empty()` from `true` (all-`None`) to `false`
30413        // (one axis carries a value); the flip must be observed for
30414        // every representative value in the accept-set the surrounding
30415        // [`AplicacaoSpec::validate_politicas`] gate accepts
30416        // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
30417        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
30418        // since the emptiness semantic reads "any axis carries a
30419        // value" — not "any axis carries a value the validate gate
30420        // accepts" — the same non-collapsing shape the peer M2
30421        // [`crate::LimitsSpec::is_empty`] /
30422        // [`crate::BehaviorSpec::is_empty`] predicates carry.
30423        //
30424        // Pins against a future silent detour that re-derived the
30425        // emptiness predicate off a peer axis (an accidental
30426        // `.rate_limit.is_none()`-only chain that dropped the
30427        // `circuit_breaker` arm entirely — the last unlifted inline
30428        // field access on `is_empty` before this lift), a
30429        // `circuit_breaker == Some(_)` collapse that key-off a
30430        // validate-gate-clamped bounds check (which would silently
30431        // classify a past-the-guard `Some(CircuitBreaker { max_failures:
30432        // 0, window: 0s })` as empty because it fails the value-shape
30433        // gate), or an accessor-side detour that no longer names the
30434        // substrate-primitive typed dispatch.
30435        //
30436        // Fifth "the emptiness predicate must route through the
30437        // substrate-primitive typed dispatch" composition pin on the
30438        // M3 mesh-slot family — closes the last unlifted composition
30439        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
30440        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
30441        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
30442        // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
30443        // composition pins on the sibling primitive-Copy + composite-
30444        // Copy axes, extended onto the peer per-`:politicas`
30445        // composite-Copy `Option<CircuitBreaker>` axis).
30446        let empty = MeshPolicy::default();
30447        assert!(
30448            empty.is_empty(),
30449            "MeshPolicy::default() must be is_empty() — every axis \
30450             defaults to None",
30451        );
30452        for cb in [
30453            CircuitBreaker {
30454                max_failures: 1,
30455                window: Duration::from_millis(1),
30456            },
30457            CircuitBreaker {
30458                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
30459                window: POLICY_BREAKER_WINDOW_MAX,
30460            },
30461        ] {
30462            let p = MeshPolicy {
30463                circuit_breaker: Some(cb),
30464                ..MeshPolicy::default()
30465            };
30466            assert!(
30467                !p.is_empty(),
30468                "MeshPolicy::is_empty must return false when \
30469                 :circuit-breaker is {cb:?} — the emptiness predicate \
30470                 reads \"any axis carries a value\", not \"any axis \
30471                 carries a value the validate gate accepts\"",
30472            );
30473            assert_eq!(
30474                p.circuit_breaker().is_none(),
30475                p.is_empty(),
30476                "when :circuit-breaker is the only set axis, \
30477                 is_empty() must equal circuit_breaker().is_none() — \
30478                 the accessor and the emptiness predicate must route \
30479                 through the same substrate-primitive typed dispatch \
30480                 on the :circuit-breaker arm",
30481            );
30482        }
30483    }
30484
30485    #[test]
30486    fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
30487        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
30488        // `:circuit-breaker` value-shape gate must key off
30489        // [`MeshPolicy::circuit_breaker`], not the raw
30490        // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
30491        // whose only set axis is a `Some(CircuitBreaker { max_failures:
30492        // 0, .. })` must surface the `PolicyBreakerZeroFailures`
30493        // refusal exactly, and the same MeshPolicy with the breaker at
30494        // the canonical lower boundary
30495        // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
30496        // pass validate. The pair jointly pins the accessor +
30497        // validate-gate composition: any future silent detour that had
30498        // the accessor omit the `Some(CircuitBreaker { max_failures:
30499        // 0, .. })` arm (a
30500        // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
30501        // collapse) would silently absorb the
30502        // `PolicyBreakerZeroFailures` refusal at the accessor
30503        // boundary — the composition pin catches that at caixa-core
30504        // build time.
30505        //
30506        // Sibling of the peer [`validate_politicas`]
30507        // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
30508        // composition pins on the sibling primitive-Copy + composite-
30509        // Copy optional-scalar axes — same "the validate / shape-gate
30510        // predicate must route through the substrate-primitive typed
30511        // dispatch" discipline extended onto the peer per-`:politicas`
30512        // composite-Copy `Option<CircuitBreaker>` axis. Second
30513        // composition-with-accessor pin on the M3 mesh-slot
30514        // `Option<CircuitBreaker>` arm alongside the
30515        // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
30516        let mut spec = three_member_spec();
30517        spec.politicas = MeshPolicy {
30518            circuit_breaker: Some(CircuitBreaker {
30519                max_failures: 0,
30520                window: Duration::from_millis(1),
30521            }),
30522            ..MeshPolicy::default()
30523        };
30524        assert!(
30525            matches!(
30526                spec.validate(),
30527                Err(AplicacaoError::PolicyBreakerZeroFailures)
30528            ),
30529            "validate_politicas must reject max_failures == 0 with \
30530             PolicyBreakerZeroFailures — the accessor and the validate \
30531             gate must route through the same substrate-primitive \
30532             typed dispatch on the :circuit-breaker zero-floor arm",
30533        );
30534        spec.politicas = MeshPolicy {
30535            circuit_breaker: Some(CircuitBreaker {
30536                max_failures: 1,
30537                window: Duration::from_millis(1),
30538            }),
30539            ..MeshPolicy::default()
30540        };
30541        assert!(
30542            spec.validate().is_ok(),
30543            "validate_politicas must accept a CircuitBreaker at the \
30544             canonical lower boundary (max_failures = 1, window = \
30545             1ms) — the accessor and the validate gate must route \
30546             through the same substrate-primitive typed dispatch on \
30547             the :circuit-breaker arm",
30548        );
30549    }
30550
30551    #[test]
30552    fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
30553        // The canonical per-`:politicas :circuit-breaker` `:max-failures`
30554        // Envoy-outlier-detection trip-threshold scalar pin:
30555        // [`CircuitBreaker::max_failures`] must return the
30556        // `:politicas :circuit-breaker :max-failures` typed `u32`
30557        // verbatim, byte-equal to the raw field access across every
30558        // representative value in the accept-set — `1` (the lower
30559        // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
30560        // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
30561        // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
30562        // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
30563        // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
30564        // refusal), `0` (a past-the-guard sentinel that pins the accessor
30565        // doesn't perform a silent bounds-collapse into `1` on the zero
30566        // arm — validate rejects zero but the accessor must ship the
30567        // raw slot verbatim so a validate-time gate regression surfaces
30568        // at the emit boundary rather than being silently absorbed),
30569        // `u32::MAX` (a past-the-guard sentinel that pins the accessor
30570        // doesn't perform a silent bounds-collapse through
30571        // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
30572        //
30573        // First sub-struct required-scalar accessor pin on the M3
30574        // mesh-slot family — sibling in shape to the peer per-`:membros`
30575        // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
30576        // (a40b0e3) required-`String`-carry accessor pins and the peer
30577        // per-`:contratos` [`WitContract::source`] /
30578        // [`WitContract::destination`] (7f0fd43) required-`String`-carry
30579        // accessor pins, extended onto the peer per-`CircuitBreaker`
30580        // required-`u32` scalar-value axis. Pins against a future silent
30581        // detour that re-derived the trip threshold from a peer axis (an
30582        // accidental `self.window.as_secs() as u32` collapse that read
30583        // the breaker's rolling-window duration as a failure count), a
30584        // `0 → 1` cluster-default projection (which would silently absorb
30585        // the `PolicyBreakerZeroFailures` refusal case at the accessor
30586        // boundary), or a bounds-collapsing accessor that clamped the
30587        // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
30588        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
30589        // must ship the raw slot verbatim).
30590        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
30591            let cb = CircuitBreaker {
30592                max_failures,
30593                window: Duration::from_secs(60),
30594            };
30595            assert_eq!(
30596                cb.max_failures(),
30597                max_failures,
30598                "CircuitBreaker::max_failures must return :politicas \
30599                 :circuit-breaker :max-failures verbatim (got {}, \
30600                 expected {max_failures})",
30601                cb.max_failures(),
30602            );
30603            assert_eq!(
30604                cb.max_failures(),
30605                cb.max_failures,
30606                "CircuitBreaker::max_failures must byte-equal the raw \
30607                 .max_failures field access across every value in the \
30608                 u32 accept-set",
30609            );
30610        }
30611    }
30612
30613    #[test]
30614    fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
30615        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
30616        // `:circuit-breaker :max-failures` zero-floor arm must key off
30617        // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
30618        // field access. Structurally: a `CircuitBreaker { max_failures:
30619        // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
30620        // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
30621        // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
30622        // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
30623        // pass validate. The pair jointly pins the accessor +
30624        // validate-gate composition: any future silent detour that had
30625        // the accessor return a fresh `1` on the zero arm (a
30626        // `.max_failures().max(1)` collapse) would silently absorb the
30627        // `PolicyBreakerZeroFailures` refusal at the accessor boundary
30628        // and the validate gate would accept a struct-literal
30629        // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
30630        // catches that at caixa-core build time.
30631        //
30632        // Peer of the sibling per-`:politicas`
30633        // [`MeshPolicy::mtls_required`] (c0110f1) /
30634        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
30635        // (7073d0f) accessor-composition pins on the sibling optional-
30636        // scalar axes — same "the validate / shape-gate predicate must
30637        // route through the substrate-primitive typed dispatch"
30638        // discipline extended onto the peer per-`CircuitBreaker`
30639        // required-scalar composition axis.
30640        let mut spec = three_member_spec();
30641        spec.politicas = MeshPolicy {
30642            circuit_breaker: Some(CircuitBreaker {
30643                max_failures: 0,
30644                window: Duration::from_secs(60),
30645            }),
30646            ..MeshPolicy::default()
30647        };
30648        assert!(
30649            matches!(
30650                spec.validate(),
30651                Err(AplicacaoError::PolicyBreakerZeroFailures)
30652            ),
30653            "validate_politicas must reject max_failures == 0 with \
30654             PolicyBreakerZeroFailures — the accessor and the validate \
30655             gate must route through the same substrate-primitive typed \
30656             dispatch on the :max-failures zero-floor arm",
30657        );
30658        spec.politicas = MeshPolicy {
30659            circuit_breaker: Some(CircuitBreaker {
30660                max_failures: 1,
30661                window: Duration::from_secs(60),
30662            }),
30663            ..MeshPolicy::default()
30664        };
30665        assert!(
30666            spec.validate().is_ok(),
30667            "validate_politicas must accept max_failures == 1 (the \
30668             lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
30669             accept-set)",
30670        );
30671    }
30672
30673    #[test]
30674    fn circuit_breaker_max_failures_projects_u32_by_copy() {
30675        // The by-copy pin: [`CircuitBreaker::max_failures`] returns
30676        // `u32` by copy — `u32` is `Copy` and the accessor must return
30677        // by value, not by reference. Peer of the sibling
30678        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
30679        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
30680        // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
30681        // optional-scalar axes, extended onto the peer
30682        // per-`CircuitBreaker` required-`u32` copy-invariant shape —
30683        // the accessor's returned `u32` must outlive `&self` (multiple
30684        // calls must return equal values from a dropped-`&self` copy,
30685        // since the returned scalar carries no borrow), and calling
30686        // the accessor twice on the same CircuitBreaker must yield the
30687        // same `u32` verbatim (idempotent, no side effects on `&self`).
30688        //
30689        // Pins against a future silent detour that returned `&u32`
30690        // (which would type-check but silently break every downstream
30691        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
30692        // first parameter is `u32`, and `&u32` would fold to a detached
30693        // copy at the call site with a `*` deref the sibling accessors
30694        // don't need), an accidental `.max_failures.wrapping_add(0)`
30695        // detour that returned a fresh copy through an arithmetic
30696        // no-op (breaking a future `const fn` regression), or a
30697        // one-arm-only accessor that returned a saturating value on
30698        // some sentinel input (breaking the pass-through invariant the
30699        // sibling required-scalar accessors carry).
30700        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
30701            let cb = CircuitBreaker {
30702                max_failures,
30703                window: Duration::from_secs(60),
30704            };
30705            let first = cb.max_failures();
30706            let second = cb.max_failures();
30707            assert_eq!(
30708                first, second,
30709                "CircuitBreaker::max_failures must be idempotent — two \
30710                 successive calls on the same &self must return the \
30711                 same u32",
30712            );
30713            assert_eq!(
30714                first, max_failures,
30715                "CircuitBreaker::max_failures must return :politicas \
30716                 :circuit-breaker :max-failures verbatim by copy — \
30717                 got {first}, expected {max_failures}",
30718            );
30719        }
30720    }
30721
30722    #[test]
30723    fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
30724        // The canonical per-`:politicas :circuit-breaker` `:window`
30725        // Envoy-outlier-detection rolling-observation-interval scalar
30726        // pin: [`CircuitBreaker::window`] must return the
30727        // `:politicas :circuit-breaker :window` typed `Duration`
30728        // verbatim, byte-equal to the raw field access across every
30729        // representative value in the accept-set — `Duration::from_millis(1)`
30730        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
30731        // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
30732        // gate carves out on the sibling `PolicyBreakerZeroWindow`
30733        // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
30734        // same gate carves out on the sibling
30735        // `PolicyBreakerWindowExceedsCap` refusal),
30736        // `Duration::ZERO` (a past-the-guard sentinel that pins the
30737        // accessor doesn't perform a silent bounds-collapse into
30738        // `Duration::from_millis(1)` on the zero arm — validate rejects
30739        // zero but the accessor must ship the raw slot verbatim so a
30740        // validate-time gate regression surfaces at the emit boundary
30741        // rather than being silently absorbed),
30742        // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
30743        // far above the 1h cap — that pins the accessor doesn't perform
30744        // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
30745        // at the return path).
30746        //
30747        // Second sub-struct required-scalar accessor pin on the M3
30748        // mesh-slot family — sibling in shape to the just-landed
30749        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
30750        // (3a74062) required-`u32` accessor pin on the peer
30751        // per-`CircuitBreaker` required-axis, extended onto the
30752        // per-sub-struct required-`Duration` axis. Pins against a
30753        // future silent detour that re-derived the observation window
30754        // from a peer axis (an accidental
30755        // `Duration::from_secs(self.max_failures as u64)` collapse that
30756        // read the breaker's trip count as an observation-interval
30757        // duration), a `Duration::ZERO → Duration::from_millis(1)`
30758        // cluster-default projection (which would silently absorb the
30759        // `PolicyBreakerZeroWindow` refusal case at the accessor
30760        // boundary), or a bounds-collapsing accessor that clamped the
30761        // return through `POLICY_BREAKER_WINDOW_MAX` (the
30762        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
30763        // must ship the raw slot verbatim).
30764        for window in [
30765            Duration::from_millis(1),
30766            POLICY_BREAKER_WINDOW_MAX,
30767            Duration::ZERO,
30768            Duration::from_secs(86_400),
30769        ] {
30770            let cb = CircuitBreaker {
30771                max_failures: 5,
30772                window,
30773            };
30774            assert_eq!(
30775                cb.window(),
30776                window,
30777                "CircuitBreaker::window must return :politicas \
30778                 :circuit-breaker :window verbatim (got {:?}, \
30779                 expected {window:?})",
30780                cb.window(),
30781            );
30782            assert_eq!(
30783                cb.window(),
30784                cb.window,
30785                "CircuitBreaker::window must byte-equal the raw \
30786                 .window field access across every value in the \
30787                 Duration accept-set",
30788            );
30789        }
30790    }
30791
30792    #[test]
30793    fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
30794        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
30795        // `:circuit-breaker :window` zero-floor arm must key off
30796        // [`CircuitBreaker::window`], not the raw `.window` field
30797        // access. Structurally: a `CircuitBreaker { window:
30798        // Duration::ZERO, .. }` embedded in a
30799        // `:politicas :circuit-breaker` slot must surface the
30800        // `PolicyBreakerZeroWindow` refusal exactly, and a
30801        // `CircuitBreaker { window: Duration::from_millis(1), .. }`
30802        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
30803        // accept-set) must pass validate. The pair jointly pins the
30804        // accessor + validate-gate composition: any future silent
30805        // detour that had the accessor return a fresh
30806        // `Duration::from_millis(1)` on the zero arm (a
30807        // `.window().max(Duration::from_millis(1))` collapse) would
30808        // silently absorb the `PolicyBreakerZeroWindow` refusal at the
30809        // accessor boundary and the validate gate would accept a
30810        // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
30811        // — the composition pin catches that at caixa-core build time.
30812        //
30813        // Peer of the sibling per-`CircuitBreaker`
30814        // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
30815        // pin on the peer required-scalar `:max-failures` axis — same
30816        // "the validate / shape-gate predicate must route through the
30817        // substrate-primitive typed dispatch" discipline extended onto
30818        // the peer per-`CircuitBreaker` required-`Duration` composition
30819        // axis.
30820        let mut spec = three_member_spec();
30821        spec.politicas = MeshPolicy {
30822            circuit_breaker: Some(CircuitBreaker {
30823                max_failures: 5,
30824                window: Duration::ZERO,
30825            }),
30826            ..MeshPolicy::default()
30827        };
30828        assert!(
30829            matches!(
30830                spec.validate(),
30831                Err(AplicacaoError::PolicyBreakerZeroWindow)
30832            ),
30833            "validate_politicas must reject window == Duration::ZERO \
30834             with PolicyBreakerZeroWindow — the accessor and the \
30835             validate gate must route through the same substrate-\
30836             primitive typed dispatch on the :window zero-floor arm",
30837        );
30838        spec.politicas = MeshPolicy {
30839            circuit_breaker: Some(CircuitBreaker {
30840                max_failures: 5,
30841                window: Duration::from_millis(1),
30842            }),
30843            ..MeshPolicy::default()
30844        };
30845        assert!(
30846            spec.validate().is_ok(),
30847            "validate_politicas must accept window == \
30848             Duration::from_millis(1) (the lower boundary of the \
30849             1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
30850        );
30851    }
30852
30853    #[test]
30854    fn circuit_breaker_window_projects_duration_by_copy() {
30855        // The by-copy pin: [`CircuitBreaker::window`] returns
30856        // `Duration` by copy — `Duration` is `Copy` and the accessor
30857        // must return by value, not by reference. Peer of the sibling
30858        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
30859        // (3a74062) by-copy pin on the peer required-scalar
30860        // `:max-failures` axis, extended onto the peer
30861        // per-`CircuitBreaker` required-`Duration` copy-invariant shape
30862        // — the accessor's returned `Duration` must outlive `&self`
30863        // (multiple calls must return equal values from a
30864        // dropped-`&self` copy, since the returned scalar carries no
30865        // borrow), and calling the accessor twice on the same
30866        // CircuitBreaker must yield the same `Duration` verbatim
30867        // (idempotent, no side effects on `&self`).
30868        //
30869        // Pins against a future silent detour that returned
30870        // `&Duration` (which would type-check but silently break every
30871        // downstream `Duration`-by-value consumer —
30872        // [`crate::render::require_positive_canonical_bounded_duration`]'s
30873        // first parameter is `Duration`, and `&Duration` would fold to
30874        // a detached copy at the call site with a `*` deref the sibling
30875        // accessors don't need), an accidental `.window + Duration::ZERO`
30876        // detour that returned a fresh copy through an arithmetic
30877        // no-op (breaking a future `const fn` regression), or a
30878        // one-arm-only accessor that returned a saturating value on
30879        // some sentinel input (breaking the pass-through invariant the
30880        // sibling required-scalar accessors carry).
30881        for window in [
30882            Duration::from_millis(1),
30883            POLICY_BREAKER_WINDOW_MAX,
30884            Duration::ZERO,
30885            Duration::from_secs(86_400),
30886        ] {
30887            let cb = CircuitBreaker {
30888                max_failures: 5,
30889                window,
30890            };
30891            let first = cb.window();
30892            let second = cb.window();
30893            assert_eq!(
30894                first, second,
30895                "CircuitBreaker::window must be idempotent — two \
30896                 successive calls on the same &self must return the \
30897                 same Duration",
30898            );
30899            assert_eq!(
30900                first, window,
30901                "CircuitBreaker::window must return :politicas \
30902                 :circuit-breaker :window verbatim by copy — \
30903                 got {first:?}, expected {window:?}",
30904            );
30905        }
30906    }
30907
30908    #[test]
30909    fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
30910        // Apex-identity pair-invariant pin composing both substrate-
30911        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
30912        // and [`WitContract::destination`] — at the emit-side call shape
30913        // every per-`(:de, :para)` CNP L4 port reader now takes. The
30914        // invariant, evaluated per-edge:
30915        //
30916        //   spec.port_for_destination(c.destination()) == expected_port
30917        //
30918        // where `expected_port` is `entrada.port` when
30919        // `c.destination() == entrada.destination()` and
30920        // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
30921        // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
30922        // pin on the per-`:entrada` axis — that pin encodes the apex
30923        // ingress L4 identity via `entrada.destination()`; this pin
30924        // encodes the per-edge L4 identity via `c.destination()`, and
30925        // both compose on the same substrate-primitive resolver so a
30926        // future refactor that silently split either accessor's apex
30927        // behavior surfaces at caixa-core build time.
30928        let mut spec = three_member_spec();
30929        if let Some(e) = spec.entrada.as_mut() {
30930            e.para = "cart".into();
30931            e.port = 8443;
30932        }
30933        let apex_contract = WitContract {
30934            de: "checkout".into(),
30935            para: "cart".into(),
30936            wit: "wasi:http/proxy".into(),
30937            endpoint: Some("/hello".into()),
30938            subject: None,
30939            slot: None,
30940        };
30941        assert_eq!(
30942            spec.port_for_destination(apex_contract.destination()),
30943            8443,
30944            "`spec.port_for_destination(c.destination())` must equal \
30945             `entrada.port` when the contract callee names the ingress \
30946             apex — the CNP per-edge L4 port and the HTTPRoute apex \
30947             backendRef port share this substrate-primitive resolver.",
30948        );
30949        let non_apex_contract = WitContract {
30950            de: "cart".into(),
30951            para: "payment".into(),
30952            wit: "wasi:http/proxy".into(),
30953            endpoint: Some("/charge".into()),
30954            subject: None,
30955            slot: None,
30956        };
30957        assert_eq!(
30958            spec.port_for_destination(non_apex_contract.destination()),
30959            DEFAULT_SERVICO_PORT,
30960            "`spec.port_for_destination(c.destination())` must fall back \
30961             to the substrate-canonical port floor when the contract \
30962             callee is not the ingress apex — the resolver's non-apex \
30963             arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
30964        );
30965    }
30966
30967    #[test]
30968    fn membro_key_consts_are_lower_camel_case_shape() {
30969        // Shape-pin: every `MEMBRO_KEY_*` const must be a
30970        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
30971        // `kebab-case` hyphens, no leading colon, no `PascalCase`
30972        // leading capital, no whitespace / dots) — the canonical shape
30973        // the `#[serde(rename_all = "camelCase")]` derive produces on
30974        // [`Membro`]. A future flip to a non-camelCase attribute at
30975        // the derive surfaces both here (this test fails on the
30976        // stale-constant shape) and at
30977        // `membro_serde_keys_match_lifted_membro_key_consts` (that test
30978        // fails on the mismatch between const and derive). Peer with
30979        // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
30980        // on the sibling `SupervisorSpec` top-level axis.
30981        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
30982            assert!(
30983                !key.is_empty(),
30984                "MEMBRO_KEY_* must be non-empty (got {key:?})"
30985            );
30986            let first = key.chars().next().unwrap();
30987            assert!(
30988                first.is_ascii_lowercase(),
30989                "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
30990                 (got {key:?}, leads with {first:?})",
30991            );
30992            assert!(
30993                key.chars().all(|c| c.is_ascii_alphanumeric()),
30994                "MEMBRO_KEY_* must be ASCII-alphanumeric only \
30995                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
30996            );
30997        }
30998    }
30999
31000    // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
31001
31002    #[test]
31003    fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
31004        // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
31005        // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
31006        // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
31007        // keys the `#[serde(rename_all = "camelCase")]` attribute on
31008        // [`WitContract`] emits for the required-triad. The three
31009        // sibling payload-arm keys already pin under
31010        // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
31011        // `STORE_FIELD_NAME` — pin all six alongside so a future
31012        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
31013        // verbatim-field-name flip at the derive attribute (any of which
31014        // would silently break every downstream JSON consumer that
31015        // reaches for one of the six via `Value::get(...)`) surfaces
31016        // here as a build-time test failure at `aplicacao.rs`, not as an
31017        // apply-time `.get(<stale-canonical-const>)` returning `None`
31018        // far from the derive-attr drift's commit. Peer with the sibling
31019        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
31020        // pin on the M3 `:membros` per-entry axis — same discipline the
31021        // `Membro` per-entry lift established, extended here to the
31022        // sibling M3 `WitContract` per-`:contratos` entry axis, the last
31023        // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
31024        // axis on the Aplicacao surface without a lifted serde-key peer.
31025        let c = WitContract {
31026            de: "cart".into(),
31027            para: "catalog".into(),
31028            wit: "wasi:http/proxy".into(),
31029            endpoint: Some("/lookup".into()),
31030            subject: None,
31031            slot: None,
31032        };
31033        let json = serde_json::to_string(&c).unwrap();
31034        for key in [
31035            crate::CONTRATO_KEY_DE,
31036            crate::CONTRATO_KEY_PARA,
31037            crate::CONTRATO_KEY_WIT,
31038            WitTarget::HTTP_FIELD_NAME,
31039        ] {
31040            let quoted = format!("\"{key}\"");
31041            assert!(
31042                json.contains(&quoted),
31043                "serialized WitContract must carry the lifted \
31044                 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
31045                 {quoted} verbatim in the JSON emission (got: {json})",
31046            );
31047        }
31048
31049        // Pin the two remaining payload-arm keys by round-tripping a
31050        // `WitContract` under each payload-shape (pub-sub, store) — the
31051        // required-triad appears on every emission but the payload arms
31052        // only surface when their `Option<String>` field is `Some`.
31053        let pubsub = WitContract {
31054            de: "cart".into(),
31055            para: "events".into(),
31056            wit: "nats:pub-sub".into(),
31057            endpoint: None,
31058            subject: Some("orders.placed".into()),
31059            slot: None,
31060        };
31061        let pubsub_json = serde_json::to_string(&pubsub).unwrap();
31062        let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
31063        assert!(
31064            pubsub_json.contains(&pubsub_quoted),
31065            "serialized pub-sub WitContract must carry the lifted \
31066             WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
31067             verbatim in the JSON emission (got: {pubsub_json})",
31068        );
31069        let store = WitContract {
31070            de: "cart".into(),
31071            para: "sessions".into(),
31072            wit: "wasi:keyvalue/store".into(),
31073            endpoint: None,
31074            subject: None,
31075            slot: Some("cart/$id".into()),
31076        };
31077        let store_json = serde_json::to_string(&store).unwrap();
31078        let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
31079        assert!(
31080            store_json.contains(&store_quoted),
31081            "serialized store WitContract must carry the lifted \
31082             WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
31083             verbatim in the JSON emission (got: {store_json})",
31084        );
31085    }
31086
31087    #[test]
31088    fn contrato_key_consts_are_pairwise_distinct() {
31089        // Cross-axis drift-detection pin: a future collapse of the six
31090        // canonical [`WitContract`] per-entry byte-strings onto the same
31091        // value (e.g. an accidental copy-paste flip of
31092        // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
31093        // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
31094        // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
31095        // every downstream probe on one axis onto the sibling axis's
31096        // overlay entry and pass every propagation-probe test that
31097        // expected only the stale axis's value. Peer of the sibling
31098        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
31099        // widened here to the six-way axis the `WitContract`
31100        // required-triad + `WitTarget` payload-triad jointly cover.
31101        let all = [
31102            crate::CONTRATO_KEY_DE,
31103            crate::CONTRATO_KEY_PARA,
31104            crate::CONTRATO_KEY_WIT,
31105            WitTarget::HTTP_FIELD_NAME,
31106            WitTarget::PUBSUB_FIELD_NAME,
31107            WitTarget::STORE_FIELD_NAME,
31108        ];
31109        for (i, a) in all.iter().enumerate() {
31110            for b in all.iter().skip(i + 1) {
31111                assert_ne!(
31112                    a, b,
31113                    "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
31114                     must be pairwise-distinct canonical byte-sequences \
31115                     — got `{a}` == `{b}`",
31116                );
31117            }
31118        }
31119    }
31120
31121    #[test]
31122    fn contrato_key_consts_are_lower_camel_case_shape() {
31123        // Shape-pin: every `CONTRATO_KEY_*` (and every peer
31124        // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
31125        // byte-sequence (no `snake_case` underscores, no `kebab-case`
31126        // hyphens, no leading colon, no `PascalCase` leading capital, no
31127        // whitespace / dots) — the canonical shape the
31128        // `#[serde(rename_all = "camelCase")]` derive produces on
31129        // [`WitContract`]. A future flip to a non-camelCase attribute at
31130        // the derive surfaces both here (this test fails on the
31131        // stale-constant shape) and at
31132        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
31133        // (that test fails on the mismatch between const and derive).
31134        // Peer with `membro_key_consts_are_lower_camel_case_shape`
31135        // (ce80ca0) on the sibling `Membro` per-entry axis.
31136        for key in [
31137            crate::CONTRATO_KEY_DE,
31138            crate::CONTRATO_KEY_PARA,
31139            crate::CONTRATO_KEY_WIT,
31140            WitTarget::HTTP_FIELD_NAME,
31141            WitTarget::PUBSUB_FIELD_NAME,
31142            WitTarget::STORE_FIELD_NAME,
31143        ] {
31144            assert!(
31145                !key.is_empty(),
31146                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
31147                 non-empty (got {key:?})"
31148            );
31149            let first = key.chars().next().unwrap();
31150            assert!(
31151                first.is_ascii_lowercase(),
31152                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
31153                 with an ASCII-lowercase byte (got {key:?}, leads with \
31154                 {first:?})",
31155            );
31156            assert!(
31157                key.chars().all(|c| c.is_ascii_alphanumeric()),
31158                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
31159                 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
31160                 whitespace (got {key:?})",
31161            );
31162        }
31163    }
31164
31165    // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
31166
31167    #[test]
31168    fn entrada_serde_keys_match_lifted_entrada_key_consts() {
31169        // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
31170        // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
31171        // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
31172        // name the exact camelCase JSON keys the
31173        // `#[serde(rename_all = "camelCase")]` attribute on
31174        // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
31175        // pin that each canonical byte-sequence appears verbatim in the
31176        // JSON — a future accidental `rename_all = "snake_case"` /
31177        // `"kebab-case"` / verbatim-field-name flip at the derive
31178        // attribute (any of which would silently break every downstream
31179        // JSON consumer that reaches for one of the four consts via
31180        // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
31181        // emitter's per-Aplicacao hostname/paths/port projection, the
31182        // future `app-operator` reconciler's per-Aplicacao ingress
31183        // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
31184        // materializer's admission-time cross-check) surfaces here as
31185        // a build-time test failure at `aplicacao.rs`, not as an
31186        // apply-time `.get(<stale-canonical-const>)` returning `None`
31187        // far from the derive-attr drift's commit. Peer with the
31188        // sibling
31189        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
31190        // (ca463a4) and
31191        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
31192        // pins on the M3 collection-slot atom axes — same discipline
31193        // both collection-slot lifts established, extended here to the
31194        // singleton `:entrada` mesh-slot atom axis, the last M3
31195        // typed-struct top-level `#[serde(rename_all = "camelCase")]`
31196        // axis on the Aplicacao surface without a lifted serde-key
31197        // peer.
31198        let e = Entrada {
31199            host: "checkout.quero.cloud".into(),
31200            para: "cart".into(),
31201            paths: vec!["/cart".into()],
31202            port: 8080,
31203        };
31204        let json = serde_json::to_string(&e).unwrap();
31205        for key in [
31206            crate::ENTRADA_KEY_HOST,
31207            crate::ENTRADA_KEY_PARA,
31208            crate::ENTRADA_KEY_PATHS,
31209            crate::ENTRADA_KEY_PORT,
31210        ] {
31211            let quoted = format!("\"{key}\"");
31212            assert!(
31213                json.contains(&quoted),
31214                "serialized Entrada must carry the lifted ENTRADA_KEY_* \
31215                 byte-sequence {quoted} verbatim in the JSON emission \
31216                 (got: {json})",
31217            );
31218        }
31219    }
31220
31221    #[test]
31222    fn entrada_key_consts_are_pairwise_distinct() {
31223        // Cross-axis drift-detection pin: a future collapse of the four
31224        // canonical [`Entrada`] singleton byte-strings onto the same
31225        // value (e.g. an accidental copy-paste flip of
31226        // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
31227        // silently reroute every downstream probe on one axis onto the
31228        // sibling axis's overlay entry and pass every propagation-probe
31229        // test that expected only the stale axis's value — the
31230        // Gateway/HTTPRoute emitter would read the hostname string
31231        // where the destination-Servico name was expected (or vice
31232        // versa), the admission-webhook cross-check would compare the
31233        // wrong pair of values, and the resulting Gateway resource
31234        // would either be admitted with garbage or rejected at the
31235        // controller far from the rebrand commit's source. Peer of the
31236        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
31237        // tetrad (40cc4e5), the two-way distinct pin on the
31238        // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
31239        // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
31240        // triad (ca463a4).
31241        let all = [
31242            crate::ENTRADA_KEY_HOST,
31243            crate::ENTRADA_KEY_PARA,
31244            crate::ENTRADA_KEY_PATHS,
31245            crate::ENTRADA_KEY_PORT,
31246        ];
31247        for (i, a) in all.iter().enumerate() {
31248            for b in all.iter().skip(i + 1) {
31249                assert_ne!(
31250                    a, b,
31251                    "ENTRADA_KEY_* consts must be pairwise-distinct \
31252                     canonical byte-sequences — got `{a}` == `{b}`",
31253                );
31254            }
31255        }
31256    }
31257
31258    #[test]
31259    fn entrada_key_consts_are_lower_camel_case_shape() {
31260        // Shape-pin: every `ENTRADA_KEY_*` const must be a
31261        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
31262        // `kebab-case` hyphens, no leading colon, no `PascalCase`
31263        // leading capital, no whitespace / dots) — the canonical shape
31264        // the `#[serde(rename_all = "camelCase")]` derive produces on
31265        // [`Entrada`]. A future flip to a non-camelCase attribute at
31266        // the derive surfaces both here (this test fails on the
31267        // stale-constant shape) and at
31268        // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
31269        // test fails on the mismatch between const and derive). Peer
31270        // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
31271        // and `contrato_key_consts_are_lower_camel_case_shape`
31272        // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
31273        // entry axes.
31274        for key in [
31275            crate::ENTRADA_KEY_HOST,
31276            crate::ENTRADA_KEY_PARA,
31277            crate::ENTRADA_KEY_PATHS,
31278            crate::ENTRADA_KEY_PORT,
31279        ] {
31280            assert!(
31281                !key.is_empty(),
31282                "ENTRADA_KEY_* must be non-empty (got {key:?})"
31283            );
31284            let first = key.chars().next().unwrap();
31285            assert!(
31286                first.is_ascii_lowercase(),
31287                "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
31288                 (got {key:?}, leads with {first:?})",
31289            );
31290            assert!(
31291                key.chars().all(|c| c.is_ascii_alphanumeric()),
31292                "ENTRADA_KEY_* must be ASCII-alphanumeric only \
31293                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
31294            );
31295        }
31296    }
31297
31298    // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
31299
31300    #[test]
31301    fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
31302        // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
31303        // ([`crate::POLITICAS_KEY_TIMEOUT`] /
31304        // [`crate::POLITICAS_KEY_RETRIES`] /
31305        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
31306        // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
31307        // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
31308        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
31309        // on [`MeshPolicy`] emits. Three of the five axes
31310        // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
31311        // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
31312        // camelCase transforms — the derive-attribute is load-bearing
31313        // on those, unlike the sibling `Entrada` / `Membro` /
31314        // `WitContract` structs whose fields are all lowercase-single-
31315        // word and where the derive is a no-op on every axis.
31316        // Serialize a fully-populated [`MeshPolicy`] (every axis
31317        // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
31318        // on none of the five slots) and pin that each canonical
31319        // byte-sequence appears verbatim in the JSON — a future
31320        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
31321        // verbatim-field-name flip at the derive attribute (any of
31322        // which would silently break every downstream JSON consumer
31323        // that reaches for one of the five consts via
31324        // `Value::get(...)` — the future M4 per-edge `:politicas`
31325        // overlay projection onto Cilium `L7Rules` and Gateway API
31326        // `HTTPRoute` backend timeouts, the future
31327        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
31328        // admission-time mesh-policy cross-check, the future
31329        // `feira lint` per-`:politicas` bound-check gate) surfaces here
31330        // as a build-time test failure at `aplicacao.rs`, not as an
31331        // apply-time `.get(<stale-canonical-const>)` returning `None`
31332        // far from the derive-attr drift's commit. Peer with the
31333        // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
31334        // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
31335        // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
31336        // (ce80ca0) pins on the M3 collection-slot / singleton-slot
31337        // atom axes — same discipline every M3 sibling lift
31338        // established, extended here to the singleton `:politicas`
31339        // mesh-slot atom axis, closing the last M3 typed-struct
31340        // top-level `#[serde(rename_all = "camelCase")]` axis on the
31341        // Aplicacao surface without a lifted serde-key peer.
31342        let p = MeshPolicy {
31343            timeout: Some(Duration::from_secs(30)),
31344            retries: Some(3),
31345            circuit_breaker: Some(CircuitBreaker {
31346                max_failures: 5,
31347                window: Duration::from_secs(60),
31348            }),
31349            mtls_required: Some(true),
31350            rate_limit: Some(RateLimit {
31351                rate: 100,
31352                window: Duration::from_secs(1),
31353            }),
31354        };
31355        let json = serde_json::to_string(&p).unwrap();
31356        for key in [
31357            crate::POLITICAS_KEY_TIMEOUT,
31358            crate::POLITICAS_KEY_RETRIES,
31359            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
31360            crate::POLITICAS_KEY_MTLS_REQUIRED,
31361            crate::POLITICAS_KEY_RATE_LIMIT,
31362        ] {
31363            let quoted = format!("\"{key}\"");
31364            assert!(
31365                json.contains(&quoted),
31366                "serialized MeshPolicy must carry the lifted \
31367                 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
31368                 JSON emission (got: {json})",
31369            );
31370        }
31371    }
31372
31373    #[test]
31374    fn politicas_key_consts_are_pairwise_distinct() {
31375        // Cross-axis drift-detection pin: a future collapse of the five
31376        // canonical [`MeshPolicy`] singleton byte-strings onto the same
31377        // value (e.g. an accidental copy-paste flip of
31378        // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
31379        // would silently reroute every downstream probe on one axis
31380        // onto the sibling axis's overlay entry and pass every
31381        // propagation-probe test that expected only the stale axis's
31382        // value — the M4 per-edge `:politicas` overlay projection would
31383        // read the retry-count string where the timeout duration was
31384        // expected (or vice versa), the CR materializer's admission
31385        // cross-check would compare the wrong pair of values, and the
31386        // resulting mesh reconciler would either bind the wrong axis
31387        // or reject the resource at reconcile far from the rebrand
31388        // commit's source. Peer of the sibling four-way distinct pin
31389        // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
31390        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
31391        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
31392        // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
31393        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
31394        let all = [
31395            crate::POLITICAS_KEY_TIMEOUT,
31396            crate::POLITICAS_KEY_RETRIES,
31397            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
31398            crate::POLITICAS_KEY_MTLS_REQUIRED,
31399            crate::POLITICAS_KEY_RATE_LIMIT,
31400        ];
31401        for (i, a) in all.iter().enumerate() {
31402            for b in all.iter().skip(i + 1) {
31403                assert_ne!(
31404                    a, b,
31405                    "POLITICAS_KEY_* consts must be pairwise-distinct \
31406                     canonical byte-sequences — got `{a}` == `{b}`",
31407                );
31408            }
31409        }
31410    }
31411
31412    #[test]
31413    fn politicas_key_consts_are_lower_camel_case_shape() {
31414        // Shape-pin: every `POLITICAS_KEY_*` const must be a
31415        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
31416        // `kebab-case` hyphens, no leading colon, no `PascalCase`
31417        // leading capital, no whitespace / dots) — the canonical shape
31418        // the `#[serde(rename_all = "camelCase")]` derive produces on
31419        // [`MeshPolicy`]. A future flip to a non-camelCase attribute
31420        // at the derive surfaces both here (this test fails on the
31421        // stale-constant shape) and at
31422        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
31423        // (that test fails on the mismatch between const and derive).
31424        // Peer with `entrada_key_consts_are_lower_camel_case_shape`
31425        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
31426        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
31427        // (ca463a4) on the sibling M3 typed-struct axes.
31428        for key in [
31429            crate::POLITICAS_KEY_TIMEOUT,
31430            crate::POLITICAS_KEY_RETRIES,
31431            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
31432            crate::POLITICAS_KEY_MTLS_REQUIRED,
31433            crate::POLITICAS_KEY_RATE_LIMIT,
31434        ] {
31435            assert!(
31436                !key.is_empty(),
31437                "POLITICAS_KEY_* must be non-empty (got {key:?})"
31438            );
31439            let first = key.chars().next().unwrap();
31440            assert!(
31441                first.is_ascii_lowercase(),
31442                "POLITICAS_KEY_* must lead with an ASCII-lowercase \
31443                 byte (got {key:?}, leads with {first:?})",
31444            );
31445            assert!(
31446                key.chars().all(|c| c.is_ascii_alphanumeric()),
31447                "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
31448                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
31449            );
31450        }
31451    }
31452
31453    // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
31454
31455    #[test]
31456    fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
31457        // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
31458        // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
31459        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
31460        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
31461        // [`CircuitBreaker`] emits inside the
31462        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
31463        // two axes (`max_failures` → `maxFailures`) is a non-trivial
31464        // camelCase transform — the derive-attribute is load-bearing on
31465        // that axis, unlike the sibling `window` field where the derive
31466        // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
31467        // pin that each canonical byte-sequence appears verbatim in the
31468        // JSON — a future accidental `rename_all = "snake_case"` /
31469        // `"kebab-case"` / verbatim-field-name flip at the derive
31470        // attribute (any of which would silently break every downstream
31471        // JSON consumer that reaches for one of the two consts via
31472        // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
31473        // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
31474        // per-edge `:politicas` overlay projection onto the mesh's
31475        // per-backend consecutive-failure-counter tripping threshold, the
31476        // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
31477        // admission-time breaker cross-check, the future `feira lint`
31478        // per-`:politicas :circuit-breaker` bound-check gate) surfaces
31479        // here as a build-time test failure at `aplicacao.rs`, not as an
31480        // apply-time `.get(<stale-canonical-const>)` returning `None`
31481        // far from the derive-attr drift's commit. Peer with the sibling
31482        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
31483        // (b55cca7) parent-axis pin — that test pins the outer
31484        // sub-block key the derive on [`MeshPolicy`] emits, this test
31485        // pins the inner keys the derive on the payload type emits, so
31486        // the two together lock the whole [`MeshPolicy`] breaker-tuning
31487        // shape end-to-end at build time.
31488        let cb = CircuitBreaker {
31489            max_failures: 5,
31490            window: Duration::from_secs(60),
31491        };
31492        let json = serde_json::to_string(&cb).unwrap();
31493        for key in [
31494            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
31495            crate::CIRCUIT_BREAKER_KEY_WINDOW,
31496        ] {
31497            let quoted = format!("\"{key}\"");
31498            assert!(
31499                json.contains(&quoted),
31500                "serialized CircuitBreaker must carry the lifted \
31501                 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
31502                 in the JSON emission (got: {json})",
31503            );
31504        }
31505    }
31506
31507    #[test]
31508    fn circuit_breaker_key_consts_are_pairwise_distinct() {
31509        // Cross-axis drift-detection pin: a future collapse of the two
31510        // canonical [`CircuitBreaker`] sub-block byte-strings onto the
31511        // same value (e.g. an accidental copy-paste flip of
31512        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
31513        // `"maxFailures"`) would silently reroute every downstream
31514        // probe on one axis onto the sibling axis's overlay entry and
31515        // pass every propagation-probe test that expected only the
31516        // stale axis's value — the M4 per-edge `:politicas` overlay
31517        // projection would read the failure-count where the window
31518        // duration was expected (or vice versa), the CR materializer's
31519        // admission cross-check would compare the wrong pair of values,
31520        // and the resulting mesh reconciler would either bind the wrong
31521        // axis or reject the resource at reconcile far from the rebrand
31522        // commit's source. Peer of the sibling five-way distinct pin on
31523        // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
31524        // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
31525        // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
31526        // six-way distinct pin on the `CONTRATO_KEY_*` triad +
31527        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
31528        let all = [
31529            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
31530            crate::CIRCUIT_BREAKER_KEY_WINDOW,
31531        ];
31532        for (i, a) in all.iter().enumerate() {
31533            for b in all.iter().skip(i + 1) {
31534                assert_ne!(
31535                    a, b,
31536                    "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
31537                     canonical byte-sequences — got `{a}` == `{b}`",
31538                );
31539            }
31540        }
31541    }
31542
31543    #[test]
31544    fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
31545        // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
31546        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
31547        // `kebab-case` hyphens, no leading colon, no `PascalCase`
31548        // leading capital, no whitespace / dots) — the canonical shape
31549        // the `#[serde(rename_all = "camelCase")]` derive produces on
31550        // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
31551        // at the derive surfaces both here (this test fails on the
31552        // stale-constant shape) and at
31553        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
31554        // (that test fails on the mismatch between const and derive).
31555        // Peer with `politicas_key_consts_are_lower_camel_case_shape`
31556        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
31557        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
31558        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
31559        // (ca463a4) on the sibling M3 typed-struct axes.
31560        for key in [
31561            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
31562            crate::CIRCUIT_BREAKER_KEY_WINDOW,
31563        ] {
31564            assert!(
31565                !key.is_empty(),
31566                "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
31567            );
31568            let first = key.chars().next().unwrap();
31569            assert!(
31570                first.is_ascii_lowercase(),
31571                "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
31572                 byte (got {key:?}, leads with {first:?})",
31573            );
31574            assert!(
31575                key.chars().all(|c| c.is_ascii_alphanumeric()),
31576                "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
31577                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
31578            );
31579        }
31580    }
31581
31582    // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
31583
31584    #[test]
31585    fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
31586        // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
31587        // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
31588        // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
31589        // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
31590        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
31591        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
31592        // [`Placement`] emits. One of the four axes (`shard_key` →
31593        // `shardKey`) is a non-trivial camelCase transform — the
31594        // derive-attribute is load-bearing on that axis, unlike the
31595        // sibling `estrategia` / `clusters` / `affinity` axes whose
31596        // source-side field names carry no `_` and where the derive is a
31597        // no-op. Serialize a fully-populated [`Placement`] (both
31598        // `Option`-carrying axes `Some(_)` so
31599        // `skip_serializing_if = "Option::is_none"` fires on neither of
31600        // the two optional slots) and pin that each canonical
31601        // byte-sequence appears verbatim in the JSON — a future
31602        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
31603        // verbatim-field-name flip at the derive attribute (any of which
31604        // would silently break every downstream consumer that reaches
31605        // for one of the four consts via
31606        // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
31607        // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
31608        // aggregator's per-cluster fanout filter keying off
31609        // `placement.clusters`, the M3 shard-pool dispatch materializer
31610        // keying off `placement.shardKey`, the M3 Adaptive compression
31611        // pass weighting off `placement.affinity`, every downstream
31612        // dispatcher branching on `placement.estrategia`, the future
31613        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
31614        // admission-time placement cross-check, the future `feira lint`
31615        // per-`:placement` bound-check gate) surfaces here as a
31616        // build-time test failure at `aplicacao.rs`, not as an
31617        // apply-time `.get(<stale-canonical-const>)` returning `None`
31618        // far from the derive-attr drift's commit. Peer with the sibling
31619        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
31620        // (b55cca7),
31621        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
31622        // (468e959),
31623        // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
31624        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
31625        // (ca463a4), and
31626        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
31627        // pins on the M3 collection-slot / singleton-slot atom axes —
31628        // closes the last M3 typed-struct top-level
31629        // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
31630        // surface without a drift-detection pin.
31631        let p = Placement {
31632            estrategia: PlacementStrategy::Sharded,
31633            clusters: vec!["rio".into(), "mar".into()],
31634            affinity: Some("data-locality".into()),
31635            shard_key: Some("$tenantId".into()),
31636        };
31637        let json = serde_json::to_string(&p).unwrap();
31638        for key in [
31639            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
31640            crate::M3_PLACEMENT_KEY_CLUSTERS,
31641            crate::M3_PLACEMENT_KEY_AFFINITY,
31642            crate::M3_PLACEMENT_KEY_SHARD_KEY,
31643        ] {
31644            let quoted = format!("\"{key}\"");
31645            assert!(
31646                json.contains(&quoted),
31647                "serialized Placement must carry the lifted \
31648                 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
31649                 the JSON emission (got: {json})",
31650            );
31651        }
31652    }
31653
31654    #[test]
31655    fn m3_placement_key_consts_are_pairwise_distinct() {
31656        // Cross-axis drift-detection pin: a future collapse of the four
31657        // canonical [`Placement`] sub-block byte-strings onto the same
31658        // value (e.g. an accidental copy-paste flip of
31659        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
31660        // `"affinity"`) would silently reroute every downstream probe on
31661        // one axis onto the sibling axis's overlay entry and pass every
31662        // propagation-probe test that expected only the stale axis's
31663        // value — the M3 shard-pool dispatch materializer would read the
31664        // affinity placement-hint where the shard-selection template was
31665        // expected (or vice versa), the M3 Adaptive compression pass's
31666        // cross-check would compare the wrong pair of values, and the
31667        // resulting placement engine would either bind the wrong axis or
31668        // reject the resource at reconcile far from the rebrand commit's
31669        // source. Peer of the sibling two-way distinct pin on the
31670        // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
31671        // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
31672        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
31673        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
31674        // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
31675        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
31676        let all = [
31677            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
31678            crate::M3_PLACEMENT_KEY_CLUSTERS,
31679            crate::M3_PLACEMENT_KEY_AFFINITY,
31680            crate::M3_PLACEMENT_KEY_SHARD_KEY,
31681        ];
31682        for (i, a) in all.iter().enumerate() {
31683            for b in all.iter().skip(i + 1) {
31684                assert_ne!(
31685                    a, b,
31686                    "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
31687                     canonical byte-sequences — got `{a}` == `{b}`",
31688                );
31689            }
31690        }
31691    }
31692
31693    #[test]
31694    fn m3_placement_key_consts_are_lower_camel_case_shape() {
31695        // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
31696        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
31697        // `kebab-case` hyphens, no leading colon, no `PascalCase`
31698        // leading capital, no whitespace / dots) — the canonical shape
31699        // the `#[serde(rename_all = "camelCase")]` derive produces on
31700        // [`Placement`]. A future flip to a non-camelCase attribute at
31701        // the derive surfaces both here (this test fails on the stale-
31702        // constant shape) and at
31703        // `placement_serde_keys_match_lifted_m3_placement_key_consts`
31704        // (that test fails on the mismatch between const and derive).
31705        // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
31706        // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
31707        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
31708        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
31709        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
31710        // (ca463a4) on the sibling M3 typed-struct axes.
31711        for key in [
31712            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
31713            crate::M3_PLACEMENT_KEY_CLUSTERS,
31714            crate::M3_PLACEMENT_KEY_AFFINITY,
31715            crate::M3_PLACEMENT_KEY_SHARD_KEY,
31716        ] {
31717            assert!(
31718                !key.is_empty(),
31719                "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
31720            );
31721            let first = key.chars().next().unwrap();
31722            assert!(
31723                first.is_ascii_lowercase(),
31724                "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
31725                 byte (got {key:?}, leads with {first:?})",
31726            );
31727            assert!(
31728                key.chars().all(|c| c.is_ascii_alphanumeric()),
31729                "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
31730                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
31731            );
31732        }
31733    }
31734
31735    // ── AplicacaoSpec::port_for_destination — the substrate-canonical
31736    //    destination-facing L4 port resolver every per-Aplicacao renderer
31737    //    reaching for a per-destination Servico TCP port axis routes
31738    //    through. The four pin tests below fix the four-way accept-set
31739    //    the resolver must always honor: (:entrada-para-matches,
31740    //    :entrada-para-mismatches, :entrada-none-so-fallback,
31741    //    :entrada-port-non-default-honored) — drift on any arm surfaces
31742    //    at caixa-core build time rather than at cluster-apply time.
31743
31744    #[test]
31745    fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
31746        // The typed `:entrada` block's `:para "cart"` matches the
31747        // queried destination, so the resolver returns the author-
31748        // declared `:port` scalar verbatim — the canonical "the
31749        // destination Servico IS the ingress apex, honor the typed
31750        // listener port" arm of the port-resolution dispatch.
31751        let mut spec = three_member_spec();
31752        if let Some(e) = spec.entrada.as_mut() {
31753            e.para = "cart".into();
31754            e.port = 9090;
31755        }
31756        assert_eq!(
31757            spec.port_for_destination("cart"),
31758            9090,
31759            "port_for_destination(entrada.para) must return entrada.port \
31760             verbatim, not the DEFAULT_SERVICO_PORT fallback"
31761        );
31762    }
31763
31764    #[test]
31765    fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
31766        // The typed `:entrada` block names `:para "cart"`, but the
31767        // queried destination is `"payment"` — a Servico that
31768        // participates in the mesh graph but is not the ingress apex.
31769        // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
31770        // canonical port floor, closing the "non-apex destination reads
31771        // the substrate default" arm. Same fixture the peer
31772        // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
31773        // pin at caixa-mesh exercises through the CNP emit-side path;
31774        // this pin exercises the shared underlying resolver directly.
31775        let spec = three_member_spec();
31776        assert_eq!(
31777            spec.port_for_destination("payment"),
31778            DEFAULT_SERVICO_PORT,
31779            "port_for_destination(non-apex-destination) must route \
31780             through the lifted DEFAULT_SERVICO_PORT canonical port floor"
31781        );
31782    }
31783
31784    #[test]
31785    fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
31786        // Internal-only Aplicacao — no `:entrada` block declared. Every
31787        // per-destination port query falls back to the lifted
31788        // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
31789        // the Aplicacao surface admits `:entrada None` (internal mesh
31790        // with no external gateway); every downstream renderer's per-
31791        // destination port axis must still resolve to a well-defined
31792        // scalar even without an ingress apex.
31793        let mut spec = three_member_spec();
31794        spec.entrada = None;
31795        assert_eq!(
31796            spec.port_for_destination("cart"),
31797            DEFAULT_SERVICO_PORT,
31798            "port_for_destination on an internal-only Aplicacao must \
31799             fall back to the lifted DEFAULT_SERVICO_PORT floor for \
31800             every destination"
31801        );
31802        assert_eq!(
31803            spec.port_for_destination("payment"),
31804            DEFAULT_SERVICO_PORT,
31805            "port_for_destination on an internal-only Aplicacao must \
31806             fall back uniformly across every destination — the fallback \
31807             is not entrada-shape-conditional"
31808        );
31809    }
31810
31811    #[test]
31812    fn port_for_destination_honors_non_default_entrada_port_verbatim() {
31813        // Structural pin against a hypothetical future refactor that
31814        // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
31815        // the resolver (a "normalize to the default when the author's
31816        // port matches the substrate default" collapse) — that would
31817        // break renderer sites that carry meaning on the emitted port
31818        // value beyond bare equality (a future per-cluster listener-
31819        // audit that keys off the author-declared port, not the
31820        // resolved-with-fallback port). Pin that a non-default
31821        // entrada.port is returned verbatim so drift here surfaces at
31822        // caixa-core build time.
31823        let mut spec = three_member_spec();
31824        if let Some(e) = spec.entrada.as_mut() {
31825            e.para = "cart".into();
31826            e.port = 8443;
31827        }
31828        assert_ne!(
31829            8443, DEFAULT_SERVICO_PORT,
31830            "test fixture must probe a port distinct from \
31831             DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
31832        );
31833        assert_eq!(
31834            spec.port_for_destination("cart"),
31835            8443,
31836            "port_for_destination(entrada.para) must return entrada.port \
31837             verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
31838        );
31839    }
31840
31841    #[test]
31842    fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
31843        // Apex-identity pair-invariant pin composing both substrate-
31844        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
31845        // and [`Entrada::destination`] — at the emit-side call shape
31846        // every per-Aplicacao renderer's ingress-apex L4 port reader
31847        // now takes. The invariant:
31848        //
31849        //   spec.port_for_destination(entrada.destination()) == entrada.port
31850        //
31851        // holds by construction under today's single-destination
31852        // `:entrada` slot (`destination()` returns `entrada.para`, and
31853        // the resolver's apex arm matches `para == destination` and
31854        // returns `entrada.port`), and every downstream consumer that
31855        // composes the two accessors at the ingress apex — the
31856        // `caixa_mesh::gateway_routes` HTTPRoute per-rule
31857        // `backendRefs[0].port` emit-site path, the peer future M4 CR
31858        // materializer's admission-webhook that promotes the scalar to
31859        // a per-CR override overlay, every future per-Aplicacao snapshot
31860        // renderer's apex-facing L4 port reader — reaches through the
31861        // same composition. Pin the identity across four permutations
31862        // (`:para` × `:port` including a non-default port to exercise
31863        // the honor-verbatim arm and a non-cart `:para` to exercise
31864        // destination-agnostic identity) so a future refactor that
31865        // silently split either accessor's apex behavior surfaces at
31866        // caixa-core build time — a subtle `destination()` renaming
31867        // that returned `entrada.host.as_str()` instead of
31868        // `entrada.para.as_str()` would blow this pin loudly, closing
31869        // the last quiet failure mode the two lifts admit in composition.
31870        //
31871        // Peer discipline with the sibling caixa-mesh cross-crate pin
31872        // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
31873        // on the two-renderer pair-invariant axis; this pin encodes the
31874        // same two-consumer coherence rule at the substrate-primitive
31875        // level so the invariant survives even if every renderer is
31876        // deleted.
31877        for (para, port) in [
31878            ("cart", DEFAULT_SERVICO_PORT),
31879            ("cart", 8443u16),
31880            ("payment", 9090u16),
31881            ("catalog", 443u16),
31882        ] {
31883            let mut spec = three_member_spec();
31884            if let Some(e) = spec.entrada.as_mut() {
31885                e.para = para.into();
31886                e.port = port;
31887            }
31888            let expected_port = spec
31889                .entrada()
31890                .expect("three_member_spec carries a typed `:entrada` block")
31891                .port();
31892            let composed_port = {
31893                let entrada = spec.entrada().expect("entrada present");
31894                spec.port_for_destination(entrada.destination())
31895            };
31896            assert_eq!(
31897                composed_port, expected_port,
31898                "`spec.port_for_destination(entrada.destination())` must \
31899                 equal `entrada.port` under today's single-destination \
31900                 `:entrada` slot — this is the apex-identity contract \
31901                 every downstream ingress-apex L4 port reader relies on. \
31902                 Input :entrada :para: {para:?}, :entrada :port: {port}"
31903            );
31904        }
31905    }
31906
31907    #[test]
31908    fn port_for_destination_apex_arm_routes_through_destination_accessor() {
31909        // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
31910        // per-`:entrada` apex-arm membership probe must key off
31911        // [`Entrada::destination`], not the raw `.para` field access.
31912        // Structurally: setting ONLY the `:entrada :para` field to a
31913        // fresh non-cart destination on an otherwise-well-formed
31914        // Aplicacao must (1) leave `e.destination()` byte-equal to
31915        // `e.para.as_str()` (the accessor is byte-projective by
31916        // definition), and (2) cause the resolver's apex arm to fire
31917        // and return `entrada.port` at exactly that new destination
31918        // while every other destination string falls through to
31919        // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
31920        // membership check. Pins against a future silent detour that
31921        // (a) re-derived the apex-arm membership probe off
31922        // `e.para == destination` in `port_for_destination` instead of
31923        // `e.destination() == destination`, silently disagreeing with
31924        // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
31925        // consumers (`entrada.destination()` at
31926        // caixa-mesh/src/lib.rs:3173, `c.destination()` at
31927        // caixa-mesh/src/lib.rs:2739) that already reach through the
31928        // accessor, (b) accessor-side introduced a per-tenant alias
31929        // arm the caller was unaware of, silently rewriting an
31930        // author-declared `:para "cart"` value to a canary-aliased
31931        // form — the raw-field-access resolver would fall through to
31932        // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
31933        // while the peer emit-site consumers landed on the aliased
31934        // destination, splitting the ingress-apex L4 port at
31935        // cluster-apply time.
31936        //
31937        // Peer of the sibling
31938        // [`validate_membros_empty_gate_routes_through_nome_accessor`]
31939        // (d0de220) composition pin on the per-`:membros` refusal-arm
31940        // axis — same "the shape-gate predicate must route through the
31941        // substrate-primitive typed dispatch" discipline extended onto
31942        // the per-`:entrada` apex-arm membership-probe axis. Closes
31943        // the last unlifted `.para` production-code read site on
31944        // `Entrada` in `caixa-core` — after this converge every
31945        // `caixa-core` `.para` field access outside the accessor's own
31946        // body and outside the `WitContract` per-`:contratos` sibling
31947        // axis is either a test-side field-setter or a doc-comment
31948        // reference.
31949        for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
31950            let mut spec = three_member_spec();
31951            if let Some(e) = spec.entrada.as_mut() {
31952                e.para = para.into();
31953                e.port = port;
31954            }
31955            let e = spec
31956                .entrada
31957                .as_ref()
31958                .expect("three_member_spec carries a typed `:entrada` block");
31959            assert_eq!(
31960                e.destination(),
31961                e.para.as_str(),
31962                "Entrada::destination must byte-equal the .para field \
31963                 access — an accessor-side detour that no longer \
31964                 projects the raw field would silently split this \
31965                 drift-detection test from the port_for_destination \
31966                 apex-arm membership probe",
31967            );
31968            assert_eq!(
31969                spec.port_for_destination(para),
31970                port,
31971                "port_for_destination must key off the accessor-projected \
31972                 destination and return `entrada.port` on the apex arm — \
31973                 input :entrada :para: {para:?}, :entrada :port: {port}",
31974            );
31975            assert_eq!(
31976                spec.port_for_destination("ghost-destination-never-a-member"),
31977                DEFAULT_SERVICO_PORT,
31978                "port_for_destination must fall through to \
31979                 DEFAULT_SERVICO_PORT on a non-matching destination \
31980                 under the accessor-projected membership check — input \
31981                 :entrada :para: {para:?}, :entrada :port: {port}",
31982            );
31983        }
31984    }
31985
31986    #[test]
31987    fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
31988        // The canonical per-`:politicas :rate-limit` `:rate`
31989        // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
31990        // [`RateLimit::rate`] must return the `:politicas :rate-limit`
31991        // typed `u32` verbatim, byte-equal to the raw field access
31992        // across every representative value in the accept-set — `1` (the
31993        // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
31994        // the surrounding [`AplicacaoSpec::validate_politicas`] gate
31995        // carves out on the sibling `PolicyRateLimitZero` refusal),
31996        // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
31997        // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
31998        // `0` (a past-the-guard sentinel that pins the accessor doesn't
31999        // perform a silent bounds-collapse into `1` on the zero arm —
32000        // validate rejects zero but the accessor must ship the raw slot
32001        // verbatim so a validate-time gate regression surfaces at the
32002        // emit boundary rather than being silently absorbed), `u32::MAX`
32003        // (a past-the-guard sentinel that pins the accessor doesn't
32004        // perform a silent bounds-collapse through
32005        // `POLICY_RATE_LIMIT_MAX` at the return path).
32006        //
32007        // First sub-struct required-scalar accessor pin on the
32008        // `RateLimit` axis — sibling in shape to the peer
32009        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
32010        // required-`u32` accessor pin on the peer per-sub-struct
32011        // required-axis. Pins against a future silent detour that
32012        // re-derived the token capacity from a peer axis (an accidental
32013        // `self.window.as_secs() as u32` collapse that read the
32014        // rate-limit window duration as a token count), a `0 → 1`
32015        // cluster-default projection (which would silently absorb the
32016        // `PolicyRateLimitZero` refusal case at the accessor boundary),
32017        // or a bounds-collapsing accessor that clamped the return
32018        // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
32019        // gate owns the bounds; the accessor must ship the raw slot
32020        // verbatim).
32021        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
32022            let rl = RateLimit {
32023                rate,
32024                window: Duration::from_secs(1),
32025            };
32026            assert_eq!(
32027                rl.rate(),
32028                rate,
32029                "RateLimit::rate must return :politicas :rate-limit :rate \
32030                 verbatim (got {}, expected {rate})",
32031                rl.rate(),
32032            );
32033            assert_eq!(
32034                rl.rate(),
32035                rl.rate,
32036                "RateLimit::rate must byte-equal the raw .rate field \
32037                 access across every value in the u32 accept-set",
32038            );
32039        }
32040    }
32041
32042    #[test]
32043    fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
32044        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
32045        // `:rate-limit :rate` zero-floor arm must key off
32046        // [`RateLimit::rate`], not the raw `.rate` field access.
32047        // Structurally: a `RateLimit { rate: 0, window:
32048        // Duration::from_secs(1) }` embedded in a `:politicas
32049        // :rate-limit` slot must surface the `PolicyRateLimitZero`
32050        // refusal exactly, and a `RateLimit { rate: 1, window:
32051        // Duration::from_secs(1) }` (the lower boundary of the
32052        // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
32053        // The pair jointly pins the accessor + validate-gate composition:
32054        // any future silent detour that had the accessor return a fresh
32055        // `1` on the zero arm (a `.rate().max(1)` collapse) would
32056        // silently absorb the `PolicyRateLimitZero` refusal at the
32057        // accessor boundary and the validate gate would accept a
32058        // struct-literal `RateLimit { rate: 0, .. }` — the composition
32059        // pin catches that at caixa-core build time.
32060        //
32061        // Peer of the sibling per-`CircuitBreaker`
32062        // [`CircuitBreaker::max_failures`] (3a74062) /
32063        // [`CircuitBreaker::window`] (373957f) accessor-composition
32064        // pins on the peer required-scalar axes — same "the validate /
32065        // shape-gate predicate must route through the substrate-primitive
32066        // typed dispatch" discipline extended onto the peer
32067        // per-`RateLimit` required-`u32` composition axis.
32068        let mut spec = three_member_spec();
32069        spec.politicas = MeshPolicy {
32070            rate_limit: Some(RateLimit {
32071                rate: 0,
32072                window: Duration::from_secs(1),
32073            }),
32074            ..MeshPolicy::default()
32075        };
32076        assert!(
32077            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
32078            "validate_politicas must reject rate == 0 with \
32079             PolicyRateLimitZero — the accessor and the validate gate \
32080             must route through the same substrate-primitive typed \
32081             dispatch on the :rate zero-floor arm",
32082        );
32083        spec.politicas = MeshPolicy {
32084            rate_limit: Some(RateLimit {
32085                rate: 1,
32086                window: Duration::from_secs(1),
32087            }),
32088            ..MeshPolicy::default()
32089        };
32090        assert!(
32091            spec.validate().is_ok(),
32092            "validate_politicas must accept rate == 1 (the lower \
32093             boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
32094        );
32095    }
32096
32097    #[test]
32098    fn rate_limit_rate_projects_u32_by_copy() {
32099        // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
32100        // `u32` is `Copy` and the accessor must return by value, not by
32101        // reference. Peer of the sibling per-`CircuitBreaker`
32102        // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
32103        // peer required-scalar `:max-failures` axis, extended onto the
32104        // peer per-`RateLimit` required-`u32` copy-invariant shape —
32105        // the accessor's returned `u32` must outlive `&self` (multiple
32106        // calls must return equal values from a dropped-`&self` copy,
32107        // since the returned scalar carries no borrow), and calling the
32108        // accessor twice on the same RateLimit must yield the same
32109        // `u32` verbatim (idempotent, no side effects on `&self`).
32110        //
32111        // Pins against a future silent detour that returned `&u32`
32112        // (which would type-check but silently break every downstream
32113        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
32114        // first parameter is `u32`, and `&u32` would fold to a detached
32115        // copy at the call site with a `*` deref the sibling accessors
32116        // don't need), an accidental `.rate.wrapping_add(0)` detour that
32117        // returned a fresh copy through an arithmetic no-op (breaking a
32118        // future `const fn` regression), or a one-arm-only accessor
32119        // that returned a saturating value on some sentinel input
32120        // (breaking the pass-through invariant the sibling required-
32121        // scalar accessors carry).
32122        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
32123            let rl = RateLimit {
32124                rate,
32125                window: Duration::from_secs(1),
32126            };
32127            let first = rl.rate();
32128            let second = rl.rate();
32129            assert_eq!(
32130                first, second,
32131                "RateLimit::rate must be idempotent — two successive \
32132                 calls on the same &self must return the same u32",
32133            );
32134            assert_eq!(
32135                first, rate,
32136                "RateLimit::rate must return :politicas :rate-limit :rate \
32137                 verbatim by copy — got {first}, expected {rate}",
32138            );
32139        }
32140    }
32141
32142    #[test]
32143    fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
32144        // The canonical per-`:politicas :rate-limit` `:window`
32145        // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
32146        // pin: [`RateLimit::window`] must return the
32147        // `:politicas :rate-limit :window` typed `Duration` verbatim,
32148        // byte-equal to the raw field access across every
32149        // representative value in the accept-set — `Duration::from_secs(1)`
32150        // (the `"s"` canonical window, the lower row of
32151        // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
32152        // [`AplicacaoSpec::validate_politicas`] gate accepts via
32153        // [`is_canonical_rate_limit_window`]),
32154        // `Duration::from_secs(60)` (the `"m"` canonical window, the
32155        // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
32156        // window, the upper row), `Duration::ZERO` (a past-the-guard
32157        // sentinel that pins the accessor doesn't perform a silent
32158        // bounds-collapse into `Duration::from_secs(1)` on the zero
32159        // arm — validate rejects an off-set window through
32160        // `PolicyRateLimitWindowNotCanonical` but the accessor must
32161        // ship the raw slot verbatim so a validate-time gate
32162        // regression surfaces at the emit boundary rather than being
32163        // silently absorbed), `Duration::from_millis(500)` (a
32164        // sub-canonical past-the-guard sentinel that pins the accessor
32165        // doesn't silently normalize a non-canonical fractional
32166        // magnitude onto the nearest canonical row).
32167        //
32168        // Second sub-struct required-scalar accessor pin on the
32169        // `RateLimit` axis — sibling in shape to the just-landed
32170        // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
32171        // accessor pin on the peer per-sub-struct required-axis,
32172        // extended onto the per-`RateLimit` required-`Duration` axis.
32173        // Pins against a future silent detour that re-derived the
32174        // refill period from a peer axis (an accidental
32175        // `Duration::from_secs(self.rate as u64)` collapse that read
32176        // the rate-limit token capacity as a refill-interval
32177        // duration), a `Duration::ZERO → Duration::from_secs(1)`
32178        // canonical-default projection (which would silently absorb
32179        // the `PolicyRateLimitWindowNotCanonical` refusal case at the
32180        // accessor boundary), or a canonical-set-collapsing accessor
32181        // that clamped the return through [`rate_limit_window_unit`]
32182        // (the `AplicacaoSpec::validate` gate owns the canonical-set
32183        // membership; the accessor must ship the raw slot verbatim).
32184        for window in [
32185            Duration::from_secs(1),
32186            Duration::from_secs(60),
32187            Duration::from_secs(3600),
32188            Duration::ZERO,
32189            Duration::from_millis(500),
32190        ] {
32191            let rl = RateLimit { rate: 100, window };
32192            assert_eq!(
32193                rl.window(),
32194                window,
32195                "RateLimit::window must return :politicas :rate-limit :window \
32196                 verbatim (got {:?}, expected {window:?})",
32197                rl.window(),
32198            );
32199            assert_eq!(
32200                rl.window(),
32201                rl.window,
32202                "RateLimit::window must byte-equal the raw .window field \
32203                 access across every value in the Duration accept-set",
32204            );
32205        }
32206    }
32207
32208    #[test]
32209    fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
32210        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
32211        // `:rate-limit :window` canonical-set arm must key off
32212        // [`RateLimit::window`], not the raw `.window` field access.
32213        // Structurally: a `RateLimit { window: Duration::from_millis(500),
32214        // .. }` embedded in a `:politicas :rate-limit` slot must
32215        // surface the `PolicyRateLimitWindowNotCanonical` refusal
32216        // exactly (with the sub-canonical `Duration::from_millis(500)`
32217        // magnitude carried through verbatim), and a `RateLimit
32218        // { window: Duration::from_secs(1), .. }` (the lower row of
32219        // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
32220        // The pair jointly pins the accessor + validate-gate
32221        // composition: any future silent detour that had the accessor
32222        // normalize the off-set window to the nearest canonical row
32223        // (a `.window().max(Duration::from_secs(1))` collapse, or a
32224        // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
32225        // collapse) would silently absorb the
32226        // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
32227        // boundary — including a drift in the error's `window` payload
32228        // (the emit-side diagnostic reader keys off the offending
32229        // magnitude verbatim, so a normalization at the accessor
32230        // boundary would silently pin the wrong magnitude in the
32231        // refusal). The composition pin catches that at caixa-core
32232        // build time.
32233        //
32234        // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
32235        // (7f81a60) accessor-composition pin on the peer required-
32236        // scalar `:rate` axis — same "the validate / shape-gate
32237        // predicate must route through the substrate-primitive typed
32238        // dispatch, and the error payload must project through the
32239        // same accessor" discipline extended onto the peer
32240        // per-`RateLimit` required-`Duration` composition axis.
32241        let mut spec = three_member_spec();
32242        spec.politicas = MeshPolicy {
32243            rate_limit: Some(RateLimit {
32244                rate: 100,
32245                window: Duration::from_millis(500),
32246            }),
32247            ..MeshPolicy::default()
32248        };
32249        match spec.validate() {
32250            Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
32251                assert_eq!(
32252                    window,
32253                    Duration::from_millis(500),
32254                    "PolicyRateLimitWindowNotCanonical must carry the \
32255                     offending :window magnitude verbatim through the \
32256                     accessor — got {window:?}, expected 500ms",
32257                );
32258            }
32259            other => panic!(
32260                "validate_politicas must reject non-canonical :window \
32261                 with PolicyRateLimitWindowNotCanonical — the accessor \
32262                 and the validate gate must route through the same \
32263                 substrate-primitive typed dispatch on the :window \
32264                 canonical-set arm; got {other:?}",
32265            ),
32266        }
32267        spec.politicas = MeshPolicy {
32268            rate_limit: Some(RateLimit {
32269                rate: 100,
32270                window: Duration::from_secs(1),
32271            }),
32272            ..MeshPolicy::default()
32273        };
32274        assert!(
32275            spec.validate().is_ok(),
32276            "validate_politicas must accept window == Duration::from_secs(1) \
32277             (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
32278        );
32279    }
32280
32281    #[test]
32282    fn rate_limit_window_projects_duration_by_copy() {
32283        // The by-copy pin: [`RateLimit::window`] returns `Duration`
32284        // by copy — `Duration` is `Copy` and the accessor must return
32285        // by value, not by reference. Peer of the sibling per-`RateLimit`
32286        // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
32287        // required-scalar `:rate` axis, extended onto the peer
32288        // per-`RateLimit` required-`Duration` copy-invariant shape —
32289        // the accessor's returned `Duration` must outlive `&self`
32290        // (multiple calls must return equal values from a
32291        // dropped-`&self` copy, since the returned scalar carries no
32292        // borrow), and calling the accessor twice on the same
32293        // RateLimit must yield the same `Duration` verbatim
32294        // (idempotent, no side effects on `&self`).
32295        //
32296        // Pins against a future silent detour that returned
32297        // `&Duration` (which would type-check but silently break every
32298        // downstream `Duration`-by-value consumer —
32299        // [`is_canonical_rate_limit_window`]'s first parameter is
32300        // `Duration`, and `&Duration` would fold to a detached copy at
32301        // the call site with a `*` deref the sibling accessors don't
32302        // need), an accidental `.window + Duration::ZERO` detour that
32303        // returned a fresh copy through an arithmetic no-op (breaking
32304        // a future `const fn` regression), or a one-arm-only accessor
32305        // that returned a canonical fallback on some sentinel input
32306        // (breaking the pass-through invariant the sibling required-
32307        // scalar accessors carry).
32308        for window in [
32309            Duration::from_secs(1),
32310            Duration::from_secs(60),
32311            Duration::from_secs(3600),
32312            Duration::ZERO,
32313            Duration::from_millis(500),
32314        ] {
32315            let rl = RateLimit { rate: 100, window };
32316            let first = rl.window();
32317            let second = rl.window();
32318            assert_eq!(
32319                first, second,
32320                "RateLimit::window must be idempotent — two successive \
32321                 calls on the same &self must return the same Duration",
32322            );
32323            assert_eq!(
32324                first, window,
32325                "RateLimit::window must return :politicas :rate-limit :window \
32326                 verbatim by copy — got {first:?}, expected {window:?}",
32327            );
32328        }
32329    }
32330
32331    #[test]
32332    fn placement_estrategia_default_pins_m3_canonical_value() {
32333        // Pin [`PLACEMENT_ESTRATEGIA_DEFAULT`] at
32334        // [`PlacementStrategy::Replicated`] — MESH-COMPOSITION §II.2's
32335        // active-active-across-every-named-cluster arm, the closest
32336        // canonical M3 production reference the substrate carries and
32337        // the arm the caixa-mesh `programs.yaml` fan-out already keys off
32338        // for every un-`:placement`-declared Aplicacao. Pinning the arm
32339        // here surfaces a future rebrand of the M3-canonical
32340        // distribution default (a widening to `Sharded` once the
32341        // substrate discovers hash-keyed distribution as the more
32342        // common production shape, a tightening to `SingleNode` for
32343        // stateful Erlang/OTP distributed-app-takeover semantics
32344        // MESH-COMPOSITION §II.1 names, a per-cluster overlay the
32345        // operator pins through a future `:placement-overrides` slot)
32346        // as a deliberate test edit, not a silent contract migration.
32347        // Peer of the sibling M2 per-supervisor value pins
32348        // [`crate::supervisor::tests::supervisor_estrategia_default_pins_otp_canonical_value`]
32349        // /
32350        // [`crate::supervisor::tests::supervisor_child_restart_default_pins_otp_canonical_value`]
32351        // extended onto the M3 mesh-primitive-defining `:placement
32352        // :estrategia` axis.
32353        assert_eq!(PLACEMENT_ESTRATEGIA_DEFAULT, PlacementStrategy::Replicated);
32354    }
32355
32356    #[test]
32357    fn placement_strategy_default_routes_through_lifted_default() {
32358        // Composition pin: the [`Default for PlacementStrategy`] impl's
32359        // return arm must route through the substrate-canonical
32360        // [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
32361        // a raw `Self::Replicated` arm. Prior to the lift the impl
32362        // carried an inline `Self::Replicated` arm with no compile-time
32363        // link back to the shared M3-canonical `Replicated` arm the
32364        // paired [`Default for Placement`] impl's struct-literal
32365        // `estrategia` field, the serde-side `#[serde(default)]` on
32366        // [`Placement::estrategia`] that resolves an author-omitted
32367        // wire-form `:placement :estrategia` scalar through the impl,
32368        // and the [`crate::manifest::Caixa::aplicacao_view`] fold's
32369        // `.unwrap_or_default()` `Option<Placement>` collapse arm (which
32370        // routes through [`Placement::default`] which routes through the
32371        // strategy default) all key off — so a future rebrand of the
32372        // M3-canonical distribution default would have had to be threaded
32373        // through the `Default` impl and the three peer routes in
32374        // lockstep or the four consumers would silently split. Byte-
32375        // parity against the lifted constant closes the split. Peer of
32376        // the sibling
32377        // [`crate::supervisor::tests::restart_strategy_default_routes_through_lifted_default`]
32378        // /
32379        // [`crate::supervisor::tests::restart_policy_default_routes_through_lifted_default`]
32380        // composition pins on the M2 per-supervisor axes.
32381        assert_eq!(PlacementStrategy::default(), PLACEMENT_ESTRATEGIA_DEFAULT);
32382    }
32383
32384    #[test]
32385    fn placement_default_estrategia_routes_through_lifted_default() {
32386        // Composition pin: the [`Default for Placement`] impl's
32387        // struct-literal `estrategia` field must route through the
32388        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
32389        // `pub const` (either directly, or via the [`PlacementStrategy::default`]
32390        // impl that the sibling
32391        // `placement_strategy_default_routes_through_lifted_default` pin
32392        // already routes onto the constant). Structurally: every
32393        // `Placement::default()` call must yield an `estrategia` field
32394        // byte-equal to the lifted constant so the two paired defaults —
32395        // the [`Default for PlacementStrategy`] impl arm and the
32396        // struct-literal default arm here — cannot silently split on any
32397        // future M3-canonical distribution-default rebrand. Peer of the
32398        // sibling M2
32399        // [`crate::supervisor::tests::supervisor_spec_default_estrategia_routes_through_lifted_default`]
32400        // byte-parity pin on the [`Default for SupervisorSpec`]
32401        // struct-literal `estrategia` field extended onto the M3
32402        // mesh-primitive-defining slot family.
32403        assert_eq!(
32404            Placement::default().estrategia,
32405            PLACEMENT_ESTRATEGIA_DEFAULT,
32406        );
32407    }
32408
32409    #[test]
32410    fn placement_serde_default_estrategia_routes_through_lifted_default() {
32411        // Composition pin: the serde-side `#[serde(default)]` on
32412        // [`Placement::estrategia`] — the wire-format author-omitted
32413        // `:placement :estrategia` arm — must resolve onto the substrate-
32414        // canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const`
32415        // (via the [`Default for PlacementStrategy`] impl the sibling
32416        // `placement_strategy_default_routes_through_lifted_default` pin
32417        // already routes onto the constant). Structurally: a `Placement`
32418        // deserialized from a payload that omits the `estrategia` key
32419        // must yield an `estrategia` field byte-equal to the lifted
32420        // constant, so the wire-format author-omitted arm and the
32421        // [`PlacementStrategy::default`] impl arm cannot silently split
32422        // on any future M3-canonical distribution-default rebrand. Peer
32423        // of the sibling M2
32424        // [`crate::supervisor::tests::child_spec_serde_default_restart_routes_through_lifted_default`]
32425        // byte-parity pin on the wire-format author-omitted `:children
32426        // :restart` scalar extended onto the M3 mesh-primitive-defining
32427        // slot family.
32428        let omitted: Placement = serde_json::from_str("{}")
32429            .expect("Placement must deserialize with the estrategia key omitted");
32430        assert_eq!(
32431            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
32432            "an author-omitted :placement :estrategia slot must degrade onto \
32433             the PLACEMENT_ESTRATEGIA_DEFAULT typed pub const (got \
32434             {:?}, expected {:?})",
32435            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
32436        );
32437    }
32438
32439    // ── contrato_target_ctors! fold pins ────────────────────────────────
32440    //
32441    // Fixture edge triple + payload-field-name label pair for every
32442    // `contrato_target_ctors!`-generated ctor pin below. Kept as
32443    // non-default `("cart", "catalog", "wasi:http/proxy")` +
32444    // `WitTarget::HTTP_FIELD_NAME` so a byte-equality mistake against
32445    // the fixture default doesn't silently pass. Peer of the sibling
32446    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
32447    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
32448    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
32449    // `missing_entry_ctor_matches_struct_literal_wrap` /
32450    // `<slot>_ctor_matches_tuple_literal_wrap` equivalence pins on the
32451    // four `LayoutError` constructor families each closed on their
32452    // sibling envelopes.
32453    fn contrato_target_ctor_fixture() -> (String, String, String, &'static str) {
32454        (
32455            "cart".to_string(),
32456            "catalog".to_string(),
32457            "wasi:http/proxy".to_string(),
32458            WitTarget::HTTP_FIELD_NAME,
32459        )
32460    }
32461
32462    #[test]
32463    fn contrato_wrong_target_ctor_matches_struct_literal_wrap() {
32464        // Equivalence pin: the ctor produces byte-equal
32465        // `AplicacaoError::ContratoWrongTarget` to the pre-lift open-
32466        // coded struct-literal on the same edge fixture, so the fold
32467        // cannot silently drift on any future field-addition /
32468        // reordering / string-conversion tweak on the variant. Peer of
32469        // the sibling `entrada_host_invalid_ctor_matches_struct_literal_wrap`
32470        // (17dd504) / the four `LayoutError` family equivalence pins.
32471        let (de, para, wit, expected) = contrato_target_ctor_fixture();
32472        let lifted = AplicacaoError::contrato_wrong_target(
32473            (de.clone(), para.clone(), wit.clone()),
32474            expected,
32475        );
32476        let struct_literal = AplicacaoError::ContratoWrongTarget {
32477            de,
32478            para,
32479            wit,
32480            expected,
32481        };
32482        assert_eq!(lifted, struct_literal);
32483    }
32484
32485    #[test]
32486    fn contrato_missing_target_ctor_matches_struct_literal_wrap() {
32487        // Equivalence pin peer of the sibling
32488        // `contrato_wrong_target_ctor_matches_struct_literal_wrap` above
32489        // on the paired `ContratoMissingTarget` variant of the same
32490        // four-slot envelope shape the `contrato_target_ctors!` macro
32491        // closes.
32492        let (de, para, wit, expected) = contrato_target_ctor_fixture();
32493        let lifted = AplicacaoError::contrato_missing_target(
32494            (de.clone(), para.clone(), wit.clone()),
32495            expected,
32496        );
32497        let struct_literal = AplicacaoError::ContratoMissingTarget {
32498            de,
32499            para,
32500            wit,
32501            expected,
32502        };
32503        assert_eq!(lifted, struct_literal);
32504    }
32505
32506    #[test]
32507    fn contrato_target_ctors_route_edge_triple_through_verbatim() {
32508        // Routing pin: the `(de, para, wit)` triple threads verbatim
32509        // onto same-named fields on both generated ctors, no wrapper-
32510        // side lowercase / trim / re-order. Sweeps a non-default triple
32511        // (`"cart-svc" → "catalog-v2"`, `"nats:pub-sub"`) so any
32512        // wrapper-side transformation surfaces here rather than at a
32513        // downstream diagnostic-shape drift. Sibling of
32514        // `entrada_host_invalid_ctor_routes_host_through_to_string`
32515        // (17dd504) on the paired triple-carrying envelope.
32516        let edge = (
32517            "cart-svc".to_string(),
32518            "catalog-v2".to_string(),
32519            "nats:pub-sub".to_string(),
32520        );
32521        let wrong =
32522            AplicacaoError::contrato_wrong_target(edge.clone(), WitTarget::PUBSUB_FIELD_NAME);
32523        let missing = AplicacaoError::contrato_missing_target(edge, WitTarget::PUBSUB_FIELD_NAME);
32524        let AplicacaoError::ContratoWrongTarget {
32525            de: wde,
32526            para: wpara,
32527            wit: wwit,
32528            ..
32529        } = wrong
32530        else {
32531            panic!("contrato_wrong_target must construct the ContratoWrongTarget variant");
32532        };
32533        let AplicacaoError::ContratoMissingTarget {
32534            de: mde,
32535            para: mpara,
32536            wit: mwit,
32537            ..
32538        } = missing
32539        else {
32540            panic!("contrato_missing_target must construct the ContratoMissingTarget variant");
32541        };
32542        assert_eq!(wde, "cart-svc");
32543        assert_eq!(wpara, "catalog-v2");
32544        assert_eq!(wwit, "nats:pub-sub");
32545        assert_eq!(mde, "cart-svc");
32546        assert_eq!(mpara, "catalog-v2");
32547        assert_eq!(mwit, "nats:pub-sub");
32548    }
32549
32550    #[test]
32551    fn contrato_target_ctors_route_expected_through_verbatim() {
32552        // Routing pin: the `expected: &'static str` label threads
32553        // verbatim (identity, not copy-and-transform) onto the
32554        // `expected` field of both variants, so the four canonical
32555        // labels [`WitTarget::HTTP_FIELD_NAME`] /
32556        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
32557        // / [`WitTarget::CAPABILITY_EXPECTED`] survive the fold as
32558        // pointer-equal (not merely value-equal) references — a wrapper-
32559        // side `.to_string()` / `Cow::Owned` promotion would break the
32560        // `&'static str` contract downstream consumers depend on.
32561        for label in [
32562            WitTarget::HTTP_FIELD_NAME,
32563            WitTarget::PUBSUB_FIELD_NAME,
32564            WitTarget::STORE_FIELD_NAME,
32565            WitTarget::CAPABILITY_EXPECTED,
32566        ] {
32567            let (de, para, wit, _) = contrato_target_ctor_fixture();
32568            let wrong = AplicacaoError::contrato_wrong_target(
32569                (de.clone(), para.clone(), wit.clone()),
32570                label,
32571            );
32572            let missing = AplicacaoError::contrato_missing_target((de, para, wit), label);
32573            match wrong {
32574                AplicacaoError::ContratoWrongTarget { expected, .. } => {
32575                    assert!(
32576                        std::ptr::eq(expected.as_ptr(), label.as_ptr())
32577                            && expected.len() == label.len(),
32578                        "contrato_wrong_target must thread the &'static str \
32579                         label pointer-equal onto the `expected` field \
32580                         (label = {label:?})",
32581                    );
32582                }
32583                other => panic!("expected ContratoWrongTarget, got {other:?}"),
32584            }
32585            match missing {
32586                AplicacaoError::ContratoMissingTarget { expected, .. } => {
32587                    assert!(
32588                        std::ptr::eq(expected.as_ptr(), label.as_ptr())
32589                            && expected.len() == label.len(),
32590                        "contrato_missing_target must thread the &'static \
32591                         str label pointer-equal onto the `expected` field \
32592                         (label = {label:?})",
32593                    );
32594                }
32595                other => panic!("expected ContratoMissingTarget, got {other:?}"),
32596            }
32597        }
32598    }
32599
32600    // ── contrato_empty_pair_ctors! fold pins ────────────────────────────
32601    //
32602    // Fixture edge pair for every `contrato_empty_pair_ctors!`-generated
32603    // ctor pin below. Kept as non-default `("cart", "catalog")` so a
32604    // byte-equality mistake against the fixture default doesn't silently
32605    // pass. Peer of the sibling `contrato_target_ctor_fixture` (14b81d5,
32606    // triple + expected-label envelope on
32607    // `contrato_target_ctors!`) / `entrada_host_invalid_ctor_matches_
32608    // struct_literal_wrap` (17dd504, host + reason envelope on
32609    // `entrada_host_invalid`) / the four `LayoutError` family
32610    // equivalence pins.
32611    fn contrato_empty_pair_ctor_fixture() -> (String, String) {
32612        ("cart".to_string(), "catalog".to_string())
32613    }
32614
32615    #[test]
32616    fn empty_wit_ctor_matches_struct_literal_wrap() {
32617        // Equivalence pin: the ctor produces byte-equal
32618        // `AplicacaoError::EmptyWit` to the pre-lift open-coded
32619        // struct-literal on the same edge pair, so the fold cannot
32620        // silently drift on any future field-addition / reordering /
32621        // string-conversion tweak on the variant. Peer of the sibling
32622        // `contrato_wrong_target_ctor_matches_struct_literal_wrap`
32623        // (14b81d5) / `entrada_host_invalid_ctor_matches_struct_literal_wrap`
32624        // (17dd504) / the four `LayoutError` family equivalence pins.
32625        let (de, para) = contrato_empty_pair_ctor_fixture();
32626        let lifted = AplicacaoError::empty_wit((de.clone(), para.clone()));
32627        let struct_literal = AplicacaoError::EmptyWit { de, para };
32628        assert_eq!(lifted, struct_literal);
32629    }
32630
32631    #[test]
32632    fn contrato_endpoint_empty_ctor_matches_struct_literal_wrap() {
32633        // Equivalence pin peer of the sibling
32634        // `empty_wit_ctor_matches_struct_literal_wrap` above on the
32635        // paired `ContratoEndpointEmpty` variant of the same two-slot
32636        // envelope shape the `contrato_empty_pair_ctors!` macro closes.
32637        let (de, para) = contrato_empty_pair_ctor_fixture();
32638        let lifted = AplicacaoError::contrato_endpoint_empty((de.clone(), para.clone()));
32639        let struct_literal = AplicacaoError::ContratoEndpointEmpty { de, para };
32640        assert_eq!(lifted, struct_literal);
32641    }
32642
32643    #[test]
32644    fn contrato_subject_empty_ctor_matches_struct_literal_wrap() {
32645        // Equivalence pin peer of the sibling
32646        // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
32647        // above on the paired `ContratoSubjectEmpty` variant of the
32648        // same two-slot envelope shape.
32649        let (de, para) = contrato_empty_pair_ctor_fixture();
32650        let lifted = AplicacaoError::contrato_subject_empty((de.clone(), para.clone()));
32651        let struct_literal = AplicacaoError::ContratoSubjectEmpty { de, para };
32652        assert_eq!(lifted, struct_literal);
32653    }
32654
32655    #[test]
32656    fn contrato_slot_empty_ctor_matches_struct_literal_wrap() {
32657        // Equivalence pin peer of the sibling
32658        // `contrato_subject_empty_ctor_matches_struct_literal_wrap`
32659        // above on the paired `ContratoSlotEmpty` variant of the same
32660        // two-slot envelope shape.
32661        let (de, para) = contrato_empty_pair_ctor_fixture();
32662        let lifted = AplicacaoError::contrato_slot_empty((de.clone(), para.clone()));
32663        let struct_literal = AplicacaoError::ContratoSlotEmpty { de, para };
32664        assert_eq!(lifted, struct_literal);
32665    }
32666
32667    #[test]
32668    fn contrato_empty_pair_ctors_route_edge_pair_through_verbatim() {
32669        // Routing pin: the `(de, para)` pair threads verbatim onto
32670        // same-named fields on all four generated ctors, no wrapper-
32671        // side lowercase / trim / re-order. Sweeps a non-default pair
32672        // (`"cart-svc" → "catalog-v2"`) so any wrapper-side
32673        // transformation surfaces here rather than at a downstream
32674        // diagnostic-shape drift. Sibling of
32675        // `contrato_target_ctors_route_edge_triple_through_verbatim`
32676        // (14b81d5) on the paired triple-carrying envelope and of
32677        // `entrada_host_invalid_ctor_routes_host_through_to_string`
32678        // (17dd504) on the sibling `{ host, reason }` envelope.
32679        let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
32680        let variants: [(AplicacaoError, &'static str); 4] = [
32681            (AplicacaoError::empty_wit(edge.clone()), "EmptyWit"),
32682            (
32683                AplicacaoError::contrato_endpoint_empty(edge.clone()),
32684                "ContratoEndpointEmpty",
32685            ),
32686            (
32687                AplicacaoError::contrato_subject_empty(edge.clone()),
32688                "ContratoSubjectEmpty",
32689            ),
32690            (
32691                AplicacaoError::contrato_slot_empty(edge.clone()),
32692                "ContratoSlotEmpty",
32693            ),
32694        ];
32695        for (built, label) in variants {
32696            let (de, para) = match built {
32697                AplicacaoError::EmptyWit { de, para }
32698                | AplicacaoError::ContratoEndpointEmpty { de, para }
32699                | AplicacaoError::ContratoSubjectEmpty { de, para }
32700                | AplicacaoError::ContratoSlotEmpty { de, para } => (de, para),
32701                other => panic!("expected {label} pair variant, got {other:?}"),
32702            };
32703            assert_eq!(de, "cart-svc", "de field on {label} must thread verbatim");
32704            assert_eq!(
32705                para, "catalog-v2",
32706                "para field on {label} must thread verbatim",
32707            );
32708        }
32709    }
32710
32711    // ── contrato_pair_value_reason_ctors! fold pins ─────────────────────
32712    //
32713    // Fixture edge pair + value + reason for every
32714    // `contrato_pair_value_reason_ctors!`-generated ctor pin below. Kept
32715    // as non-default `("cart", "catalog")` on the `(de, para)` pair and
32716    // fixed per-axis `<val>` / reason so a byte-equality mistake against
32717    // the fixture default doesn't silently pass. Peer of the sibling
32718    // `contrato_empty_pair_ctor_fixture` (8580068, pair-only envelope on
32719    // `contrato_empty_pair_ctors!`) / `contrato_target_ctor_fixture`
32720    // (14b81d5, triple + expected-label envelope on
32721    // `contrato_target_ctors!`) / `entrada_host_invalid_ctor_matches_
32722    // struct_literal_wrap` (17dd504, host + reason envelope on
32723    // `entrada_host_invalid`).
32724    fn contrato_pair_value_reason_ctor_fixture() -> (String, String) {
32725        ("cart".to_string(), "catalog".to_string())
32726    }
32727
32728    #[test]
32729    fn contrato_endpoint_invalid_ctor_matches_struct_literal_wrap() {
32730        // Equivalence pin: the ctor produces byte-equal
32731        // `AplicacaoError::ContratoEndpointInvalid` to the pre-lift
32732        // open-coded struct-literal on the same
32733        // `(edge_pair, endpoint, reason)` triple, so the fold cannot
32734        // silently drift on any future field-addition / reordering /
32735        // string-conversion tweak on the variant. Peer of the sibling
32736        // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
32737        // (8580068) on the paired two-slot envelope of the same
32738        // `{ de, para, ... }` prefix, and of
32739        // `entrada_host_invalid_ctor_matches_struct_literal_wrap`
32740        // (17dd504) on the sibling `{ <field>: String, reason: String }`
32741        // two-slot envelope.
32742        let (de, para) = contrato_pair_value_reason_ctor_fixture();
32743        let endpoint = "/charge";
32744        let reason = "sample reason text";
32745        let lifted =
32746            AplicacaoError::contrato_endpoint_invalid((de.clone(), para.clone()), endpoint, reason);
32747        let struct_literal = AplicacaoError::ContratoEndpointInvalid {
32748            de,
32749            para,
32750            endpoint: endpoint.to_string(),
32751            reason: reason.to_string(),
32752        };
32753        assert_eq!(lifted, struct_literal);
32754    }
32755
32756    #[test]
32757    fn contrato_subject_invalid_ctor_matches_struct_literal_wrap() {
32758        // Equivalence pin peer of the sibling
32759        // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap`
32760        // above on the paired `ContratoSubjectInvalid` variant of the
32761        // same four-slot envelope shape the
32762        // `contrato_pair_value_reason_ctors!` macro closes.
32763        let (de, para) = contrato_pair_value_reason_ctor_fixture();
32764        let subject = "checkout.events.charge.failed";
32765        let reason = "sample reason text";
32766        let lifted =
32767            AplicacaoError::contrato_subject_invalid((de.clone(), para.clone()), subject, reason);
32768        let struct_literal = AplicacaoError::ContratoSubjectInvalid {
32769            de,
32770            para,
32771            subject: subject.to_string(),
32772            reason: reason.to_string(),
32773        };
32774        assert_eq!(lifted, struct_literal);
32775    }
32776
32777    #[test]
32778    fn contrato_slot_invalid_ctor_matches_struct_literal_wrap() {
32779        // Equivalence pin peer of the sibling
32780        // `contrato_subject_invalid_ctor_matches_struct_literal_wrap`
32781        // above on the paired `ContratoSlotInvalid` variant of the same
32782        // four-slot envelope shape.
32783        let (de, para) = contrato_pair_value_reason_ctor_fixture();
32784        let slot = "checkout/$orderId";
32785        let reason = "sample reason text";
32786        let lifted =
32787            AplicacaoError::contrato_slot_invalid((de.clone(), para.clone()), slot, reason);
32788        let struct_literal = AplicacaoError::ContratoSlotInvalid {
32789            de,
32790            para,
32791            slot: slot.to_string(),
32792            reason: reason.to_string(),
32793        };
32794        assert_eq!(lifted, struct_literal);
32795    }
32796
32797    #[test]
32798    fn contrato_wit_invalid_ctor_matches_struct_literal_wrap() {
32799        // Equivalence pin peer of the sibling
32800        // `contrato_slot_invalid_ctor_matches_struct_literal_wrap` above
32801        // on the paired `ContratoWitInvalid` variant of the same four-
32802        // slot envelope shape the `contrato_pair_value_reason_ctors!`
32803        // macro closes. Fold pinned this test lands with the last
32804        // `{ de, para, <field>: String, reason: String }` open-coded
32805        // struct-literal inside [`WitContract::target`] rewritten to
32806        // route through the macro-generated
32807        // [`AplicacaoError::contrato_wit_invalid`] ctor — a byte-mismatch
32808        // between the ctor and the pre-lift struct-literal trips this
32809        // pin ahead of any downstream diagnostic-shape drift on the
32810        // `:contratos :wit` axis.
32811        let (de, para) = contrato_pair_value_reason_ctor_fixture();
32812        let wit = "wasi-http/proxy";
32813        let reason = "sample reason text";
32814        let lifted = AplicacaoError::contrato_wit_invalid((de.clone(), para.clone()), wit, reason);
32815        let struct_literal = AplicacaoError::ContratoWitInvalid {
32816            de,
32817            para,
32818            wit: wit.to_string(),
32819            reason: reason.to_string(),
32820        };
32821        assert_eq!(lifted, struct_literal);
32822    }
32823
32824    #[test]
32825    fn contrato_pair_value_reason_ctors_route_edge_pair_through_verbatim() {
32826        // Routing pin: the `(de, para)` pair threads verbatim onto
32827        // same-named fields on all four generated ctors, no wrapper-
32828        // side lowercase / trim / re-order. Sweeps a non-default pair
32829        // (`"cart-svc" → "catalog-v2"`) so any wrapper-side
32830        // transformation surfaces here rather than at a downstream
32831        // diagnostic-shape drift. Sibling of
32832        // `contrato_empty_pair_ctors_route_edge_pair_through_verbatim`
32833        // (8580068) on the paired two-slot envelope and of
32834        // `contrato_target_ctors_route_edge_triple_through_verbatim`
32835        // (14b81d5) on the paired triple-carrying envelope.
32836        let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
32837        let variants: [(AplicacaoError, &'static str); 4] = [
32838            (
32839                AplicacaoError::contrato_endpoint_invalid(edge.clone(), "/x", "r"),
32840                "ContratoEndpointInvalid",
32841            ),
32842            (
32843                AplicacaoError::contrato_subject_invalid(edge.clone(), "x.y", "r"),
32844                "ContratoSubjectInvalid",
32845            ),
32846            (
32847                AplicacaoError::contrato_slot_invalid(edge.clone(), "x/y", "r"),
32848                "ContratoSlotInvalid",
32849            ),
32850            (
32851                AplicacaoError::contrato_wit_invalid(edge.clone(), "wasi:http/proxy", "r"),
32852                "ContratoWitInvalid",
32853            ),
32854        ];
32855        for (built, label) in variants {
32856            let (de, para) = match built {
32857                AplicacaoError::ContratoEndpointInvalid { de, para, .. }
32858                | AplicacaoError::ContratoSubjectInvalid { de, para, .. }
32859                | AplicacaoError::ContratoSlotInvalid { de, para, .. }
32860                | AplicacaoError::ContratoWitInvalid { de, para, .. } => (de, para),
32861                other => panic!("expected {label} pair variant, got {other:?}"),
32862            };
32863            assert_eq!(de, "cart-svc", "de field on {label} must thread verbatim");
32864            assert_eq!(
32865                para, "catalog-v2",
32866                "para field on {label} must thread verbatim",
32867            );
32868        }
32869    }
32870
32871    #[test]
32872    fn contrato_pair_value_reason_ctors_route_reason_through_into_uniformly() {
32873        // Cross-arm invariance pin — the four ctors all route
32874        // `reason: impl Into<String>` verbatim onto their respective
32875        // typed variants through the shared
32876        // [`contrato_pair_value_reason_ctors!`] macro. Sweeps a fixture
32877        // pair (`&str` literal, `format!` output) against every ctor to
32878        // pin that no per-arm wrapper transformation drifted in against
32879        // the uniform macro-generated body. Peer of
32880        // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
32881        // (981060b) on the sibling two-slot envelope's cross-arm sweep.
32882        let edge = || ("cart".to_string(), "catalog".to_string());
32883        let via_literal = "literal reason text";
32884        let via_format = format!("{} reason text", "literal");
32885        assert_eq!(
32886            AplicacaoError::contrato_endpoint_invalid(edge(), "/e", via_literal),
32887            AplicacaoError::contrato_endpoint_invalid(edge(), "/e", via_format.clone()),
32888        );
32889        assert_eq!(
32890            AplicacaoError::contrato_subject_invalid(edge(), "s.t", via_literal),
32891            AplicacaoError::contrato_subject_invalid(edge(), "s.t", via_format.clone()),
32892        );
32893        assert_eq!(
32894            AplicacaoError::contrato_slot_invalid(edge(), "k/v", via_literal),
32895            AplicacaoError::contrato_slot_invalid(edge(), "k/v", via_format.clone()),
32896        );
32897        assert_eq!(
32898            AplicacaoError::contrato_wit_invalid(edge(), "wasi:http/proxy", via_literal),
32899            AplicacaoError::contrato_wit_invalid(edge(), "wasi:http/proxy", via_format),
32900        );
32901    }
32902
32903    // ── contrato_endpoint_not_absolute standalone ctor pins ─────────────
32904    //
32905    // Fail-before-pass-after pins for the standalone
32906    // [`AplicacaoError::contrato_endpoint_not_absolute`] inherent ctor
32907    // (see the paired doc-block above the ctor definition) — the fold of
32908    // the last open-coded three-slot `{ de, para, endpoint: <val>
32909    // .to_string() }` struct-literal inside [`WitContract::target`]'s
32910    // HTTP-arm leading-slash gate onto one substrate primitive on the
32911    // envelope. A byte-mismatched ctor body would trip the equivalence
32912    // pin first, ahead of any downstream diagnostic-shape drift.
32913    //
32914    // Peer of the sibling standalone-ctor equivalence pins on the peer
32915    // one-off variants across caixa-core:
32916    // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap` +
32917    // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap` above
32918    // on the paired two-slot and four-slot per-`:contratos :endpoint`
32919    // envelopes; `child_caixa_invalid_ctor_matches_struct_literal_wrap`
32920    // and `child_versao_invalid_ctor_matches_struct_literal_wrap`
32921    // (d2ef2ec) on the sibling `SupervisorError` `{ caixa, [versao,]
32922    // reason }` two- and three-slot envelopes; the
32923    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` (17dd504)
32924    // pin on the sibling standalone `{ host, reason }` two-slot ctor.
32925    fn contrato_endpoint_not_absolute_ctor_fixture() -> (String, String) {
32926        ("cart".to_string(), "catalog".to_string())
32927    }
32928
32929    #[test]
32930    fn contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap() {
32931        // Equivalence pin: the ctor produces byte-equal
32932        // `AplicacaoError::ContratoEndpointNotAbsolute` to the pre-lift
32933        // open-coded struct-literal on the same `(edge_pair, endpoint)`
32934        // pair, so the fold cannot silently drift on any future
32935        // field-addition / reordering / string-conversion tweak on the
32936        // variant. Same equivalence-pin shape as the sibling
32937        // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
32938        // (8580068) on the paired two-slot envelope and
32939        // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap`
32940        // (14e13f1) on the paired four-slot envelope of the same
32941        // `{ de, para, ... }`-prefix `:endpoint` axis.
32942        let (de, para) = contrato_endpoint_not_absolute_ctor_fixture();
32943        let endpoint = "charge";
32944        let lifted =
32945            AplicacaoError::contrato_endpoint_not_absolute((de.clone(), para.clone()), endpoint);
32946        let struct_literal = AplicacaoError::ContratoEndpointNotAbsolute {
32947            de,
32948            para,
32949            endpoint: endpoint.to_string(),
32950        };
32951        assert_eq!(lifted, struct_literal);
32952    }
32953
32954    #[test]
32955    fn contrato_endpoint_not_absolute_ctor_routes_edge_pair_through_verbatim() {
32956        // Routing pin on the `(de, para)` axis: sweep a non-default
32957        // pair (`"cart-svc" → "catalog-v2"`) so any wrapper-side
32958        // lowercase / trim / re-order surfaces here rather than at a
32959        // downstream diagnostic-shape drift. Peer of
32960        // `contrato_empty_pair_ctors_route_edge_pair_through_verbatim`
32961        // (8580068) on the paired two-slot envelope and
32962        // `contrato_pair_value_reason_ctors_route_edge_pair_through_verbatim`
32963        // (14e13f1) on the paired four-slot envelope of the same
32964        // `{ de, para, ... }`-prefix `:contratos` axis.
32965        let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
32966        let built = AplicacaoError::contrato_endpoint_not_absolute(edge, "charge");
32967        match built {
32968            AplicacaoError::ContratoEndpointNotAbsolute { de, para, .. } => {
32969                assert_eq!(de, "cart-svc", "de field must thread verbatim");
32970                assert_eq!(para, "catalog-v2", "para field must thread verbatim");
32971            }
32972            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
32973        }
32974    }
32975
32976    #[test]
32977    fn contrato_endpoint_not_absolute_ctor_routes_endpoint_through_to_string() {
32978        // Routing pin on the `endpoint: &str` axis: sweep a non-default
32979        // value (`"charge"` — no leading `/`, the exact shape the
32980        // [`WitContract::target`] HTTP-arm leading-slash gate rejects)
32981        // through the sole payload-carrier constructor axis so any
32982        // wrapper-side transformation on the `endpoint.to_string()`
32983        // one-field construction surfaces here rather than at a
32984        // downstream diagnostic-shape mismatch. Sibling of
32985        // `contrato_pair_value_reason_ctors_route_reason_through_into_uniformly`
32986        // (14e13f1) on the sibling four-slot envelope's payload-carrier
32987        // routing pin.
32988        let edge = || ("cart".to_string(), "catalog".to_string());
32989        let via_literal = "charge";
32990        let via_string = String::from("charge");
32991        assert_eq!(
32992            AplicacaoError::contrato_endpoint_not_absolute(edge(), via_literal),
32993            AplicacaoError::contrato_endpoint_not_absolute(edge(), via_string.as_str()),
32994        );
32995    }
32996
32997    // ── contrato_self_loop standalone ctor pins ─────────────────────────
32998    //
32999    // Fail-before-pass-after pins for the standalone
33000    // [`AplicacaoError::contrato_self_loop`] inherent ctor (see the paired
33001    // doc-block above the ctor definition) — the fold of the last
33002    // open-coded two-slot `{ caixa: <ct>.source().to_string(), wit:
33003    // <ct>.world_ref().to_string() }` struct-literal inside
33004    // [`AplicacaoSpec::validate_contratos`]'s per-`:contratos` self-edge
33005    // arm onto one substrate primitive on the [`AplicacaoError`]
33006    // envelope, projecting through the paired [`WitContract::source`] /
33007    // [`WitContract::world_ref`] scalar accessors on the substrate
33008    // primitive. A byte-mismatched ctor body would trip the equivalence
33009    // pin first, ahead of any downstream diagnostic-shape drift.
33010    //
33011    // Peer of the sibling standalone-ctor equivalence pins on the peer
33012    // one-off variants across caixa-core:
33013    // `contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap`
33014    // (cdf1a2c) above on the paired three-slot `{ de, para, endpoint }`
33015    // envelope, the sibling
33016    // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap` +
33017    // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap` on
33018    // the paired two-slot and four-slot per-`:contratos :endpoint`
33019    // envelopes, and the sibling
33020    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` (17dd504)
33021    // pin on the sibling standalone `{ host, reason }` two-slot ctor.
33022    fn contrato_self_loop_ctor_fixture() -> WitContract {
33023        WitContract {
33024            de: "cart".to_string(),
33025            para: "cart".to_string(),
33026            wit: "wasi:http/proxy".to_string(),
33027            endpoint: Some("/self".to_string()),
33028            subject: None,
33029            slot: None,
33030        }
33031    }
33032
33033    #[test]
33034    fn contrato_self_loop_ctor_matches_struct_literal_wrap() {
33035        // Equivalence pin: the ctor produces byte-equal
33036        // `AplicacaoError::ContratoSelfLoop` to the pre-lift open-coded
33037        // struct-literal that read the same two fields through
33038        // [`WitContract::source`] and [`WitContract::world_ref`]. Guards
33039        // any future field-addition / reordering / string-conversion
33040        // tweak on the variant. Same equivalence-pin shape as the
33041        // sibling `contrato_endpoint_not_absolute_ctor_matches_
33042        // struct_literal_wrap` (cdf1a2c) on the paired three-slot
33043        // per-`:contratos :endpoint` envelope.
33044        let contract = contrato_self_loop_ctor_fixture();
33045        let lifted = AplicacaoError::contrato_self_loop(&contract);
33046        let struct_literal = AplicacaoError::ContratoSelfLoop {
33047            caixa: contract.source().to_string(),
33048            wit: contract.world_ref().to_string(),
33049        };
33050        assert_eq!(lifted, struct_literal);
33051    }
33052
33053    #[test]
33054    fn contrato_self_loop_ctor_routes_source_and_world_ref_through_verbatim() {
33055        // Routing pin sweeping non-default `caixa` and `:wit` values
33056        // (`"catalog-v2"` / `"nats:pub-sub"`) through the paired
33057        // [`WitContract::source`] / [`WitContract::world_ref`] accessor
33058        // axes so any wrapper-side lowercase / trim / re-order surfaces
33059        // here rather than at a downstream diagnostic-shape drift.
33060        // Peer of the sibling
33061        // `contrato_endpoint_not_absolute_ctor_routes_edge_pair_through_verbatim`
33062        // (cdf1a2c) routing pin on the sibling three-slot envelope.
33063        let contract = WitContract {
33064            de: "catalog-v2".to_string(),
33065            para: "catalog-v2".to_string(),
33066            wit: "nats:pub-sub".to_string(),
33067            endpoint: None,
33068            subject: Some("orders.>".to_string()),
33069            slot: None,
33070        };
33071        let built = AplicacaoError::contrato_self_loop(&contract);
33072        match built {
33073            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
33074                assert_eq!(
33075                    caixa, "catalog-v2",
33076                    "caixa slot must thread WitContract::source() verbatim"
33077                );
33078                assert_eq!(
33079                    wit, "nats:pub-sub",
33080                    "wit slot must thread WitContract::world_ref() verbatim"
33081                );
33082            }
33083            other => panic!("expected ContratoSelfLoop, got {other:?}"),
33084        }
33085    }
33086
33087    #[test]
33088    fn contrato_self_loop_ctor_projects_source_field_not_destination() {
33089        // Accessor-fidelity pin: the ctor's `caixa` slot keys off the
33090        // [`WitContract::source`] accessor (matching the pre-lift open-
33091        // coded body's field selection), not [`WitContract::destination`].
33092        // Under today's `WitContract::is_self_loop()`-gated call site
33093        // the two are equal by that predicate's own contract, but a
33094        // future consumer that constructs the ctor against a not-yet-
33095        // gated candidate contract — an M4
33096        // `mesh.pleme.io/v1alpha1/Aplicacao` CR admission webhook re-
33097        // checking a per-`(:de, :para)`-patched candidate before the
33098        // self-loop gate re-fires, a per-tenant per-Aplicacao overlay
33099        // resolver rejecting a self-edge introduced by a cluster-local
33100        // `:contratos` override — needs the pre-lift field selection
33101        // pinned so a silent `.destination()` swap at the ctor body
33102        // surfaces here rather than at a downstream diagnostic mis-
33103        // attribution far from the self-loop diagnostic's owner
33104        // (the `caller` side per MESH-COMPOSITION §III.1's typed edge
33105        // direction).
33106        //
33107        // Deliberately constructs a non-self-loop pair (`"cart" →
33108        // "catalog"`) so the two accessors yield distinct bytes on the
33109        // fixture — a `.destination()` swap at the ctor body would land
33110        // `"catalog"` in the `caixa` slot instead of `"cart"` and trip
33111        // the assertion here.
33112        let contract = WitContract {
33113            de: "cart".to_string(),
33114            para: "catalog".to_string(),
33115            wit: "wasi:http/proxy".to_string(),
33116            endpoint: Some("/charge".to_string()),
33117            subject: None,
33118            slot: None,
33119        };
33120        let built = AplicacaoError::contrato_self_loop(&contract);
33121        match built {
33122            AplicacaoError::ContratoSelfLoop { caixa, .. } => {
33123                assert_eq!(
33124                    caixa, "cart",
33125                    "caixa slot must project WitContract::source() (not destination)"
33126                );
33127            }
33128            other => panic!("expected ContratoSelfLoop, got {other:?}"),
33129        }
33130    }
33131
33132    // Per-variant equivalence pins for the [`aplicacao_caixa_only_ctors!`]
33133    // macro definition (see the paired doc-block above the macro definition)
33134    // — every generated `<ctor>(caixa: &str) -> Self` constructor folds the
33135    // uniform `Self::<Variant> { caixa: caixa.to_string() }` one-field
33136    // struct-literal onto one substrate primitive. The four per-variant
33137    // equivalence pins below (fail-before-pass-after by construction — a
33138    // byte-mismatched macro arm would trip its equivalence pin first) lock
33139    // each generated constructor to its struct-literal peer under
33140    // `PartialEq`, so every wire-up in [`WitContract::require_endpoints_in`],
33141    // [`AplicacaoSpec::validate_membros`], and
33142    // [`validate_no_self_membership`] on that variant produces a byte-equal
33143    // `AplicacaoError` to the pre-lift open-coded struct-literal. The
33144    // cross-axis pin that follows (non-default caixa name) routes the sole
33145    // constructor input axis through `.to_string()`, so the fold does not
33146    // silently collapse onto a fixed name.
33147    //
33148    // Peer of the sibling per-variant `<ctor>_matches_struct_literal_wrap`
33149    // and cross-axis `<macro>_route_caixa_through_to_string` pins on the
33150    // sibling `SupervisorError` `{ caixa: String }` envelope (db09650,
33151    // `supervisor_caixa_only_ctors!`), sibling of the peer per-variant +
33152    // cross-axis pins on the peer three `AplicacaoError` sub-family folds
33153    // (14b81d5 / 8580068 / 981060b / 14e13f1), sibling of the peer four
33154    // `LayoutError` families (131ca0d / 0419438 / 1b09f9d / 3fe3dd7), sibling
33155    // of the peer M2 `:behavior` envelope fold (67c31ec,
33156    // `behavior_slot_path_ctors!` `{ slot, path }`), sibling of the peer M2
33157    // `:upgrade-from` envelope folds (8e67041 / 7468ca9), and sibling of the
33158    // peer `DepError` envelope folds (792aa92 / f85f145 / 0e35793).
33159
33160    #[test]
33161    fn contrato_member_missing_ctor_matches_struct_literal_wrap() {
33162        assert_eq!(
33163            AplicacaoError::contrato_member_missing("cart"),
33164            AplicacaoError::ContratoMemberMissing {
33165                caixa: "cart".to_string(),
33166            },
33167            "generated contrato_member_missing ctor must produce byte-equal \
33168             AplicacaoError to the open-coded struct-literal wrap on the \
33169             same &str fixture",
33170        );
33171    }
33172
33173    #[test]
33174    fn membro_versao_empty_ctor_matches_struct_literal_wrap() {
33175        assert_eq!(
33176            AplicacaoError::membro_versao_empty("cart"),
33177            AplicacaoError::MembroVersaoEmpty {
33178                caixa: "cart".to_string(),
33179            },
33180            "generated membro_versao_empty ctor must produce byte-equal \
33181             AplicacaoError to the open-coded struct-literal wrap on the \
33182             same &str fixture",
33183        );
33184    }
33185
33186    #[test]
33187    fn membro_duplicate_ctor_matches_struct_literal_wrap() {
33188        assert_eq!(
33189            AplicacaoError::membro_duplicate("cart"),
33190            AplicacaoError::MembroDuplicate {
33191                caixa: "cart".to_string(),
33192            },
33193            "generated membro_duplicate ctor must produce byte-equal \
33194             AplicacaoError to the open-coded struct-literal wrap on the \
33195             same &str fixture",
33196        );
33197    }
33198
33199    #[test]
33200    fn membro_is_self_aplicacao_ctor_matches_struct_literal_wrap() {
33201        assert_eq!(
33202            AplicacaoError::membro_is_self_aplicacao("checkout"),
33203            AplicacaoError::MembroIsSelfAplicacao {
33204                caixa: "checkout".to_string(),
33205            },
33206            "generated membro_is_self_aplicacao ctor must produce byte-equal \
33207             AplicacaoError to the open-coded struct-literal wrap on the \
33208             same &str fixture",
33209        );
33210    }
33211
33212    #[test]
33213    fn aplicacao_caixa_only_ctors_route_caixa_through_to_string() {
33214        // Cross-axis pin: sweep the sole constructor input axis (`caixa:
33215        // &str`) through a non-default fixture name against every generated
33216        // arm in the [`aplicacao_caixa_only_ctors!`] macro, so any
33217        // wrapper-side lowercase / trim / truncate / re-order on the
33218        // `caixa.to_string()` sole-field construction surfaces here rather
33219        // than at a downstream diagnostic-shape mismatch. Peer of the
33220        // sibling `supervisor_caixa_only_ctors_route_caixa_through_to_string`
33221        // cross-axis pin on the sibling `SupervisorError` `{ caixa: String }`
33222        // envelope (db09650), extended here onto the peer `AplicacaoError`
33223        // `{ caixa: String }` envelope so every substrate-primitive ctor
33224        // family in caixa-core carrying a single-slot `{ caixa: String }`
33225        // shape guarantees the sole-field construction routes the caller's
33226        // `&str` through `.to_string()` verbatim.
33227        let name = "cache-v2";
33228        assert_eq!(
33229            AplicacaoError::contrato_member_missing(name),
33230            AplicacaoError::ContratoMemberMissing {
33231                caixa: name.to_string(),
33232            },
33233        );
33234        assert_eq!(
33235            AplicacaoError::membro_versao_empty(name),
33236            AplicacaoError::MembroVersaoEmpty {
33237                caixa: name.to_string(),
33238            },
33239        );
33240        assert_eq!(
33241            AplicacaoError::membro_duplicate(name),
33242            AplicacaoError::MembroDuplicate {
33243                caixa: name.to_string(),
33244            },
33245        );
33246        assert_eq!(
33247            AplicacaoError::membro_is_self_aplicacao(name),
33248            AplicacaoError::MembroIsSelfAplicacao {
33249                caixa: name.to_string(),
33250            },
33251        );
33252    }
33253
33254    #[test]
33255    fn entrada_path_not_absolute_ctor_matches_struct_literal_wrap() {
33256        assert_eq!(
33257            AplicacaoError::entrada_path_not_absolute("api/cart"),
33258            AplicacaoError::EntradaPathNotAbsolute {
33259                path: "api/cart".to_string(),
33260            },
33261            "generated entrada_path_not_absolute ctor must produce byte-equal \
33262             AplicacaoError to the open-coded struct-literal wrap on the \
33263             same &str fixture",
33264        );
33265    }
33266
33267    #[test]
33268    fn entrada_path_duplicate_ctor_matches_struct_literal_wrap() {
33269        assert_eq!(
33270            AplicacaoError::entrada_path_duplicate("/api/cart"),
33271            AplicacaoError::EntradaPathDuplicate {
33272                path: "/api/cart".to_string(),
33273            },
33274            "generated entrada_path_duplicate ctor must produce byte-equal \
33275             AplicacaoError to the open-coded struct-literal wrap on the \
33276             same &str fixture",
33277        );
33278    }
33279
33280    // ── membro_versao_invalid ctor pins ────────────────────────────────
33281    //
33282    // Per-variant byte-equality + cross-axis routing pins guaranteeing the
33283    // lifted [`AplicacaoError::membro_versao_invalid`] inherent constructor
33284    // produces an `AplicacaoError` structurally identical to the pre-lift
33285    // `Self::MembroVersaoInvalid { caixa: caixa.to_string(), versao:
33286    // versao.to_string(), reason: reason.into() }` open-coded three-slot
33287    // struct-literal on the same `(&str, &str, reason)` fixture. Peer of
33288    // the sibling `child_versao_invalid_ctor_matches_struct_literal_wrap` +
33289    // `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
33290    // pins on the peer `SupervisorError` `{ caixa: String, versao: String,
33291    // reason: String }` envelope's per-`:children :versao` axis (d2ef2ec),
33292    // extended here onto the paired per-`:membros :versao` axis on the
33293    // sibling `AplicacaoError` envelope so both three-slot `{ caixa,
33294    // versao, reason }` per-caixa-versao-invalidation ctors on caixa-core's
33295    // typed-error surface guarantee the shared three-field construction
33296    // routes through one substrate primitive per envelope.
33297
33298    #[test]
33299    fn membro_versao_invalid_ctor_matches_struct_literal_wrap() {
33300        let caixa = "cart";
33301        let versao = "not-a-req";
33302        let reason = "sample reason text";
33303        assert_eq!(
33304            AplicacaoError::membro_versao_invalid(caixa, versao, reason),
33305            AplicacaoError::MembroVersaoInvalid {
33306                caixa: caixa.to_string(),
33307                versao: versao.to_string(),
33308                reason: reason.to_string(),
33309            },
33310            "lifted membro_versao_invalid ctor must produce byte-equal \
33311             AplicacaoError to the open-coded struct-literal wrap on the \
33312             same (&str, &str, reason) fixture",
33313        );
33314    }
33315
33316    #[test]
33317    fn membro_versao_invalid_ctor_routes_caixa_and_versao_through_to_string() {
33318        // Cross-axis pin: sweep the two `&str`-shaped constructor input
33319        // axes (`caixa`, `versao`) through non-default fixtures so any
33320        // wrapper-side lowercase / trim / truncate / re-order on either
33321        // `.to_string()` field construction surfaces here rather than at
33322        // a downstream diagnostic-shape mismatch. Peer of the sibling
33323        // `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
33324        // routing pin on the peer `SupervisorError` envelope.
33325        let caixa = "Cart-V2";
33326        let versao = "0.1.0-alpha+build.42";
33327        let reason = "constructed reason";
33328        let err = AplicacaoError::membro_versao_invalid(caixa, versao, reason);
33329        let AplicacaoError::MembroVersaoInvalid {
33330            caixa: got_caixa,
33331            versao: got_versao,
33332            reason: got_reason,
33333        } = err
33334        else {
33335            panic!("membro_versao_invalid must construct MembroVersaoInvalid variant");
33336        };
33337        assert_eq!(got_caixa, caixa.to_string());
33338        assert_eq!(got_versao, versao.to_string());
33339        assert_eq!(got_reason, reason.to_string());
33340    }
33341
33342    #[test]
33343    fn membro_versao_invalid_ctor_routes_reason_through_into() {
33344        // Route pin: the `reason: impl Into<String>` bound accepts both
33345        // `&str` literals and `format!(…)` / `String` outputs verbatim,
33346        // matching the sibling
33347        // `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
33348        // routing pin on the peer `SupervisorError::child_versao_invalid`.
33349        // Pins the sole `AplicacaoSpec::validate_membros` wire-up's
33350        // `require_valid_versao_requirement`-delivered `reason` closure
33351        // parameter (typed `String`) picks the ctor up without a per-arm
33352        // wrapper transformation, and every future consumer that
33353        // constructs the variant from a `format!(…)` reason surfaces
33354        // byte-equal to the `&str`-literal path.
33355        let caixa = "cart";
33356        let versao = "not-a-req";
33357        let from_literal = AplicacaoError::membro_versao_invalid(caixa, versao, "literal reason");
33358        let from_format =
33359            AplicacaoError::membro_versao_invalid(caixa, versao, format!("{} reason", "literal"));
33360        let from_string =
33361            AplicacaoError::membro_versao_invalid(caixa, versao, "literal reason".to_string());
33362        assert_eq!(from_literal, from_format);
33363        assert_eq!(from_literal, from_string);
33364    }
33365
33366    #[test]
33367    fn aplicacao_path_only_ctors_route_path_through_to_string() {
33368        // Cross-axis pin: sweep the sole constructor input axis (`path:
33369        // &str`) through a non-default fixture path against every generated
33370        // arm in the [`aplicacao_path_only_ctors!`] macro, so any
33371        // wrapper-side lowercase / trim / truncate / re-order on the
33372        // `path.to_string()` sole-field construction surfaces here rather
33373        // than at a downstream diagnostic-shape mismatch. Peer of the
33374        // sibling `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
33375        // cross-axis pin on the peer `AplicacaoError` `{ caixa: String }`
33376        // envelope (d9f6867), extended here onto the sibling
33377        // `AplicacaoError` `{ path: String }` envelope so every substrate-
33378        // primitive ctor family in caixa-core carrying a single-slot
33379        // `{ <slot>: String }` shape guarantees the sole-field construction
33380        // routes the caller's `&str` through `.to_string()` verbatim.
33381        let path = "/api/v2/checkout";
33382        assert_eq!(
33383            AplicacaoError::entrada_path_not_absolute(path),
33384            AplicacaoError::EntradaPathNotAbsolute {
33385                path: path.to_string(),
33386            },
33387        );
33388        assert_eq!(
33389            AplicacaoError::entrada_path_duplicate(path),
33390            AplicacaoError::EntradaPathDuplicate {
33391                path: path.to_string(),
33392            },
33393        );
33394    }
33395
33396    // ── aplicacao_policy_scalar_ctors! per-variant + cross-axis pins ────────
33397    //
33398    // Per-variant byte-equality pins guaranteeing every generated ctor arm in
33399    // the [`aplicacao_policy_scalar_ctors!`] macro produces an `AplicacaoError`
33400    // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
33401    // one-line struct-literal on the same `Copy`-`Duration | u32` fixture, plus
33402    // one cross-axis sweep that routes each per-variant `<field>: <ty>` scalar
33403    // through the sole `$field:ident: $ty:ty` axis the macro exposes so any
33404    // wrapper-side truncation / re-order / silent `.into()` / silent constant-
33405    // substitution on any one variant surfaces here rather than at a downstream
33406    // per-`:politicas` diagnostic-shape drift. Peer of the sibling per-variant
33407    // pins on `aplicacao_field_reason_ctors!` (981060b),
33408    // `aplicacao_caixa_only_ctors!` (d9f6867), `aplicacao_path_only_ctors!`
33409    // (3ba8de6), `contrato_pair_value_reason_ctors!` (14e13f1),
33410    // `contrato_empty_pair_ctors!` (8580068), `contrato_target_ctors!`
33411    // (14b81d5), plus the sibling `DepError` / `SupervisorError` /
33412    // `LayoutError` / `LimitsError` / `BehaviorError` / `UpgradeError`
33413    // per-envelope ctor-macro pins.
33414
33415    #[test]
33416    fn policy_timeout_not_canonical_ctor_matches_struct_literal_wrap() {
33417        let timeout = Duration::from_micros(1_500);
33418        assert_eq!(
33419            AplicacaoError::policy_timeout_not_canonical(timeout),
33420            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
33421            "generated policy_timeout_not_canonical ctor must produce byte-equal \
33422             `AplicacaoError::PolicyTimeoutNotCanonical` to the pre-lift \
33423             struct-literal wrap on the same `Copy`-`Duration` fixture",
33424        );
33425    }
33426
33427    #[test]
33428    fn policy_timeout_exceeds_cap_ctor_matches_struct_literal_wrap() {
33429        let timeout = Duration::from_secs(3_601);
33430        assert_eq!(
33431            AplicacaoError::policy_timeout_exceeds_cap(timeout),
33432            AplicacaoError::PolicyTimeoutExceedsCap { timeout },
33433            "generated policy_timeout_exceeds_cap ctor must produce byte-equal \
33434             `AplicacaoError::PolicyTimeoutExceedsCap` to the pre-lift \
33435             struct-literal wrap on the same `Copy`-`Duration` fixture",
33436        );
33437    }
33438
33439    #[test]
33440    fn policy_retries_exceeds_cap_ctor_matches_struct_literal_wrap() {
33441        let retries = 47_u32;
33442        assert_eq!(
33443            AplicacaoError::policy_retries_exceeds_cap(retries),
33444            AplicacaoError::PolicyRetriesExceedsCap { retries },
33445            "generated policy_retries_exceeds_cap ctor must produce byte-equal \
33446             `AplicacaoError::PolicyRetriesExceedsCap` to the pre-lift \
33447             struct-literal wrap on the same `Copy`-`u32` fixture",
33448        );
33449    }
33450
33451    #[test]
33452    fn policy_breaker_max_failures_exceeds_cap_ctor_matches_struct_literal_wrap() {
33453        let max_failures = 1_337_u32;
33454        assert_eq!(
33455            AplicacaoError::policy_breaker_max_failures_exceeds_cap(max_failures),
33456            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
33457            "generated policy_breaker_max_failures_exceeds_cap ctor must produce \
33458             byte-equal `AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` to \
33459             the pre-lift struct-literal wrap on the same `Copy`-`u32` fixture",
33460        );
33461    }
33462
33463    #[test]
33464    fn policy_breaker_window_not_canonical_ctor_matches_struct_literal_wrap() {
33465        let window = Duration::from_micros(500);
33466        assert_eq!(
33467            AplicacaoError::policy_breaker_window_not_canonical(window),
33468            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
33469            "generated policy_breaker_window_not_canonical ctor must produce \
33470             byte-equal `AplicacaoError::PolicyBreakerWindowNotCanonical` to the \
33471             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
33472        );
33473    }
33474
33475    #[test]
33476    fn policy_breaker_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
33477        let window = Duration::from_secs(3_700);
33478        assert_eq!(
33479            AplicacaoError::policy_breaker_window_exceeds_cap(window),
33480            AplicacaoError::PolicyBreakerWindowExceedsCap { window },
33481            "generated policy_breaker_window_exceeds_cap ctor must produce \
33482             byte-equal `AplicacaoError::PolicyBreakerWindowExceedsCap` to the \
33483             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
33484        );
33485    }
33486
33487    #[test]
33488    fn policy_rate_limit_exceeds_cap_ctor_matches_struct_literal_wrap() {
33489        let rate = 1_000_001_u32;
33490        assert_eq!(
33491            AplicacaoError::policy_rate_limit_exceeds_cap(rate),
33492            AplicacaoError::PolicyRateLimitExceedsCap { rate },
33493            "generated policy_rate_limit_exceeds_cap ctor must produce byte-equal \
33494             `AplicacaoError::PolicyRateLimitExceedsCap` to the pre-lift \
33495             struct-literal wrap on the same `Copy`-`u32` fixture",
33496        );
33497    }
33498
33499    #[test]
33500    fn policy_rate_limit_window_not_canonical_ctor_matches_struct_literal_wrap() {
33501        let window = Duration::from_secs(15);
33502        assert_eq!(
33503            AplicacaoError::policy_rate_limit_window_not_canonical(window),
33504            AplicacaoError::PolicyRateLimitWindowNotCanonical { window },
33505            "generated policy_rate_limit_window_not_canonical ctor must produce \
33506             byte-equal `AplicacaoError::PolicyRateLimitWindowNotCanonical` to \
33507             the pre-lift struct-literal wrap on the same `Copy`-`Duration` \
33508             fixture",
33509        );
33510    }
33511
33512    #[test]
33513    fn aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly() {
33514        // Cross-axis routing pin: sweep each generated `<field>: <ty>`
33515        // constructor input axis through a non-default `Copy` fixture against
33516        // every arm in the [`aplicacao_policy_scalar_ctors!`] macro, so any
33517        // wrapper-side silent `.into()` / silent constant-substitution / silent
33518        // field re-name away from the canonical `timeout | retries |
33519        // max_failures | window | rate` axes on any one variant, or a
33520        // `Duration | u32` axis silently rerouted through some other `Copy`
33521        // coercion, surfaces here rather than at a downstream per-`:politicas`
33522        // diagnostic-shape drift. Peer of the sibling
33523        // `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
33524        // (d9f6867), `aplicacao_path_only_ctors_route_path_through_to_string`
33525        // (3ba8de6), `dep_nome_list_ctors_route_nome_and_list_through_uniformly`
33526        // (6f5e0cd), and `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
33527        // (d2ef2ec) cross-axis routing pins on the peer per-envelope ctor
33528        // families, extended here onto the last M3 per-`:politicas` per-axis
33529        // `AplicacaoError` variant family folded onto a substrate primitive.
33530        //
33531        // Fixtures picked out of each variant's accept-set boundary rather
33532        // than the default value so a silent constant-substitution to `0` /
33533        // `Duration::ZERO` / any per-variant sentinel surfaces here on the
33534        // structural-equality assertion. The two `Duration` fixtures pick the
33535        // sub-millisecond and above-cap ends respectively; the three `u32`
33536        // fixtures pick above-cap magnitudes for `retries` / `max_failures` /
33537        // `rate` respectively (each variant's cap sits well below the fixture
33538        // so the pre-lift struct-literal wrap the fixture is compared against
33539        // is the same shape the pre-lift wire-up produced).
33540        let sub_ms = Duration::from_micros(1_500);
33541        let above_hour = Duration::from_secs(3_700);
33542        let non_canonical_rl_window = Duration::from_secs(15);
33543        assert_eq!(
33544            AplicacaoError::policy_timeout_not_canonical(sub_ms),
33545            AplicacaoError::PolicyTimeoutNotCanonical { timeout: sub_ms },
33546        );
33547        assert_eq!(
33548            AplicacaoError::policy_timeout_exceeds_cap(above_hour),
33549            AplicacaoError::PolicyTimeoutExceedsCap {
33550                timeout: above_hour,
33551            },
33552        );
33553        assert_eq!(
33554            AplicacaoError::policy_retries_exceeds_cap(47),
33555            AplicacaoError::PolicyRetriesExceedsCap { retries: 47 },
33556        );
33557        assert_eq!(
33558            AplicacaoError::policy_breaker_max_failures_exceeds_cap(1_337),
33559            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
33560                max_failures: 1_337,
33561            },
33562        );
33563        assert_eq!(
33564            AplicacaoError::policy_breaker_window_not_canonical(sub_ms),
33565            AplicacaoError::PolicyBreakerWindowNotCanonical { window: sub_ms },
33566        );
33567        assert_eq!(
33568            AplicacaoError::policy_breaker_window_exceeds_cap(above_hour),
33569            AplicacaoError::PolicyBreakerWindowExceedsCap { window: above_hour },
33570        );
33571        assert_eq!(
33572            AplicacaoError::policy_rate_limit_exceeds_cap(1_000_001),
33573            AplicacaoError::PolicyRateLimitExceedsCap { rate: 1_000_001 },
33574        );
33575        assert_eq!(
33576            AplicacaoError::policy_rate_limit_window_not_canonical(non_canonical_rl_window),
33577            AplicacaoError::PolicyRateLimitWindowNotCanonical {
33578                window: non_canonical_rl_window,
33579            },
33580        );
33581    }
33582
33583    #[test]
33584    fn aplicacao_policy_scalar_ctors_are_const_zero_runtime_work() {
33585        // Const-eval pin: the [`aplicacao_policy_scalar_ctors!`] macro spells
33586        // every generated ctor `const fn` so a caller can pin an
33587        // `AplicacaoError` at compile time — the same zero-runtime-work
33588        // property the pre-lift `|<slot>| AplicacaoError::<Variant> { <slot> }`
33589        // closure carried on its `Copy`-pass-through construction path (no
33590        // `.to_string()` / `.into()` allocation, no branching). If any future
33591        // edit silently drops the `const` qualifier from the macro body the
33592        // per-arm `const` bindings below fail to compile, which surfaces the
33593        // regression at the substrate-primitive definition rather than at
33594        // some downstream consumer that had come to rely on the `const`-
33595        // constructibility. Peer of the sibling per-variant
33596        // `_ctor_matches_struct_literal_wrap` pins above on the runtime-
33597        // equality axis; this pin closes the compile-time-const axis on the
33598        // same generated family.
33599        const TIMEOUT_NC: AplicacaoError =
33600            AplicacaoError::policy_timeout_not_canonical(Duration::from_micros(1));
33601        const TIMEOUT_CAP: AplicacaoError =
33602            AplicacaoError::policy_timeout_exceeds_cap(Duration::from_secs(3_601));
33603        const RETRIES_CAP: AplicacaoError = AplicacaoError::policy_retries_exceeds_cap(11);
33604        const MAX_FAIL_CAP: AplicacaoError =
33605            AplicacaoError::policy_breaker_max_failures_exceeds_cap(1_001);
33606        const CB_WIN_NC: AplicacaoError =
33607            AplicacaoError::policy_breaker_window_not_canonical(Duration::from_micros(1));
33608        const CB_WIN_CAP: AplicacaoError =
33609            AplicacaoError::policy_breaker_window_exceeds_cap(Duration::from_secs(3_601));
33610        const RATE_CAP: AplicacaoError = AplicacaoError::policy_rate_limit_exceeds_cap(1_000_001);
33611        const RL_WIN_NC: AplicacaoError =
33612            AplicacaoError::policy_rate_limit_window_not_canonical(Duration::from_secs(15));
33613        assert!(matches!(
33614            TIMEOUT_NC,
33615            AplicacaoError::PolicyTimeoutNotCanonical { .. }
33616        ));
33617        assert!(matches!(
33618            TIMEOUT_CAP,
33619            AplicacaoError::PolicyTimeoutExceedsCap { .. }
33620        ));
33621        assert!(matches!(
33622            RETRIES_CAP,
33623            AplicacaoError::PolicyRetriesExceedsCap { .. }
33624        ));
33625        assert!(matches!(
33626            MAX_FAIL_CAP,
33627            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { .. }
33628        ));
33629        assert!(matches!(
33630            CB_WIN_NC,
33631            AplicacaoError::PolicyBreakerWindowNotCanonical { .. }
33632        ));
33633        assert!(matches!(
33634            CB_WIN_CAP,
33635            AplicacaoError::PolicyBreakerWindowExceedsCap { .. }
33636        ));
33637        assert!(matches!(
33638            RATE_CAP,
33639            AplicacaoError::PolicyRateLimitExceedsCap { .. }
33640        ));
33641        assert!(matches!(
33642            RL_WIN_NC,
33643            AplicacaoError::PolicyRateLimitWindowNotCanonical { .. }
33644        ));
33645    }
33646}